text:
Q: How to prove that a pullback map is linear The following question was left as an exercise in my assignment of Manifolds and I am not able to prove this.
Question: Define the map $T^{*} : L^{k}(W) \to L^{k} (V)$  , where $\alpha \in L^{k}(W)$ defined by $T^{*} (\alpha) ( v_1,...,v_k) = \alpha( T(v_1),...,T(v_k))$. $T^{*} (\alpha)$ is called pullback map of $\alpha$ by $T^{*}$.
Here $L^k (V)= V^{*} \oplus ...\oplus V^{*}$.
$T^{*} (\alpha) (v_1+ w_1,...,v_k +w_k)= \alpha ( T(v_1+w_1) ,...,T(v_k+w_k)) = \alpha( T(v_1) +T(w_1), ..., T(v_k) +T(w_k))$.

But I am not able to prove the RHS equal to $\alpha(T(v_1) ,..., T(v_k) )$ + $\alpha( T(w_1,...,T(w_k))$.

Can you please help me with this?

A: Suffices to explore $k=2$. This is the only way I can make sense of this picture.
I am assuming $\alpha \in W^*\oplus W^*$ means $\alpha : W\oplus W \to \mathbb K$ is bilinear. This means that $T^*\alpha$ is bilinear map, not linear. So, in general, $\alpha \in L^k(W)$ is a $k$-linear map.
Assume $T:V\to W$ is linear. Then
$$
\begin{align*}
 (T^*\alpha)(\lambda u_1+\mu v_1,u_2) &= \alpha (T(\lambda u_1+\mu v_1), Tu_2) \\
&= \alpha (\lambda Tu_1 + \mu Tv_1, Tu_2) \\
&= \alpha (\lambda Tu_1,Tu_2) + \alpha (\mu Tv_1,Tu_2) \\
&= \lambda\alpha (Tu_1,Tu_2) + \mu\alpha (Tv_1,Tv_2) \\
&= \lambda(T^*\alpha)(u_1,u_2) + \mu(T^*\alpha)(v_1,u_2)
\end{align*}
 $$
and similarly for linearity in second component.
And for linearity of $T^*$ one has
$$
\begin{align*}
T^*(\lambda\alpha + \mu\beta)\mathbf v &= (\lambda\alpha+\mu\beta)(Tv_1,Tv_2) \\& = \lambda\alpha(Tv_1,Tv_2) + \mu\beta (Tv_1,Tv_2)\\ &= \lambda(T^*\alpha)\mathbf v + \mu(T^*\beta)\mathbf v \\
&= (\lambda T^*\alpha + \mu T^*\beta)\mathbf v
\end{align*}
 $$
for every $(v_1,v_2) =:\mathbf v \in V\oplus V$.


text:
Q: Angular UI tooltip from element Is it possible to have an Angular UI tooltip from an element, not from an attribute value?
Something like:
Show the tooltip

Hello, world!

A: Angular UI tooltips seem pretty simplistic for what you're trying to accomplish.
But it's definitely achievable. If you're willing to override some of the core modules and directives in the Angular UI library like it's been pointed out here. You can do so very well.
But if you're looking for a quick and easy solution - I'd recommend using qTip (http://qtip2.com/). It's a pretty powerful tooltip library.
Worst case, you can just use their JS and have your own style / Angular UI tooltip style on top of it.
You can do something like this -

$('a').qtip({
  content: {
    text: $('#tooltip1').html()
  }
});
<link href="http://cdn.jsdelivr.net/qtip2/2.2.1/jquery.qtip.min.css" rel="stylesheet" />

Show the tooltip

Hello, world!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Avoiding "yield" repetition in coroutine-like JavaScript function I'm using io.js, a fork of node that already supports ES6 generators without the need for special flags, and Kris Kowal's Q library.
What I'm making is a game script, where almost every single action is async, and I'm using Q.spawn to keep things sane. This is the current state of my code, and it works:
var q = require('q');
var tw = require('./lib/typewriter');
q.spawn(function*() {
    tw.clear();
    yield tw.type({d:100}, "August 3, 9:47 AM", {w:500});
    yield tw.type("District Court");
    yield tw.type("Defendant Lobby No. 2", {w:2000});
    yield tw.breakLine();
    yield tw.type({who:"Phoenix"}, {dh:true}, {d:30}, "(Boy am I nervous!)", {w:1500});
    yield tw.breakLine().then(function(){ throw new Error("BOOM!"); });
    yield tw.type({who:"Mia"}, {dh:true}, {d:40}, "Wright!", {w:1250});
    yield tw.type({di:true}, {d:50}, "Did you", {w:1000}, {d:0}, " ", {d:30}, "turn off the lights?", {w:1000});
    yield tw.type({di:true}, {d:400}, ". . .", {w:1000});
    yield tw.type({di:true}, {d:40}, "I can't see a thing!", {w:1000});
    yield tw.breakLine();
    process.exit();
});

However, adding yield to every single line sucks. I'm almost making the jump towards Luvit to escape from this madness, but I'm giving JavaScript its chance.
Under normal circumstances, I can omit most yielding, like this:
var q = require('q');
var tw = require('./lib/typewriter');
q.spawn(function*() {
    tw.clear();
    tw.type({d:100}, "August 3, 9:47 AM", {w:500});
    tw.type("District Court");
    tw.type("Defendant Lobby No. 2", {w:2000});
    tw.breakLine();
    tw.type({who:"Phoenix"}, {dh:true}, {d:30}, "(Boy am I nervous!)", {w:1500});
    tw.breakLine();
    tw.type({who:"Mia"}, {dh:true}, {d:40}, "Wright!", {w:1250});
    tw.type({di:true}, {d:50}, "Did you", {w:1000}, {d:0}, " ", {d:30}, "turn off the lights?", {w:1000});
    tw.type({di:true}, {d:400}, ". . .", {w:1000});
    tw.type({di:true}, {d:40}, "I can't see a thing!", {w:1000});
    yield tw.breakLine();
    process.exit();
});

Only one yield is still there, just to be sure process.exit() won't execute too early. The typewriter module actually queues most commands, so this works. This would be reasonable.
However, if a callback throws somewhere, as in:
tw.breakLine().then(function(){ throw new Error("BOOM!"); });

Then Q will swallow it up and, since there is no catch handler attached to that promise, it will just be silently garbage collected.
If JavaScript generators just detected expression statements yielding promises and automatically yielded that, it would be awesome (so long as you could opt out of it somehow, of course).
Is there a JavaScript preprocessor that does that?
Or is there some other way to avoid explicitly yielding on every single line but still get exceptions to be caught?

A:
If JavaScript generators just detected expression statements yielding promises and automatically yielded that, it would be awesome.

It would be terrible.

Or is there some other way to avoid explicitly yielding on every single line but still get exceptions to be caught?

Not really. But for your use case I would recommed to use an asynchronous helper function to decrease the number of yields to use:
var paragraph = q.async(function*(lines) {
    for (let line of lines)
        yield tw.type(...line);
    yield tw.breakLine();
});
q.spawn(function*() {
    tw.clear();
    yield paragraph([
        [{d:100}, "August 3, 9:47 AM", {w:500}],
        ["District Court"],
        ["Defendant Lobby No. 2", {w:2000}]
    ]);
    yield paragraph([
        [{who:"Phoenix"}, {dh:true}, {d:30}, "(Boy am I nervous!)", {w:1500}]
    ]);
    throw new Error("BOOM!");
    yield paragraph([
        [{who:"Mia"}, {dh:true}, {d:40}, "Wright!", {w:1250}],
        [{di:true}, {d:50}, "Did you", {w:1000}, {d:0}, " ", {d:30}, "turn off the lights?", {w:1000}],
        [{di:true}, {d:400}, ". . .", {w:1000}],
        [{di:true}, {d:40}, "I can't see a thing!", {w:1000}]
    ]);
    process.exit();
});


text:
Q: Дискорд Бот не отвечает на команду Я хотел сделать бота для Дискорд, который отправляет рандомную картинку с определённого сабреддита(в данном случае с r/memes), но при вводе команды - тишина
Код:
import praw
import random
from discord.ext import commands

TOKEN = "token :)"

bot = commands.Bot(description="test", command_prefix="$")
bot.remove_command( 'help' )

reddit = praw.Reddit(client_id='ID :)',
                     client_secret='Secret :)',
                     user_agent='MyBot')

@bot.command()
async def meme():
    memes_submissions = reddit.subreddit('memes').hot()
    post_to_pick = random.randint(1, 10)
    for i in range(0, post_to_pick):
        submission = next(x for x in memes_submissions if not x.stickied)

    await bot.say(submission.url)

bot.run(TOKEN)

Терминал выводит при эту ошибку после отправки команды на сервере:
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\HOME\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 690, in _parse_arguments
    next(iterator)
StopIteration

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\HOME\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\HOME\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 979, in on_message
    await self.process_commands(message)
  File "C:\Users\HOME\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 976, in process_commands
    await self.invoke(ctx)
  File "C:\Users\HOME\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\HOME\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
    await self.prepare(ctx)
  File "C:\Users\HOME\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
    await self._parse_arguments(ctx)
  File "C:\Users\HOME\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 693, in _parse_arguments
    raise discord.ClientException(fmt.format(self))
discord.errors.ClientException: Callback for meme command is missing "ctx" parameter.

Я не понимаю с чем это связано. Я - новичок в Python

A: Интерпретатор сообщает вам, что у функции meme() упущен аргумент ctx.
ctx - Контекст выполнения команды, содержащий информацию о сервере, пользователе и другую информацию
Этот аргумент в вашу функцию передает discord, при вызове команды, однако ваша функция не принимает аргументов.
Чтобы не возникало ошибки, достаточно просто добавить в функцию принятие аргумента:
async def meme(ctx):

Ну и насколько мне известно, у объекта commands.Bot нет функции say(). Если вы хотите отправить сообщение, в канал, где была вызвана команда, то можете как раз таки воспользоваться контекстом:
await ctx.send(submission.url)


text:
Q: How to set a minimum point snap distance? There are two points: A and B.  I need to snap any points within a 65 m search radius (blue buffer) of point A.  However, the snap distance of B needs to be exactly 5m apart from A (i.e. located anywhere on the red buffer).  I know the Snap or Integrate tools can perform the snapping, however, I need to find a programmatic solution to set the minimum snap distance.  How can I set a minimum snap distance for this type of analysis?  I will need to eventually scale this up to accommodate thousands of points.

Desired Outcome (below)

A: For the Points that fall within the 65 meter radius, can't you just subtract 5 meters from A's Y coordinate and use A's X coordinate to find a Point at the 5 meter position? You can use the DA cursor to update these Point's Geometry to the 5m position.

A: How about this for an idea.
If B is within the specified distance of A then create a polyline between A and B. You can then create a point any distance along that polyline.
Polyline object has a method positionalongline.

A: If you're not limiting yourself to an arcpy solution, what you're describing sounds like fairly common practice with ArcObjects - there is a 'Buffer Snap Agent' sample here:
Buffer snap agent
http://resources.arcgis.com/en/help/arcobjects-net/conceptualhelp/index.html#/d/000100000334000000.htm
I haven't tested it but was interested in the VB.NET logic - that logic setting your min/max search distance (your outer buffer) and snap to distance (your inner buffer) is in the function, snippet copied from the published sample below.  In this sample the distances are hard-coded, as you can see...
(http://resources.arcgis.com/en/help/arcobjects-net/conceptualhelp/index.html#//000100000886000000)
Public Function Snap(ByVal geom As IGeometry, ByVal point As IPoint, ByVal tolerance As Double) As Boolean Implements IEngineSnapAgent.Snap
      GetFeatureClass()

      Dim b_setNewFeatureCache As Boolean = False

      If m_featureClass Is Nothing Or m_editor Is Nothing Then
        Return False
      End If

      If m_featureClass.ShapeType <> esriGeometryType.esriGeometryPoint Then
        Return False
      End If

      'Check if a feature cache has been created.
      If Not b_setNewFeatureCache Then
        m_featureCache = New FeatureCache()
        b_setNewFeatureCache = True
      End If

      'Fill the New Cache with the geometries.
      'It is up to the developer to choose an appropriate value
      'given the map units and the scale at which editing will be undertaken.
      FillCache(m_featureClass, point, 10000)

      Dim proximityOp As IProximityOperator = DirectCast(point, IProximityOperator)
      Dim minDist As Double = tolerance
      Dim cachePt As IPoint = New PointClass()
      Dim snapPt As IPoint = New PointClass()
      Dim outPoly As IPolygon = New PolygonClass()
      Dim topoOp As ITopologicalOperator

      Dim feature As IFeature
      Dim Index As Integer = 0
      Dim Count As Integer
      For Count = 0 To m_featureCache.Count - 1 Step Count + 1
        feature = m_featureCache.Feature(Count)
        cachePt = feature.Shape
        topoOp = cachePt

        'Set the buffer distance to an appropriate value
        'given the map units and data being edited
        outPoly = topoOp.Buffer(1000)

        Dim Dist As Double = proximityOp.ReturnDistance(outPoly)
        If Dist < minDist Then
          Index = Count
          minDist = Dist
        End If
      Next

      'Make sure minDist is within the search tolerance.
      If minDist >= tolerance Then
        Return False
      End If

      'Retrieve the feature and its part again.
      feature = m_featureCache.Feature(Index)
      cachePt = feature.Shape
      topoOp = cachePt

      'Set the buffer distance to an appropriate value
      'given the map units and data being edited
      outPoly = topoOp.Buffer(1000)
      proximityOp = outPoly
      snapPt = proximityOp.ReturnNearestPoint(point, esriSegmentExtension.esriNoExtension)

      'Since point was passed in ByValue, we have to modify its values instead.
      'of giving it a new address.
      point.PutCoords(snapPt.X, snapPt.Y)

      Return True

End Function

A: if you are snapping the B towards the A, you could create 5 m buffers around each A's, then you use snap with a tolerance of 60 meters.


text:
Q: a question regarding wronskian I was working on following problem:
Let $y_1$ and $y_2$ be solutions of

$$x^2y'' + y' + (\sin x)y = 0$$

satisfying
$$y_1(0) = 0, y_1'(0)=1,y_2(0) = 1, y_2'(0)=0 $$.
I worked like following:
since wronskian $W$ is given as $$W = ce^{-\int-\frac{1}{x^2}\,dx}~,$$ wronskian is not zero except the point $x=0$. Thus, The two given solutions are L.I. and hence $y_1$ and  $y_2$ do not have common zeroes. Am I right in concluding this? Kindly rectify if somehwere I went wrong. Thanks for giving time.

A: The question looks incomplete and unanswered for a long time: but guessing from OP's attempt, I think (s)he is trying to find the Wronskian.
Here's couple of hints that will help you solve the question:

*

*$y_1(0) = 0, y_1'(0)=1,y_2(0) = 1, y_2'(0)=0 $. What does that tell you about $W_{(y_1,y_2)}(0)$ ($W_{(y_1,y_2)}(x)=\left|\begin{matrix}y_1(x) &&y_2(x)\\y'_1(x) && y'_2(x)\end{matrix}\right|$)?

*A little $\color{red}{\text{correction}}$ and $\color{green}{\text{added details}}$ into Abel's identity which you seem to have used in your attempt:
$$W(x)=\color{green}{W(0)}\times \color{red}{e^{-\int_0^x \frac1{x^2}dx}}=?$$


text:
Q: Ugly ::selection two-color background I'm trying to use a custom ::selection effect in Chrome but getting this bad blue coloration on highlighted text:

Here's my CSS:
::selection {
    color:#ffffff;
    background: #000000;
}
::-moz-selection {
    color:#ffffff;
    background: #000000;
}
::-webkit-selection {
    color:#ffffff;
    background: #000000;
}

I can't replicate the error in Firefox - is there anything I can do, or is it just a feature of the browser?

A: You want to wrap the text in a <p> tag.

A: I'm a little confused, because the selected text is applying the style from the code you're using... white text on a black background.
Is the light blue part the problem? If that's the case, I think the structure/css of the surrounding container(s) would be more helpful to get to the bottom of this.


text:
Q: Constants and simplifying enum value access For an enum with only one member variable, is there a simpler (and best practices) way to access it without the use of an accessor method? I had alternatively considered using public static final variables in a constants class but the more I read, the more people suggest using enum as the way to encapsulate those values.
To attempt to illustrate what I mean, I've included the following example:
public enum FILE_NAME {

   MAIN("MAIN.TXT"),
   ATTACHMENT("ATTACHMENT.TXT"),
   OTHER("OTHER.HTM");

   private String fileName;

   FILE(String fileName) {
     this.fileName = fileName;
   }

   public String getfileName() {
     return fileName;
   }
}

I would then normally access that value like so:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(bos);

// Add file
zip.putNextEntry(new ZipEntry(FILE_NAME.MAIN.getFileName()));

For my particular use case, I'd much prefer to be access the filename with a call like:
...
zip.putNextEntry(new ZipEntry(FILE_NAME.MAIN));

In doing so, the code reduces the length (and almost syntactic redundancy of calling a filename of a file) of the call needed to access the MAIN file name text. While this may not even be feasible or desirable, I'm curious to know if it's worth considering.
Thanks.

A: To simplify it, and still keep it safe, use a public final String field for the file name:
public enum FileType {
    MAIN("MAIN.TXT"),
    ATTACHMENT("ATTACHMENT.TXT"),
    OTHER("OTHER.HTM");

    // Name in all-caps to make it look like the constant it is
    public final String FILENAME;

    private FileType(String fileName) {
       this.FILENAME = fileName;
    }
}

To use it:
zip.putNextEntry(new ZipEntry(FileType.MAIN.FILENAME));

Note that change of class name to "FileType" to better adhere to java standards.

A: It seems like the following would work better
public enum FILE_NAME {

   MAIN("MAIN.TXT"),
   ATTACHMENT("ATTACHMENT.TXT"),
   OTHER("MAIN.TXT");

   private String fileName;

   FILE(String fileName) {
     this.fileName = fileName;
   }

   public void putEntry ( ZipOUtputStream zip )
   {
         zip.putNextEntry(new ZipEntry(this.getFileName()));
   }

   public String getfileName() {
     return fileName;
   }
}

Then you could use it like:
FILE_NAME.MAIN.putEntry(zip);

A: You can have aliases
enum Pet
{
    cat("meow"),
    dog("woof")

    String getSound()
}

public static final Pet CAT = Pet.cat;

public static final String MEOW = Pet.cat.getSound();


text: Q: Authentication as two different users when connecting to IIS7 I apologize if I completely bungle this question and description.  I have a test and production asp.net application both using windows authentication.  They are the same build but for some reason, on my development machine, the test application has started authenticating me as domain\user1 while the production application authenticates me as domain\user2 who I am logged in as.  If I try a different machine, both the test and production applications authenticate me as domain\user2 as expected.  This happens in both IE and Firefox and only on my dev machine.  I've cleared my cache, checked everything I can think of to check and I'm probably missing something obvious.  Any thoughts as to why Firefox and IE would be passing me as domain\user1 to the test application?


text:
Q: Magento 2 : Display dropdown attribute with its label in product listing page How to display dropdown type product attribute in product listing page and I also want to display that label name?
How to display that drop-down attributes? I created in admin. But, it's not displayed on listing page. But, it's proper display in product view page.

A: For that, you need to override renderer.phtml file and need to change onlySwatches and enableControlLabel attributes value.
Go to

app/design/frontend/<VendorName>/<themeName>/Magento_Swatches/templates/product/listing/rederer.phtml

Replace this below code
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
?>
<?php
/** @var $block \Magento\Swatches\Block\Product\Renderer\Listing\Configurable */
$productId = $block->getProduct()->getId();
?>
<div class="swatch-opt-<?= /* @escapeNotVerified */ $productId ?>"
     data-role="swatch-option-<?= /* @escapeNotVerified */ $productId ?>">

Clean cache and check the output.
Output :


text:
Q: Postfix: restrict outgoing mail sender domains I have a postfix 3.2.4, listening on port 25 for both incoming and outgoing mail. I know, it would be much better to use 587 submission port, but I can't reconfigure all of the existing email clients already using port 25. Clients use SASL authentication.
In order to avoid misconfiguration and/or misuse, I would like to only allow outgoing mail if it comes from an allowed domain, i.e. the sender address (the FROM mail header) belongs to one of my domains.
I know it could be easily done using a separate sumbission port for outgoing email, but is there any way to do it using the same 25 port for both icoming and outgoing email?
Thanks!


text:
Q: Wordpress: Querying a database from within javascipt / jquery I have a simple postcode search in my wordpress site. The user enters a postcode, clicks search and the browser directs to a new URL based on the postcode entered.
Presently, I have a large switch statement in the onclick handler of the button, which parses the postcode input in a text box and generates some display text and a URL which I then launch using window.open.
It works OK, but as I add more and more postcodes its bloating the code loaded into the browser and it's all visible in dev console. I'm also limited when it comes to making changes as I'm having to go in and modify the code to implement logic directly in my onclick handler. It's a bit of a mess!
What I would like to achieve is to store all of the relevant information in a mysql database, query the DB  when the form button is clicked, and then launch the URL which will be returned by the db query (well, there'll be a bit more logic in the server script than that but ultimately I'll just be returning a URL and some text).
I'm struggling to get my head around how to implement this. It appears the DB queries need to be in PHP on the server and has to be queried asynchronously? I'm getting lost down a rabbit hole of AJAX which I'm struggling to understand!
I'm not looking to asynchronously update content on my page - at the point that we're running code in the onclick handler, we're ready to launch a new page based on the postcode entered. It appears the required solution is a little more complex than I hoped it might be.
Can anybody suggest how I might implement this? Do I have to use PHP & AJAX?
Thanks


text: Q: Automatic rearrangement and regions When JetBrains' IDE's automatic rearrangement feature is used, it seems it ignores regions and move items between code regions. Is there any way to prevent moving items from a region to another on when rearranging?


text:
Q: Proving a function $\frac{1}{2y}\int_{x-y}^{x+y} f(t) dt=f(x)$ is a linear polynomial Here's the question:

Let $f:\mathbb{R}\to\mathbb{R}$ be a twice differentiable function
  such that $$\frac{1}{2y}\int_{x-y}^{x+y} f(t) dt=f(x)\text{ for all
 }x\in\mathbb{R},y>0$$ Show that there exist $a,b\in\mathbb{R}$ such
  that $f(x)=ax+b$ for all $x\in\mathbb{R}$.

My attempt:
It immediately follows from Fundamental Theorem of Calculus that $f'(x)=\frac{1}{2y} \left( f(x+y)-f(x-y) \right)$ for all $x\in\mathbb{R},y>0$.
Let $x\in\mathbb{R}$ and $y>0$ be arbitrary. Then there is a $c\in(x-y, x+y)$ such that $\frac{f(x+y)-f(x-y)}{2y}=f'(c)$. But $\frac{f(x+y)-f(x-y)}{2y}=f'(x)$ hence,  $f'(x)=f'(c)$. But since $x$ was arbitrary, $f'(x)=f'(c)$ for all $x\in\mathbb{R}$. Hence, it follows again by Fundamental Theorem of Calculus that $f(x)=f'(c)x+f(0)$ for all $x\in\mathbb{R}$.

It appears to me as if my proof is correct but I never used the "twice differentiable part". Are there any flaws in my proof? Alternative proofs are welcome.

EDIT: As pointed out by David, my proof is wrong. Hints would be appreciated.

A: Rewriting the equation as
$$\int_{x-y}^{x+y}f(t)dt=2yf(x)$$
and differentiating the above equation twice with respect to y one obtains that:
$$f'(x+y)=f'(x-y)$$ from which one can conclude that, after setting respectively $x\rightarrow x-y$ and $x\rightarrow x+y$:
$$f'(x-2y)=f'(x)=f'(x+2y) ~~\forall y>0$$
which overrides the fact that y is defined to be positive and sets all values that $f$ takes on the axis equal (if y was a real number we would be able to conclude that simply by virtue of the 2nd equation written). Thus $f'$ is constant and we finally find that
$$f(x)=Cx+D$$
for C,D real numbers. One can check with backsubstitution that there are no other constraints on the two parameters.
In light of this proof, I don't have a good answer as to why $f$ needs to be twice differentiable.

A: Since $\int_{x-y}^{x+y} {f(t)dt}= 2yf(x)$, $f(x+y)+f(x-y)=2f(x)$by differentiating by $y$.
This means that $f(x)$is symmetric by (x, f(x))for all $x$

A: We have:
$$\frac{1}{2y}\int_{x-y}^{x+y}f(t)dt=f(x)$$
where: $f(x)=ax+b$ so we can say:
$$\frac{1}{2y}\int_{x-y}^{x+y}[at+b]dt=f(x)$$
$$\left[a\frac{t^2}2+bt\right]_{x-y}^{x+y}=2yf(x)$$
$$\frac{a}{2}\left[(x+y)^2-(x-y)^2\right]+b\left[(x+y)-(x-y)\right]=2yf(x)$$
$$2axy+2by=2yf(x)$$
$$ax+b=f(x)$$
so algebraically it works


text:
Q: What to use as metatable? Reading http://lua-users.org/wiki/LuaClassesWithMetatable the Vector example uses the following technique for the metatable:
Vector={}
Vector_mt={__index=Vector}

function Vector:new(x,y)
    return setmetatable({x=x,y=y},Vector_mt)
end

function Vector:add(v)
    return Vector:new(self.x+v.x,self.y+v.y)
end

Supposing we want to use __add to support the + operator, we need to explicitly mention it in the metatable, and also we need to reorder things, so that the metatable and the constructor are mentioned after Vector:add:
Vector={}

function Vector:add(v)
    return Vector:new(self.x+v.x,self.y+v.y)
end

Vector_mt={__index=Vector,__add=Vector.add}

function Vector:new(x,y)
    return setmetatable({x=x,y=y},Vector_mt)
end

To avoiding having to mention each metamethod in the metatable, I can set Vector itself as the metatable, then I can add __add (plus, obviously, __index) as a method of Vector:
Vector={}

function Vector:new(x,y)
    return setmetatable({x=x,y=y},Vector)
end

function Vector:add(v)
    return Vector:new(self.x+v.x,self.y+v.y)
end

function Vector:__index(k)
    return Vector[k]
end

function Vector:__add(b)
    return self:add(b)
end

is the latter not recommended and why?

A:
and also we need to reorder things, so that the metatable and the constructor are mentioned after Vector:add

No. A table is a reference. On adding metatable, it is not deep copied. You can add fields to it later, and it will affect the metatable.
This is over-complicated:
function Vector:__index(k)
    return Vector[k]
end

Simply do this:
Vector.__index = Vector

See https://codereview.stackexchange.com/a/253022/230923 for an example of a Lua "class".


text:
Q: Resaving camera roll images are smaller When I resave an image from camera roll, it is smaller than the original one :
same number of pixels, same width and height, same colorspace, same DPI,
but file size is less :
original = 2.5 MB
resaved one = 1.5 MB
I use this method :
UIImageWriteToSavedPhotosAlbum(imageTosave, self, nil, nil);
Is this normal ?
Thank you for your help .

A: I encountered this issue a while agoitand found a workaround. Try wrapping the image in a new png:
NSData* imageData = UIImagePNGRepresentation (yourOriginalImage); // get PNG representation
UIImage* image2 = [UIImage imageWithData:imagedata]; // wrap UIImage around PNG representation
UIImageWriteToSavedPhotosAlbum(image2, nil, nil, nil); // save to photo album

Please let me know if this workaround still works. If not, I will remove this answer.


text:
Q: How do i pick out just one element to add to listBox1, not the hole row? here is an example of the xml file:
<Registrerte>
  <Registrert>
    <Kundenavn>Tomas</Kundenavn>
    <Startdato>06.04.2016</Startdato>
    <Antalldager>5</Antalldager>
  </Registrert>
  <Registrert>
    <Kundenavn>Øyvind </Kundenavn>
    <Startdato>08.08.08</Startdato>
    <Antalldager>6</Antalldager>
  </Registrert>
</Registrerte>

here is the code:
DataSet ds = new DataSet();
            ds.ReadXml(@"C:\Users\Li\Desktop\oppgave\WebSite4\registrering.xml");
        if (ds.Tables.Count > 0)
        {
            for (int o = 0; o < ds.Tables[0].Rows.Count; o++)
            {
                for (int g = 0; g < ds.Tables[0].Columns.Count; g++)
                {
                    listBox1.Items.Add(ds.Tables[0].Rows[o][g].ToString());
                }
            }
        }

i just want to show Kundenavn in listBox1. how do i do that ?


text:
Q: In PowerShell, how do I determine if a domain-joined computer is connected to the domain network? Before querying Active Directory, I need to make sure that the computer is actually attached to the corporate network (i.e., a domain network) with a secure connection to a domain controller. Network Location Awareness does this behind the scenes and presents the network profile in the GUI.
How do I do this in PowerShell?

A: This appears to work well, and should work on all versions of PowerShell:
function Test-DomainNetworkConnection
{
    # Returns $true if the computer is attached to a network where it has a secure connection
    # to a domain controller
    #
    # Returns $false otherwise

    # Get operating system  major and minor version
    $strOSVersion = (Get-WmiObject -Query "Select Version from Win32_OperatingSystem").Version
    $arrStrOSVersion = $strOSVersion.Split(".")
    $intOSMajorVersion = [UInt16]$arrStrOSVersion[0]
    if ($arrStrOSVersion.Length -ge 2)
    {
        $intOSMinorVersion = [UInt16]$arrStrOSVersion[1]
    } `
    else
    {
        $intOSMinorVersion = [UInt16]0
    }

    # Determine if attached to domain network
    if (($intOSMajorVersion -gt 6) -or (($intOSMajorVersion -eq 6) -and ($intOSMinorVersion -gt 1)))
    {
        # Windows 8 / Windows Server 2012 or Newer
        # First, get all Network Connection Profiles, and filter it down to only those that are domain networks
        $domainNetworks = Get-NetConnectionProfile | Where-Object {$_.NetworkCategory -eq "Domain"}
    } `
    else
    {
        # Windows Vista, Windows Server 2008, Windows 7, or Windows Server 2008 R2
        # (Untested on Windows XP / Windows Server 2003)
        # Get-NetConnectionProfile is not available; need to access the Network List Manager COM object
        # So, we use the Network List Manager COM object to get a list of all network connections
        # Then we get the category of each network connection
        # Categories: 0 = Public; 1 = Private; 2 = Domain; see: https://msdn.microsoft.com/en-us/library/windows/desktop/aa370800(v=vs.85).aspx

        $domainNetworks = ([Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]"{DCB00C01-570F-4A9B-8D69-199FDBA5723B}"))).GetNetworkConnections() | `
            ForEach-Object {$_.GetNetwork().GetCategory()} | Where-Object {$_ -eq 2}
    }
    return ($domainNetworks -ne $null)
}

With this function defined, simply type:
Test-DomainNetworkConnection

If it returns $true, then you know you have connectivity to a domain controller.


text:
Q: How can I split the output of "ps -ef" into "row output" How can I split the output of "ps -ef" into "row output".   One of the problems I am having is how to handle the "gpm -m /dev/input/mice -t exps2" as a single item during string tokenization.
If 'ps -ef' output is like this:
root      3410     1  0 Jun17 ?        00:00:00 gpm -m /dev/input/mice -t exps2
root      3424     1  0 Jun17 ?        00:00:00 crond
root      3488     1  0 Jun17 ?        00:00:00 /usr/sbin/atd

Then, how can I pretty print it so it looks like:
1:
root
3410
00:00:00
gpm -m /dev/input/mice -t exps2

2:
root
3424
00:00:00
crond

3:
root
3488
00:00:00
/usr/sbin/atd

A: Here's one way:
let i=0
while read line; do
  read user pid _ _ _ _ time command <<<"$line"
  if [ "$user" != UID ]; then # skip header line
    printf "%s\n" $((++i)): "$user" "$pid" "$time" "$command" ""
  fi
done < <(ps -ef)

You could also read the line directly into an array of fields in the first place with read -a, but then the command comes in as multiple elements and it's a little more work to combine it back into a single word.

A: Use the following shell snippet
OIFS=$IFS
IFS=$'\n'
i=0
for line in `ps -ef`; do
    echo "$i:"
    echo $line | cut -d' ' -f1
    echo $line | cut -d' ' -f2
    echo $line | cut -d' ' -f7
    echo $line | cut -d' ' -f8-
    (( i++ ))
done
IFS=$OIFS

A: Here's one way using awk:
ps -ef | awk -v OFS="\n" '{ for (i=8;i<=NF;i++) line = (line ? line FS : "") $i; print NR ":", $1, $2, $7, line, ""; line = "" }'

Results:
1:
root
3410
00:00:00
gpm -m /dev/input/mice -t exps2

2:
root
3424
00:00:00
crond

3:
root
3488
00:00:00
/usr/sbin/atd


text:
Q: RecursionError: maximum recursion depth exceeded in comparison inside class? Here's my code:
import zlib

import funcy

class DeflateData:
    def __init__(self, data):
        self.__data = data

    @property
    def compressed_data(self):
        compressed_data = bytearray()

        for chunk in funcy.chunks(32768, self.__data):
            compressed_data += zlib.compress(chunk, 9)

        return self.compressed_data

if __name__ == "__main__":
    with open("input_file", "rb") as infile:
        data = infile.read()

    deflate = DeflateData(data)

    print(deflate.compressed_data)

It works perfectly fine as a function not part of a class; however, I put it in a class as shown, and it gives the maximum recursion error, and it is stuck in an infinite loop. I think this has something to do with self.__data repeatedly being initialized when it should only be initialized once? That's just a guess, I have no idea what seems to be off, but any help would be appreciated.


text:
Q: transfer file from one subfolder of one repository to another in bitbucket without loosing history I recently discovered that as part of my project, a file was placed in the wrong location and now I need to move it to the appropriate directory in the correct repository. My issue is that I wish to retain the commit history.
I have been following a GitHub Community thread titled "Adding a folder from one repo to another" via Git Bash but this deals with the entire sub-directory and not just one file.

A: Move the file to the new place where it is needed to be, after that make a commit
Git will automatically maintain history even if the commit is for changing file path or adding comment line in the code.


text:
Q: MYSQL - How to check if a column has value or is it null and another column has value like 10 Lets say i have a table with 3 columns id, user and status.
I need to find rows which have status as 1 or null and user = 'someName'
I am lookin for a condition like this:
if (user == 'name' && status == 1 || status == null)
How do i do this in mysql

A: Just:
WHERE user = 'someName' AND (status = 1 OR status IS NULL)

This can be simplified as the shorter (but possibly less efficient)
WHERE user = 'someName' AND IFNULL(status, 1) = 1

Note that this does not exactly the same thing as your pseudo-code:
user == 'name' && status == 1 || status == null

Is equivalent to:
( user == 'name' && status == 1 ) || status == null

Which would translate as:
WHERE (user = 'someName' AND status = 1) OR status IS NULL

My understanding of your question, however, is that you meant the first above conditions.

A: You may try below -
SELECT * FROM TAB
WHERE user = 'Some Name'
AND (status = 1 OR status IS NULL)


text:
Q: Android DownloadManager and Media Scanner I'm trying to get an image downloaded via DownloadManager to show up in the Gallery app, but nothing I do works. According to the documentation, I thought this code would be sufficient:
  public void downloadImage(String url) {
        Uri Download_Uri = Uri.parse(url);
        DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
        request.allowScanningByMediaScanner();
        download_id = downloadManager.enqueue(request);
  }

But when the file downloads, it does not show up in the Gallery app. So I tried a download receiver to add it manually, like so:
 BroadcastReceiver receiver = new BroadcastReceiver() {
     @Override
     public void onReceive(Context context, Intent intent) {
         String action = intent.getAction();
         if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
             long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
             Query query = new Query();
             query.setFilterById(downloadId);
             Cursor c = downloadManager.query(query);
             if (c.moveToFirst()) {
                 int columnIndex = c
                         .getColumnIndex(DownloadManager.COLUMN_STATUS);
                 if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
                     String uriString = downloadManager.getUriForDownloadedFile(download_id).toString();
                             //c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                     Log.i("filname", uriString);
                     MediaScannerConnection.scanFile(ArticleActivity.this,
                              new String[] { uriString }, null,
                              new MediaScannerConnection.OnScanCompletedListener() {
                          public void onScanCompleted(String path, Uri uri) {
                              Log.i("Media Scanner", "Scanned " + path + ":");
                              Log.i("Media Scanner", "-> uri=" + uri);
                          }
                     });
                 }
             }
         }
     }
 };

That doesn't work either. The URI printed with the "filename" tag is something like 'content://downloads/my_downloads/97' instead of the name of the actual file that was downloaded. In the downloads app, the filename is the same as it was on the server. The Uri logged with the "Media Scanner" tag is null.
Am I missing something simple here? I've been pulling my hair out for a few hours on this.

A: I figured it out. I had to add a download location. The following line fixes it.
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, Download_Uri.getLastPathSegment());

A: The accepted answer was right for me until I tested it in Android 6.0. I'm not sure if it's an undocumented change, but downloadManager.getUriForDownloadedFile(download_id) is always returning a URI of the type content://downloads/my_downloads/97 for me, no matter if I set the file destination in the download request.
How I fixed it is by using the cursor from the download manager:
Query query = new Query();
query.setFilterById(downloadId);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
    String filePath = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
}


text:
Q: OData v4 DefaultODataBatchHandler NotImplementedException In my web service I've setup for batch requests. I wrapped the DefaultODataBatchHandler class just to add break points. It is processing the requests successfully and the CreateResponseMessageAsync method is creating a 200 OK response. But the client is receiving the following:
{
  "Message": "An error has occurred.",
  "ExceptionMessage": "The method or operation is not implemented.",
  "ExceptionType": "System.NotImplementedException",
  "StackTrace": "   at System.Web.HttpContextBase.get_Response()\r\n   at System.Web.UI.Util.GetUrlWithApplicationPath(HttpContextBase context, String url)\r\n   at System.Web.Routing.RouteCollection.NormalizeVirtualPath(RequestContext requestContext, String virtualPath)\r\n   at System.Web.Routing.RouteCollection.GetVirtualPath(RequestContext requestContext, String name, RouteValueDictionary values)\r\n   at System.Web.Http.WebHost.Routing.HostedHttpRouteCollection.GetVirtualPath(HttpRequestMessage request, String name, IDictionary`2 values)\r\n   at System.Web.Http.Routing.UrlHelper.GetVirtualPath(HttpRequestMessage request, String routeName, IDictionary`2 routeValues)\r\n   at System.Web.Http.Routing.UrlHelper.Route(String routeName, IDictionary`2 routeValues)\r\n   at System.Web.Http.Routing.UrlHelper.Link(String routeName, IDictionary`2 routeValues)\r\n   at System.Web.OData.Extensions.UrlHelperExtensions.CreateODataLink(UrlHelper urlHelper, String routeName, IODataPathHandler pathHandler, IList`1 segments)\r\n   at System.Web.OData.Extensions.UrlHelperExtensions.CreateODataLink(UrlHelper urlHelper, IList`1 segments)\r\n   at System.Web.OData.Formatter.ODataMediaTypeFormatter.GetDefaultBaseAddress(HttpRequestMessage request)\r\n   at System.Web.OData.Formatter.ODataMediaTypeFormatter.GetBaseAddressInternal(HttpRequestMessage request)\r\n   at System.Web.OData.Formatter.ODataMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content, HttpContentHeaders contentHeaders)\r\n   at System.Web.OData.Formatter.ODataMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Net.Http.HttpContent.<CopyToAsyncCore>d__44.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.OData.Batch.ODataBatchResponseItem.<WriteMessageAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.OData.Batch.ODataBatchContent.<SerializeToStreamAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Net.Http.HttpContent.<LoadIntoBufferAsyncCore>d__49.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Owin.HttpMessageHandlerAdapter.<BufferResponseContentAsync>d__13.MoveNext()"
}

I have no idea why or where this is coming from.
ODataConfig.cs
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        var builder = new ODataConventionModelBuilder();

        var tags = builder.EntitySet<EventTag>("EventTags");
        tags.HasOptionalBinding(x => x.Parent, tags);

        var events = builder.EntitySet<Event>("Events");
        events.HasManyBinding(x => x.Tags, tags);

        var batchHandler = new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer);

        config.MapODataServiceRoute("odata", "odata", builder.GetEdmModel(), batchHandler);
    }
}

A: I resolved this by making sure I called into Register with a new instance of HttpConfiguration, rather than re-using one from before (which I had wired up Autofac on). I guess you could get the same problems if you tried to wire this up using GlobalConfiguration.Configuration.
Trick is to set up WebApi on a new HttpConfiguration instance.


text:
Q: Google Fonts in Firefox renders pixelated I am using Google Fonts service and I noticed that some fonts are rendered in a different way in Chrome and Firefox.
See this example, using Kite One font.
Why does Firefox pixelate the text? What can I do via CSS or server-side to avoid this pixelation?
EDIT: I am including the font using Google Fonts api:
<link href='http://fonts.googleapis.com/css?family=Kite+One' rel='stylesheet' type='text/css'>

A: you can try this trick : text-shadow: 1px 1px 1px rgba(0,0,0,0.004);
The rendering of the police is part of the browser not really customisable by css.


text:
Q: Error copying matching creds -- Swift (REST API call) I'm trying to make an REST API call to a universal devices hub to turn a switch on. It seems like the call is going through, however I am getting an error that says I need credentials, which makes sense because there are credentials needed to get into the interface. However I am not sure how to make this work.
My code is the following
class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBOutlet weak var lightOn: UIButton!
@IBAction func lightOn(_ sender: Any) {

    guard let url = URL(string: "http://0.0.0.0/rest/nodes/ZW002_1/cmd/DFON") else { return }

    let userCredential = URLCredential(user: "admin",
                                       password: "admin",
                                       persistence: .permanent)

    URLCredentialStorage.shared.setDefaultCredential(userCredential, for: protectionSpace)

    // create URL session ~ defaulted to GET

    let session = URLSession.shared

    session.dataTask(with: url) { (data, response, error) in

        // optional chaining to make sure value is inside returnables and not not

        if let response = response {
            print(response)
        }

        if let data = data {

            // assuming the data coming back is Json -> transform bytes into readable json data

            do {

                let json = try JSONSerialization.jsonObject(with: data, options: [])

                print(json)

            }   catch {

                print("error")
            }
        }

        }.resume() // if this is not called this block of code isnt executed

}

}

I tried piecing together a couple examples online, and the ones I have seen use protectionSpace but when I use it the code returns:
Use of unresolved identifier 'protectionSpace'

Also overall whenever I actually run the simulator I get this exact error:
2017-12-26 13:28:58.656122-0600 hohmtest[6922:1000481] CredStore - performQuery - Error copying matching creds.  Error=-25300, query={
atyp = http;
class = inet;
"m_Limit" = "m_LimitAll";
ptcl = http;
"r_Attributes" = 1;
sdmn = "/";
srvr = "192.168.1.73";
sync = syna;
}
<NSHTTPURLResponse: 0x60400042a3e0>
{ URL:
http://192.168.1.73/rest/nodes/ZW002_1/cmd/DON/ } { Status Code: 401,
Headers {
"Cache-Control" =     (
    "max-age=3600, must-revalidate"
);
Connection =     (
    "Keep-Alive"
);
"Content-Length" =     (
    0
);
"Content-Type" =     (
    "text/html; charset=UTF-8"
);
EXT =     (
    "UCoS, UPnP/1.0, UDI/1.0"
);
"Last-Modified" =     (
    "Tue, 26 Dec 2017 11:26:15 GMT"
);
"Www-Authenticate" =     (
    "Basic realm=\"/\""
);
} }
error

A: This solution worked for me. This is how I called a REST API that required a username and password. For those wondering, I put this code inside my IBAction button and didn't have to do anything else other than making the button.
let username = "admin"
let password = "admin"
let loginData = String(format: "%@:%@", username, password).data(using: String.Encoding.utf8)!
let base64LoginData = loginData.base64EncodedString()

// create the request
let url = URL(string: "http:/rest/nodes/ZW002_1/cmd/DFON")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Basic \(base64LoginData)", forHTTPHeaderField: "Authorization")

//making the request
let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print("\(error)")
        return
    }

    if let httpStatus = response as? HTTPURLResponse {
        // check status code returned by the http server
        print("status code = \(httpStatus.statusCode)")
        // process result
    }
}
task.resume()

********* EXTRA NOTE *************
If yours does not have a username and password and you are trying to call a REST API call in swift here is some code that can help you! BOTH ARE GET REQUESTS!
@IBAction func onGetTapped(_ sender: Any) {

    guard let url = URL(string: "https://jsonplaceholder.typicode.com/users") else { return }

    // create URL session ~ defaulted to GET

    let session = URLSession.shared

    session.dataTask(with: url) { (data, response, error) in

        // optional chaining to make sure value is inside returnables and not not

        if let response = response {
            print(response)
        }

        if let data = data {

            // assuming the data coming back is Json -> transform bytes into readable json data

            do {

                let json = try JSONSerialization.jsonObject(with: data, options: [])

                print(json)

            }   catch {

                print("error")
            }
        }

        }.resume() // if this is not called this block of code isnt executed

}


text:
Q: I started training an object detection AI and my loss value is 22 digits long, how normal is this? I downloaded my dataset from googles Open Image Dataset V6 and converted the txt annotations into VOC annotations so I could use it in Tensorflow following this tutorial.
I have 4 classes with a 100 training sets and 50 test sets each.I'm using google colab following this tutorial series.
As Im writing this, training is currently at step 26k and my loss value is now 23 digits long and I suspect its going even higher. I'm fairly new here but I'm pretty sure that number is suppose to be going down. I'd really appreciate some help

A: ok, so it wasn't suppose to do that... but I fixed it. I started snooping here and eventually ended up here. They call it 'Loss explosion'. Apparently in my case, my class names in label.pbtxt didn't match those in my tfrecord file when training.
Turns out that labels are case sensitive. I had the OIDV4 dataset already converted to VOC at this point but I still had the txt annotations hanging around. Checking the label text annotations from the downloaded dataset, I found out that they were labeled with class names with the first character in uppercase, way different from the class names I set inside my labelmap.pbtxt.
sO I wEnt ThrOuGH aLL 700 LABeL aNnoTatIon tXT fILEs BY HAND anD cHanGe-(no, not really, but I think you know what to do at this point :))
so...
HEED MY WARNING TRAINER!!!
check thine class names...
check thine labelmaps.pbtxt...
check thine generate_tfrecords.py...
check thine downloaded datasets...
else thine loss is by explosion...
or idk... just check your spelling I guess?


text:
Q: Pandas irow() automatically converts int to float x = DataFrame([(1,2.0),(2,4.0)], columns=['a','b'])
x.dtypes
a      int64
b    float64
a = x.irow(0)
a
output:
a    1.0
b    2.0
Name: 0, dtype: float64

why does pandas convert automatically to float? how can I keep the int columns as int without use astype/cast for each field after using irow?

A: It returns a Series for that row so the dtype is promoted to float due to the presence of the float in col b
In [33]:
type(x.irow(0))

Out[33]:
pandas.core.series.Series

Also that method is deprecated you should be using iloc:
In [31]:
x.iloc[0]

Out[31]:
a    1.0
b    2.0
Name: 0, dtype: float64

In practicality this is not a real issue as accessing a specific column of a row will preserve the dtype:
In [36]:
x['a'].iloc[0]

Out[36]:
1

In [37]:
type(x['a'].iloc[0])

Out[37]:
numpy.int64

A: You could use dtype=object for use each data own type like below
df = pd.read_excel(INPUT_FILE, index_col=0, dtype=object)


text:
Q: Performing operations on Django Querysets I have very large Querysets with the following general form:
(
    {id: x}
    {termVector: [ '.00035 .00052...' ]}
)

If I want to convert the termVectors from a string to a list of floats, is there a standard way of doing that? I've been using the .values() method and iterating through the resulting dict, but it seems to be pretty computationally heavy given the size of the querysets.
I feel like there must be a better way but I can't seem to find any way of doing it in the documentation.
EDIT:
My current placeholder method looks like this:
    for vectorList in termVectorQS:
        termVector.append(vectorList['termVector'].split())
    for x in termVector:
        for y in x:
            termList.append(float(y))

It just splits the vector string by whitespace, then converts each string to a float and adds it to an array (termList) that I use for further calculations.

A: Rather than looping again, you can use map to convert everything to a float
termVectorQS = [{"termVector": '.00035 .00052 .000112 .000113 .0114 .00035 .00052 .000112 .000113 .0114 .00035 .00052 .000112 .000113 .0114 .00035 .00052 .000112 .000113 .0114' }]

termList = []
for vectorList in termVectorQS:
        termList.append(list(map(float, vectorList['termVector'].split())))

It isn't a huge speedup but this ran in 820ms for 160000 iterations and looping twice was 1.19 s


text:
Q: Validation library in JavaScript Is there any validation library in JavaScript? I'm looking for something small, simple and basic.
Example 1
var email = "steve@jobs.com";

if ( validate(email, "email") ) {

  // Success

}

Example 2
var email = "steve@jobs.com";

if ( validate(email, {
  "length": [0, 12],
  "characters": ["a", "b", "c", "d", "e", ...],
}) ) {

  // Success

}

Thank you.

A: If you just want to validate emails, check out this link:
http://www.white-hat-web-design.co.uk/articles/js-validation.php
And here's phone number validation:
http://www.smartwebby.com/DHTML/phone_no_validation.asp
(To answer your question directly, I don't know of any validation libraries :) )

A: Have you tried looking at
jquery Validation

A: For form validation based on some common types, perhaps see my Form AutoValidate library.

A: Take a look here, there, in hotscripts you have a couple of options.


text:
Q: Can a character in C ever be both a newline and a NULL terminator?
*

*What is the purpose of if (cmdline[-1] == '\n' && cmdline[-1] == '\0') in the following code sample?

*

*when will this ever evaluate to true?

*How does the negative index in cmdline[-1] work here? I've seen similar questions on SO, but here there's no pointer arithmetic beforehand.

Here's the pseudocode it comes from:
parseInfo *parse (char *cmdline) {
  parseInfo *Result;
  char command[MAXLINE];
  int com_pos = -1;

  if (cmdline[-1] == '\n' && cmdline[-1] == '\0')
    return NULL;

  Result = malloc(sizeof(parseInfo));
  init_info(Result);
  com_pos=0;
  /*  while (cmdline[i] != '\n' && cmdline[i] != '\0') { */

  command[com_pos]='\0';
  parse_command(command, 0); /* &Result->CommArray[Result->pipeNum]);*/

  return Result;
}

EDIT #1:
Why does "When does this NOT get printed?" get printed in the following situation:
EDIT #2: I made cmdline a valid string by increasing the length by 1 (include the null character) and by copying length bytes into length malloc'd ones.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void parse(char *cmdline) {
  printf("'%c'\n", cmdline[-1]);
  if (cmdline[-1] == '\0' || cmdline[-1] == '\n') {
    printf("When does this NOT get printed?\n");
  }
}

int main() {
  char str[100] = "hello";
  const int length = strlen(str) + 1;
  char *cmdline = malloc(length * sizeof(char));
  strncpy(cmdline, str, length);
  parse(cmdline);
  return 0;
}

With the corresponding output:
$ gcc -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.1.0 (clang-602.0.49) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.3.0
Thread model: posix
$ gcc negative_index.c
$ ./a.out
''
When does this NOT get printed?

A: *

*No, a char can NOT be both \n and \0, the code perhaps meant
to use || instead of &&.

*For example:
char str[100] = "hello world";
char *cmdline = str + 10;

Then cmdline[-1] is the same as str[9].


text:
Q: Food which is not cooked yet How do I say a vegetable or some meat is not cooked yet?
Is it raw or fresh?
Because uncooked meat/vegetable may be rotten. And they may not be fresh.

... add spices, salt, water with vegetables/meat and keep them on stove (with flame) for an hour

Is this boil or cook?
It can't be cook, because I am not stirring, or applying any special procedure to the food.

A: *

*It's 'uncooked' for something that is not cooked yet. Translates to:

not cooked; raw:

Ref: http://www.dictionary.com/browse/uncooked

*

*Simmer makes more sense instead of cook or boil in this case

A: I agree with Malvolio up to a point regarding the usage of uncooked vs. raw.   But raw can also be used to refer to food which is intended to be cooked.
Fresh can refer to food which is cooked as well as that which is uncooked. Food ceases to be fresh when its flavour, texture, appearance or edibility deteriorate.

A: "Uncooked" and "undercooked" imply that the food ought to be cooked ("uncooked chicken").
"Raw" implies a deliberate simplicity in preparation.  It hasn't been cooked, heavily spiced, or aged.
"Fresh" means that the food is not only uncooked but literally fresh: newly arrived from its source.


text:
Q: Prove/Disprove: For any sets A and B, $(A \cup B)^c = A^c \cap B^c$ After drawing a diagram of this statement, I believe it to be false. However, I'm having trouble approaching how to disprove this. Do I try to prove the negation? Or what else can I do?

A: $x\in (A'\cap B')\to x\in A'$ and $x\in B'$. If $x\in A'$ then $x\notin A$ and if $x\in B'$ then $x\notin B$. In both cases, $x\notin A\cup B$. This means that $x\in (A\cup B)'$. The other direction is analogous. You can do it.

A: $x\in(A\cup B)'$ $\Rightarrow$ $(x\notin A\text{ and } x\notin B)$ $\Rightarrow$ $(x\in A'\text{ and } x\in B')$ $\Rightarrow$ $x\in A'\cap B'$ $\Rightarrow (A\cup B)'\subseteq A'\cap B'$
$x\in A'\cap B'$ $\Rightarrow$ $(x\in A'\text{ and } x\in B')$ $\Rightarrow$ $(x\notin A\text{ and }x\notin B)$ $\Rightarrow$ $x\in(A\cup B)'$ $\Rightarrow A'\cap B'\subseteq (A\cup B)'$
And
$(A\cup B)'\subseteq A'\cap B'$ and $A'\cap B'\subseteq (A\cup B)'$ $\Leftrightarrow$ $(A \cup B)' = A' \cap B'$


text:
Q: What is the best way to handle: onload not being triggered for images with size zero in JavaScript? To make sure an image is load on our page and then proceed to the next state, we have used the onload method as mentioned here:
image = new Image();

image.onload = function(){
  // go to the next state
};

image.src = image_url;

The issue is the event is not triggered for images with size zero and as a result the page stays in the halt mode and does not progress to the next state.
What is the best way to handle the issue with onload function not being triggered for images with size zero?
Related questions:
1- new Image(), how to know if image 100% loaded or not?

A: If you really want to do this with 0 size files, try to make it a script. 0 size script is valid. See:
Trying to fire the onload event on script tag
Or if you really have some real images, but some are "nothing", then use a 1x1 "clear_pixel.gif". You can also make it invisible with css (though then you won't see the real images either), maybe there's a way to detect from js in the onload what's the real size of the image.

A: If you want your process to proceed when the image either finishes loading or fails to load, you can add your event handler to the .onerror event:
var image = new Image();

image.onload = image.onerror = function () {
    // go to the next state
};

image.src = image_url;

A: Can you give the images a non-0 size and then use position:absolute to place them off the page where they are not visible?
height:1px
width:1px
position:absolute
left:-1000000px

(I'm assuming here that they are actual images with non-zero size, but you made the img element have size 0 in order for the images not to be visible. I'm not exactly sure that's the case.)


text:
Q: program to write data to django DB has with throws error about settings. i have a python program that reads in NMEA sentences and writes them to my django database.
update = breadCrumbs2(deviceID= device[0], time = tdStamp , latitude = msg.latitude,
                              longitude = msg.longitude , fixQualty = int(msg.gps_qual),
                              numSat = int(msg.num_sats),hdop = msg.horizontal_dil,
                              altitude = msg.altitude, geoIdalSeparation = msg.geo_sep,
                              deltaLastUpdate = Decimal(0), diffRefStationID = int(1),
                              nmeaCheckSum = "")
        update.save()

this works fine when run from eclipse. but when i try to run it from my linux box i get an error:
"django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings."
but when i go into the django shell to configure settings i get.
 >>> from django.conf import settings
>>> settings.configure()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 93, in configure
    raise RuntimeError('Settings already configured.')
RuntimeError: Settings already configured.

how to i correct this conflict. (i have restarted Django and Apache)


text:
Q: Javascript Calculation Issue in some Formulas I Have some Formulas in Javascript and trying to format them but unable to do that .
Here is my JS code from which i am trying to make calculations
I have these two variable from which i get input and then make calculations
var pkrusd;
var pkrusd = parseFloat(document.getElementById('txtpkrusd').value, 10);
var ratelb;
ratelb = parseFloat(document.getElementById('txtRatelb').value, 10);

And here are my formulas from which i show results
var res;
res=roundNumber((pkrusd*ratelb)/100.00,2);
document.getElementById('txtF5').value = addCommas(res);
//Per Kg
var perkg=((pkrusd*ratelb)/100.00)*2.20462262184878;
document.getElementById('txtperkg').value=addCommas(roundNumber(perkg,2));
//RS Per Maund
var perMaund=roundNumber((((pkrusd*ratelb)/100.00)*2.20462262184878)*37.3242,2);
document.getElementById('txtperMaund').value=addCommas(perMaund);

Problem is that when i res formula and values pkrusd and ratelb are 91 and 100 and formula for these is (91*100)/100 the result is 91 but i want to set some formating that should be displayed as 91.00 and when values are (91*250)*100 then result is 227.5 but i want to display as 227.50.If there any possibilty for this then please help me to do this

A: Have a look at toFixed()
Example:
var n=91;
alert(n.toFixed(2));

That outputs 91.00


text:
Q: Python, comparing dataframe rows, adding new column - Truth Value Error? I am quite new to Python, and somewhat stuck here.
I just want to compare floats with a previous or forward row in a dataframe, and mark a new column accordingly. FWIW, I have 6000 rows to compare. I need to output a string or int as the result.
My Python code:
for row in df_an:

    x = df_an['mid_h'].shift(1)
    y = df_an['mid_h']

    if y > x:
        df_an['bar_type'] = 1

I get the error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
The x and y variables are generated, but apparently things go wrong with the  if y > x: statement.
Any advice much appreciated.
A different approach...
I managed to implement the suggested .gt operator.
df_an.loc[df_an.mid_h.gt(df_an.mid_h.shift()) &\
          df_an.mid_l.gt(df_an.mid_l.shift()), "bar_type"] = UP

A: Instead of row; you basically shifting whole row then comparing; try this once;
df_an = pd.DataFrame({"mid_h":[1,3,5,7,7,5,3]})

df_an['bar_type'] = df_an.mid_h.gt(df_an.mid_h.shift())

# Output

   mid_h  bar_type
0      1     False
1      3      True
2      5      True
3      7      True
4      7     False
5      5     False
6      3     False


text:
Q: joining multiple dynamic lists of objects So I'm really trying to build dynamic reports in C# based off of multiple stored procedures across multiple databases and then join the results.
Here is an example:
List 1:
  { monthyear = '032016', submitted = '56', approved = '27'},
  { monthyear = '042016', submitted = '67', approved = '30'}

List 2
  { monthyear = '032016', returned = '17'},
  { monthyear = '042016', returned = '22'}

Knowing that the "key" column is dynamic and the results built into each list are dynamic. I am however able to retrieve a string representation of the key column that joins the lists.
The result I am looking for is:
  { monthyear = '032016', submitted = '56', approved = '27', returned = '17'},
  { monthyear = '042016', submitted = '67', approved = '30', returned = '22'}

Both list are stored as an IEnumerable<object> with an intended result of       IEnumerable<object>.
Is there a way to join these, not concat, without looping?

A: in linq you can write the join query as this
var res = list1.Join(list2, a => a.monthyear , b => b.monthyear ,
(a, b) => new { a.monthyear,a.returned, b.submitted, b.approved});

but i`m not sure how it is implemented internally
Edit
in this case you`ll need to use reflection first (you can enhance this)
foreach (PropertyInfo p in typeof(firstObj).GetProperties())
        {
            foreach (PropertyInfo p2 in typeof(secondObject).GetProperties())
                if (p.Name == p2.Name)
                    match = p.Name;
        }

now the variable match stores the key as string
list1.Join(list2, a=>a.GetType().GetProperty(match).GetValue(a,null), b => b.GetType().GetProperty(match).GetValue(b,null), (a, b) => new { a.first, a.second..... });

or
, (a,b) => new { a, b});

my guide was this and this
morever check this to select all the properties if you don`t know their names
hope this helps

A: Well, looping is going to be required, if for no other reason than to loop through the SP results as they come in from the database.
That aside, you could have a Dictionary<string, Dictionary<string, object>> that will hold the final result. Reflection can pull all properties out from each of the records as they come in, and drop them into a Dictionary<string, object> for each record (keyed by property name, value is property value). Then merge these dictionaries into the big Dictionary<string, Dictionary<string, object>> which is keyed by whatever property you're interested in (looks like the "monthyear" property).
Reflection might not even be necessary e.g. if you're using a DataTable then you already have programmatic access to all the record field names and values.


text:
Q: Trace inequality for product of three matrices For square matrices $A,B,C\in\mathbb C^{n\times n}$ is it correct that
$$\lvert\mathrm{Tr}(ABC)\rvert \le \sqrt{\mathrm{Tr}(A^\ast A \lvert B\rvert)\mathrm{Tr}(CC^\ast \lvert B\rvert)},$$
where $\lvert B\rvert$ is the positive-semidefinite square-root $\lvert B\rvert=(B^\ast B)^{1/2}$? Note that the rhs. is non-negative since the product of positive-semidefinite matrices has a non-negative trace.
The answer is trivially yes if $B=\lvert B\rvert$ since then
$$\lvert\mathrm{Tr}(ABC)\rvert=\lvert\mathrm{Tr}(A\lvert B\rvert^{1/2}\lvert B\rvert^{1/2} C)\rvert\le \sqrt{\mathrm{Tr}(A \lvert B\rvert A^\ast)\mathrm{Tr}( \lvert B\rvert C C^\ast )}$$
due to Cauchy-Schwarz.

A: The proposed inequality is valid as long as we are  allowed to tweak it a bit:
$$
  |\mathrm{Tr}(abc)| \le
  \sqrt{\mathrm{Tr}(a^\ast a | b^*|)\ \mathrm{Tr}(cc^\ast | b|)}.
$$
The difference is the term $| b^*|$ instead of $| b|$ in the RHS.
To prove it let $b=u|b|$ be the polar decomposition of $b$ and notice that by Cauchy-Schwarz
$$
  |\mathrm{Tr}(abc)|^2 =
  |\mathrm{Tr}(au|b|^{1/2}|b|^{1/2}c)|^2 \leq  $$$$ \leq
  \mathrm{Tr}(au|b|^{1/2}|b|^{1/2}u^*a^*)
  \ \mathrm{Tr}(c^*|b|^{1/2}|b|^{1/2}c)|^2 = $$$$ =
  \mathrm{Tr}(au|b|u^*a^*)
  \ \mathrm{Tr}(c^*|b|c)|^2.
  \tag {1}
  $$
Next notice that
$$
  (u|b|u^*)^2 =   u|b|u^*u|b|u^* = u|b||b|u^* = bb^*,
  $$
which means that   $u|b|u^*$ is a  positive matrix whose square coincides with $bb^*$, whence
$$
  u|b|u^* = |b^*|.
  \tag{2}
  $$
Plugging (2) in  $(1)$ then completes the proof.

Given the nature of Math, in which the pieces fit together in an incredibly elegant way, I dare say that the problem
that led the OP to formulate this question might be better served by the above inequality, as compared to the originally
proposed one.  I would be very thankful if they could confirm it or deny it in a comment!

A: For reasons of continuity we need only consider this purported inequality when $B$ is invertible.
The answer to OP's question is No and I construct an explicit counter example below using Polar Form and Cauchy-Schwarz.
using Polar Decomposition $B = UP$
and for concreteness suppose that $U$ is the discrete Fourier transform and $P\succ \mathbf 0$ is a diagonal matrix with distinct diagonal entries
$\Big\vert\text{trace}\big(ABC\big)\Big\vert $
$=\Big\vert\text{trace}\big(AUP^\frac{1}{2}P^\frac{1}{2}C\big)\Big\vert $
$=\Big\vert\text{trace}\big((P^\frac{1}{2}C)(AUP^\frac{1}{2})\big)\Big\vert $
$=\Big\vert\text{trace}\big((C^*P^\frac{1}{2})^*(AUP^\frac{1}{2})\big)\Big\vert $
$\leq  \Big\Vert AUP^\frac{1}{2}\Big \Vert_F \Big \Vert C^*P^\frac{1}{2}\Big \Vert_F $
by Cauchy Scwharz
now I select $A$ such that $U^*A^*AU = P$
(note that $A^*A = UPU^* \neq P$)
finally select $C^*:=  AU$. Then the above Cauchy-Schwarz is met with equality, so
$\Big\vert\text{trace}\big(ABC\big)\Big\vert $
$=\Big\Vert AUP^\frac{1}{2}\Big \Vert_F \Big \Vert C^*P^\frac{1}{2}\Big \Vert_F $
$=\Big\Vert AUP^\frac{1}{2}\Big \Vert_F^2$
$=\text{trace}\Big(  U^*A^*AUP\Big)$
$=\Big \Vert U^*A^*AU\Big \Vert_F \Big \Vert P\Big \Vert_F$
$=\Big \Vert A^*A\Big \Vert_F \Big \Vert P\Big \Vert_F$
$\gt \text{trace}\Big(  A^*AP\Big)$
by Cauchy Schwarz
putting this all together, we have found a case where
$ \sqrt{\mathrm{Tr}(A \lvert B\rvert A^\ast)\cdot \mathrm{Tr}( \lvert B\rvert C C^\ast )} =  \sqrt{\mathrm{Tr}(A \lvert B\rvert A^\ast)\cdot \lvert\mathrm{Tr}(ABC)\rvert} \lt \lvert\mathrm{Tr}(ABC)\rvert$

A: As the other two answers show, the inequality as it stands is false. It can be corrected by changing the first $|B|$ on the RHS to $|B^\ast|$. It is easier to prove the corrected inequality by singular value decomposition $B=USV^\ast$ than by polar decomposition. Denote by $\langle X,Y\rangle$ the Frobenius inner product $\operatorname{tr}(XY^\ast)$. By Cauchy-Schwarz inequality,
\begin{aligned}
|\operatorname{tr}(ABC)|
&=|\operatorname{tr}(AUSV^\ast C)|\\
&=|\langle AUS^{1/2},C^\ast VS^{1/2}\rangle|\\
&\le\sqrt{\langle AUS^{1/2},AUS^{1/2}\rangle \langle C^\ast VS^{1/2},C^\ast VS^{1/2}\rangle}\\
&=\sqrt{\operatorname{tr}(AUSU^\ast A^\ast) \operatorname{tr}(C^\ast VSV^\ast C)}\\
&=\sqrt{\operatorname{tr}(A|B^\ast|A^\ast) \operatorname{tr}(C^\ast|B|C)}\\
&=\sqrt{\operatorname{tr}(A^\ast A|B^\ast|) \operatorname{tr}(CC^\ast|B|)}.\\
\end{aligned}


text:
Q: time.sleep freezes the program after forking (Go) I am forking into "daemon" mode with this function:
func daemon(nochdir, noclose int) int {

        ret, _, err := syscall.Syscall(syscall.SYS_FORK, 0, 0, 0)
        if err != 0 {
                maybe_exit_err("Forking", err)
                return -1
        }
        switch ret {
        case 0:
                break
        default:
                os.Exit(0)
        }

        sid, err2 := syscall.Setsid()
        maybe_exit_err(fmt.Sprintf("could not set session: %s", sid), err2)
        if sid == -1 {
                return -1
        }
        if nochdir == 0 {
                os.Chdir("/")
        }
        if noclose == 0 {
                f, e := os.OpenFile("/dev/null", os.O_RDWR, 0)
                if e == nil {
                        fd := int(f.Fd())
                        syscall.Dup2(fd, int(os.Stdin.Fd()))
                        syscall.Dup2(fd, int(os.Stdout.Fd()))
                        syscall.Dup2(fd, int(os.Stderr.Fd()))
                }
        }
        return 0
}

The program works fine as long as I do not use time.Sleep(1 * time.Second). After that, it just sits there doing nothing, I have even added writing test string in a loop to a file I opened myself, and nothing is being written there after time.Sleep is used (and it works fine if not).
What might be the reason here?
OS: Debian Linux 7.2 x64
go version: 1.2

A: It seems I've ran into general issue with runtime: https://code.google.com/p/go/issues/detail?id=6664
UPDATE:
G++1 : https://github.com/sevlyar/go-daemon
SO--1


text:
Q: Get Joomla jdoc in PHP? I am very new to Joomla, and I am trying to get the output of a <jdoc:include /> tag in PHP before the page is rendered.
My menu is included like this: <jdoc:include type="modules" name="main menu" />
I am trying to count the <li> tags within the main menu. I have it setup like this:
$str = <<< HTML
    <jdoc:include type="modules" name="main menu" />
HTML;
$count = substr_count($str, '<li>');
echo $count;
echo $str;

The menu echoes like normal, but $count is always 0, like it hasn't parsed yet.

A: <jdoc:include type="modules" name="main menu" /> is used to include the module in "main menu" position.li tag is in modules/mod_menu/tmpl/default.php page

A: <jdoc:include type="modules" name="main menu" />

Above line means that your main manu is included as a Joomla module.
If you are to count you will have to render the module 1st.
method 1
$document   = &JFactory::getDocument();
$renderer   = $document->loadRenderer('module');
$params   = array('style'=>$style);
$result = $renderer->render(JModuleHelper::getModule('mod_main_menu'), $params);

else try this code to render
method 2
$module = &JModuleHelper::getModule('mod_module');
$result = JModuleHelper::renderModule($module);

Let's assume that your main menu module name is mod_main_menu.
Then try to count like below.
$count = substr_count($result, '<li>');
echo $count;


text:
Q: Reading and checking Character Problem This is my code
#include<stdio.h>

int main()
{

    char choice;

    printf("Do you want to enter a number:");
    scanf("%c",&choice);

    while(choice == 'y')
    {
      printf("Entered number\n");
      printf("Do you want to enter a number:");
      scanf("%c",&choice);

    }

    printf("End\n");

return 0;
}

and the output was
Do you want to enter a number:y
Entered number
Do you want to enter a number:End

for the first time, it checked whether my character is 'y' but in the loop after first time execution, it doesnot wait for user to type, it just terminates the loop . what might have gone wrong ?  please help

A: Take look at - http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1044873249&id=1043284392
#include<stdio.h>

int main()
{
    char choice;

    printf("Do you want to enter a number:");
    scanf("%c",&choice);

    while (choice == 'y')
    {
        while ((choice = getchar()) != '\n' && choice != EOF);
        printf("Entered number\n");
        printf("Do you want to enter a number:");
        scanf("%c",&choice);
    }

    printf("End\n");

    return 0;
}

DONOT USE : fflush Why fflush(stdin) is wrong


text:
Q: Calculating lens size for head mounted display I am trying to make a single-eye head mounted display in order to use with Drone - to see video from a drone with one eye and see drone with another one.
I have a 2.9" display (size of image is 52mm x 33mm) and need help to choose a correct lens to see the image as close as  possible to an eye. I tried already several lens:

*

*D=40mm, F=125mm, glass: I see area (about 90mm x 55mm) much bigger than required image (52mm x 33mm) and distance between the lens and display is too far

*D=40mm, F=40mm, fresnel: I almost can see required image, but it requires to put the lens extreamly close to an eye that is inconvinient

Could you please help with calculation of lens parameter to make an eye possible to see full 52mm x 33mm image produced by display. My calculation shows that it should be 24.9 mm between eye and "D=40mm, F=40mm" lens to see full 52mm x 33mm image produced by display, but that is wrong in reality.


text:
Q: How to delete all cloudwatch log groups and stream by date? After some time using AWS I find my cloudwatch is full of obsolete logs, is there a way to delete all log groups and streams by date? So I can clear all previous year logs.

A: While you can set the retention period on a stream as @DominikHelps said, that just deletes the messages; it will not delete the stream itself.
You can use the CLI to find the streams for a log group, along with the time they're created:
aws logs describe-log-streams --log-group-name Example --output text --query 'logStreams[*].[creationTime,logStreamName]' | sort -rn

This gives you output that looks like this:
1544374120302   stream1
1544373223032   stream2
1544365017774   stream3

The numbers are epoch timestamps, in milliseconds. You can use a tool like this to translate them into human-readable timestamps. Then, once you've identified the stream(s) that you want to delete, you can again use the CLI:
aws logs delete-log-stream --log-group-name Example --log-stream-name stream1

It's a fairly easy step from doing this manually to doing it as a cronjob. And if you don't mind programming, turning it into a Lambda that's invoked by a CloudWatch Events scheduled event.

A: Logs are kept indefinitely by default.
How ever you can set this by log group:
Log Retention—By default, logs are kept indefinitely and never expire. You can adjust the retention policy for each log group, keeping the indefinite retention, or choosing a retention periods between 10 years and one day.
More Info here:
https://docs.aws.amazon.com/en_en/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html
How to change log data retention:
https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html


text:
Q: Direction of Carnot cycle? My textbook states that

"If an engine is to do work on a sustained basis, the working substance must operate in a cycle; ie, the working substance must pass through a closed series of thermodynamic processes, called strokes, returning again and again to each state in every cycle."

I have not understood exactly why it is necessary for the heat engine to operate in a cycle. Why is the operation in a single direction less efficient than that in a cycle?
Please share your insights and help me. Much thanks in advance :-) Regards.
Edit: Although this question may, at first glance, come across as primitive and maybe even a little silly, I request you to please bear in mind that it has not been very long since I began my study of thermodynamics and also, I have only just graduated high school.

A: The engine is definitely more efficient if it is not a cycle, cycling back reduces efficiency.  But the reason it is necessary is that you want to keep it going, so you must return it to its initial state.  Consider the pistons in a car engine, it would be much better to just fire each piston and get a push on the axle and never compress the gas again, because compressing the gas removes energy from the axle.  But how could you drive a car down a road if you only fire each piston once?  That'd take a lot of pistons!

A: The second law of thermodynamics (Kelvin-Planck version) says that a heat engine cannot do work cyclically and isothermally. "Cyclically" is crucial - heat engines that do work isothermally but non-cyclically are trivial (e.g. a gas expanding reversibly).
By the way, heat engines that perform work cyclically and isothermally do exist. In this video one switches the capacitor on and off and the system can repeatedly lift floating weights:
http://www.youtube.com/watch?v=T6KAH1JpdPg
 "Liquid Dielectric Capacitor"
Switching the capacitor on and off involves no work done on the system so the energy for the work done BY the system (if it repeatedly lifts floating weights) can only come from the environmental heat, in violation of the second law.


text:
Q: StatusBar Padding automatically added on setNeedsLayout I want to display a ViewController from the bottom over the current ViewController, with a specific height. Then I added the ability to move the ViewController up, all the way behind the StatusBar. I implemented it with a UIPresentationController. It looks like this:

And now I have a big Problem: When I set a new Value to any label, the method setNeedsLayout gets called and the view of my presented ViewController adds padding of 20px to the top. It looks like this:

My Aim is to set the new Text to labels without triggering this padding insertion. Why is it even added? I tried setting the frame and bounds of the view manually, but it didn't work. The property automaticallyAdjustsScrollViewInsets didn't help either.

A: After some research I found out that I just could override the prefersStatusBarHidden method. By doing this, the status bar went away. Because the dialog is modal, I needed to add myDestinationController.modalPresentationCapturesStatusBarAppearance = true to make it work.
I hope it helps some people in the future!


text:
Q: Switch Case - Break e Return dentro de uma Função - Arduino Olá, boa tarde! Gostaria de compreender como o switch case funciona na linguagem C++ do Arduino. Tenho a seguinte situação hipotética:

estado_principal=0;
estados_Japão=0;

setup () {
}

loop {

switch case (estado_principal) {
    case 0:
    irparaJapão();
    estado_principal=1;
    break;

    case 1:
    irparaChina();
    estado_principal=2;
    break;

    case 2:
    irparaEUA();
    estado_principal=0;
}
}

void irparaJapão () {

switch case (estados_Japão) {

    case 0:
    comprarpassagem();
    estados_Japão = 1;
    break;

    case 1:
    checarbagagem();
    estados_Japão = 2;
    break;

    case 2:
    pegaroavião();
    return;

}
}

*

*Nessa situação, para eu sair do switch case dentro da função irparaJapão() e retornar para a próxima linha do código no loop principal (neste caso, estado_principal=1), basta o uso do comando return, como eu coloquei dentro do case 2 do switch case dentro da função irparaJapão()?

*Caso, por exemplo, eu esteja dentro do case 1 do switch case presente na função irparaJapão(), após executar checarbagagem(), na próxima linha eu declaro estado_Japão=2 (com o objetivo de declarar o valor da variável para a próxima execução do switch case). Após isso eu coloquei o break! O que esse break faz, em meu caso? O meu objetivo é permanecer na função e executar o case 2 do switch case! Como eu faço isso?
Obrigado desde já!


text:
Q: Unable to get a fresh aspnetcore .net5 react project to deploy using docker I'm quite new to docker, and have spent many hours trying to get this problem fixed. I am unable to deploy my aspnetcore react docker image to docker. I have successfully deployed many aspnetcore images, but when it comes to the SPA I cannot seem to figure it out. I started a fresh .net5 react project to test the docker file. I created a docker-compose file for the build. Each time i get the following error. Any help would be greatly appreciated.
The project is called dockerSPA - I created this specifically for testing purposes. Please let me know if i can supply additional information to solve this issue
Dockerfile
ARG NODE_IMAGE=node=16:0
FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app
EXPOSE 80

ENV NODE_ENV=production

FROM ${NODE_IMAGE} as node-build
WORKDIR /web
COPY DockerSPA/ClientApp/package.json .
COPY DockerSPA/ClientApp/package-lock.json .
COPY DockerSPA .

RUN npm i npm@7.12.1 -g && npm update && npm install && npm run build:prod
# RUN npm install -production

FROM mcr.microsoft.com/dotnet/sdk:5.0.102-ca-patch-buster-slim AS build
WORKDIR /src

COPY ["DockerSPA/DockerSPA.csproj", "DockerSPA/"]
RUN dotnet restore "DockerSPA/DockerSPA.csproj"
COPY . .
WORKDIR "/src/DockerSPA"
RUN dotnet build "DockerSPA.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "DockerSPA.csproj" -c Release -o /app/publish

COPY . .
COPY --from=node-build /web .

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "DockerSPA.dll"]

package.json scrips
 "scripts": {
    "start": "rimraf ./build && react-scripts start",
    "build": "react-scripts build",
    "build:prod": "npm start build",
    "test": "cross-env CI=true react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "lint": "eslint ./src/"
  },

docker-compose.yml
version: "3.9"  # optional since v1.27.0

services:

  nodejs:
    image: node:16

  webspa:
    container_name: dockerSPA
    build:
      context: .
      dockerfile: DockerSPA/Dockerfile
      args:
        NODE_IMAGE: ${NODE_IMAGE:-node:16.0}
    ports:
      -  "5200:80"
    depends_on:
      - nodejs

full docker error after using 'docker-compose up'
Building webspa
[+] Building 9.4s (23/26)
 => [internal] load build definition from Dockerfile                                                                                0.0s
 => => transferring dockerfile: 1.15kB                                                                                0.0s
 => [internal] load .dockerignore                                                                                0.0s
 => => transferring context: 35B                                                                                0.0s
 => [internal] load metadata for mcr.microsoft.com/dotnet/sdk:5.0.102-ca-patch-buster-slim                                                                                0.4s
 => [internal] load metadata for mcr.microsoft.com/dotnet/aspnet:5.0                                                                                0.0s
 => [internal] load metadata for docker.io/library/node:16.0                                                                                0.5s
 => [build 1/7] FROM mcr.microsoft.com/dotnet/sdk:5.0.102-ca-patch-buster-slim@sha256:1b832feb890536fdd31e0553587c40e33f9f0c7ce62bec3be6f1d2b4307c14f7                                                                                0.0s
 => [base 1/2] FROM mcr.microsoft.com/dotnet/aspnet:5.0                                                                                0.0s
 => [internal] load build context                                                                                0.0s
 => => transferring context: 3.42kB                                                                                0.0s
 => [node-build 1/6] FROM docker.io/library/node:16.0@sha256:25516f3de85ebf588e29d81052495d2e1177b55cddbd7ddab2f5ff2c4496dd5e                                                                                0.0s
 => CACHED [build 2/7] WORKDIR /src                                                                                0.0s
 => CACHED [base 2/2] WORKDIR /app                                                                                0.0s
 => CACHED [final 1/2] WORKDIR /app                                                                                0.0s
 => [build 3/7] COPY [DockerSPA/DockerSPA.csproj, DockerSPA/]                                                                                0.0s
 => CACHED [node-build 2/6] WORKDIR /web                                                                                0.0s
 => CACHED [node-build 3/6] COPY DockerSPA/ClientApp/package.json .                                                                                0.0s
 => CACHED [node-build 4/6] COPY DockerSPA/ClientApp/package-lock.json .                                                                                0.0s
 => CACHED [node-build 5/6] COPY DockerSPA .                                                                                0.0s
 => CANCELED [node-build 6/6] RUN npm i npm@7.12.1 -g && npm update && npm install && npm run build:prod                                                                                8.7s
 => [build 4/7] RUN dotnet restore "DockerSPA/DockerSPA.csproj"                                                                                3.0s
 => [build 5/7] COPY . .                                                                                0.1s
 => [build 6/7] WORKDIR /src/DockerSPA                                                                                0.1s
 => [build 7/7] RUN dotnet build "DockerSPA.csproj" -c Release -o /app/build                                                                                3.6s
 => ERROR [publish 1/3] RUN dotnet publish "DockerSPA.csproj" -c Release -o /app/publish                                                                                1.8s
------
 > [publish 1/3] RUN dotnet publish "DockerSPA.csproj" -c Release -o /app/publish:
#17 0.632 Microsoft (R) Build Engine version 16.8.3+39993bd9d for .NET
#17 0.632 Copyright (C) Microsoft Corporation. All rights reserved.
#17 0.632
#17 1.014   Determining projects to restore...
#17 1.200   All projects are up-to-date for restore.
#17 1.674   DockerSPA -> /src/DockerSPA/bin/Release/net5.0/DockerSPA.dll
#17 1.674   DockerSPA -> /src/DockerSPA/bin/Release/net5.0/DockerSPA.Views.dll
#17 1.719   /bin/sh: 2: /tmp/tmpbc0abd804da1470aa4bbde26647a85f4.exec.cmd: npm: not found
#17 1.721 /src/DockerSPA/DockerSPA.csproj(38,5): error MSB3073: The command "npm install" exited with code 127.
------
executor failed running [/bin/sh -c dotnet publish "DockerSPA.csproj" -c Release -o /app/publish]: exit code: 1
ERROR: Service 'webspa' failed to build : Build failed

EDIT
I have managed to finally get the react spa client to deploy by instead installing nodejs by following the old .net3 recommendations from microsoft with some small updates. Now My nodejs service exits right away with code 0;
DOCKER FILE
#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/dotnet/sdk:5.0.102-ca-patch-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
RUN curl -sL https://deb.nodesource.com/setup_16.x |  bash -
RUN apt-get install -y nodejs

FROM mcr.microsoft.com/dotnet/sdk:5.0.102-ca-patch-buster-slim AS build
RUN curl -sL https://deb.nodesource.com/setup_16.x |  bash -
RUN apt-get install -y nodejs

WORKDIR /src
COPY ["DockerSPA/DockerSPA.csproj", "DockerSPA/"]
RUN dotnet restore "DockerSPA/DockerSPA.csproj"
COPY . .
WORKDIR "/src/DockerSPA"
RUN dotnet build "DockerSPA.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "DockerSPA.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "DockerSPA.dll"]

errors:
dockerSPA | warn: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[60]
dockerSPA |       Storing keys in a directory '/root/.aspnet/DataProtection-Keys' that may not be persisted outside of the container. Protected data will be unavailable when container is destroyed.
dockerSPA | warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
dockerSPA |       No XML encryptor configured. Key {494d834e-82ff-4408-beab-6c6ad51cb722} may be persisted to storage in unencrypted form.
dockerSPA | warn: Microsoft.AspNetCore.Server.Kestrel[0]
dockerSPA |       Unable to bind to http://localhost:5000 on the IPv6 loopback interface: 'Cannot assign requested address'.
dockerSPA | warn: Microsoft.AspNetCore.Server.Kestrel[0]
dockerSPA |       Unable to bind to https://localhost:5001 on the IPv6 loopback interface: 'Cannot assign requested address'.

Something tells me i need to setup redis to handle these issues but i could be wrong.


text:
Q: Prove that if $B$ is an antisymmetric matrix, then $\det(B+I) \neq 0$ Prove that if $B$ is an antisymmetric matrix with real entries, then $\det(B+I) \neq 0$.

A: The matrix $B$ satisfies $B^T=-B$; suppose $\det(B+I)=0$; then there exists $x\ne0$ such that $(B+I)x=0$. It follows that $Bx=-x$ and so
$$
x^TBx=-x^Tx
$$
Transpose both sides, getting
$$
x^TB^Tx=-x^Tx
$$
and use the hypothesis $B^T=-B$ to get a contradiction.
(It can be made without contradiction, of course.)


text:
Q: Where do I find Crimbo Schematics? Where do I find Crimbo Schematics? I have heard of people getting Crimbo Schematics such as the Tripod or the Wrecking Ball, but I do not see the wiki giving any information and the information online isn't there.

A: The schematics drop rarely from any combat in the Kingdom.
The wiki usually is slow to update, but for anything regarding Crimbo this should be the page to check for news. At the moment it seems that the schematics still don't do anything.


text:
Q: Dropdown menu button [not dropdown menu] won't trigger click event after the first time I have a bootstrap 4 dropdown button, and I have a click listener attached to that button itself. When I click the dropdown button to open the menu,, the first time button onclick handler is getting hit. Then menu opens fine and if I click outside the menu closes as the default behavior of bootstrap dropdown.
But from then if I click the button to open the menu again, the button onclick handler not getting hit afterward.
I need to add this handler so that before each occasion of menu-open I can set some values within the dropdown menu items and then show it.
this js fiddle represents the issue
Link to JS Bin
How to solve this issue. Is it a problem of event bubbling?
Any way to overcome this?

$(document).on('click', '.MainButton', function(e){
  alert("opening dropdown");
})
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">

          Dropdown

          11111111
          22222222
          33333333


text:
Q: java stream - flatmap with method reference I am new to java and to stream so my question is why does this work:
This method is in my Tree class:
public Stream<Tree> flattened() {
    return Stream.concat(
            Stream.of(this),
            children.stream().flatMap(Tree::flattened));
}

flatMap wants a function with t as param and flattened method doesnt have input parameters at all
whats happening here?

A: There is indeed a hidden parameter in your function call.  Because flattened is a non-static method, there is an implicit parameter in your function, which is known as this.
Basically, you are calling flattened on each object in your stream, with the said element being your parameter.
EDIT (for clarification): Tree::flattened can mean one of two things.  It could mean:
tree -> Tree.flattened(tree) //flattened is a static method, which yours is not

or it could also mean:
tree -> tree.flattened() //flattened is an instance method, as in your case

further to that, it could also mean:
tree -> this.flattened(tree) //also doesn't apply to your case

From the JLS:

If the compile-time declaration is an instance method, then the target
  reference is the first formal parameter of the invocation method.
  Otherwise, there is no target reference