text:
Q: iOS Charts: Showing actual value with percentage inside PieChart? I'm currently using Charts - by Daniel Gindi, and following his demo, I've implemented a PieChart like so:

It was achieve using the following code:
func createPieChart(dataPoints: [String: Double])
{
    for index in 0..<sortedDates.count
    {
        let year = sortedDates[index]

        guard let costs = dataPoints[year] else {
            return
        }

        let dataEntry = PieChartDataEntry(value: costs, label: year)

        dataEntries.append(dataEntry)
    }

    chartDataSet = PieChartDataSet(values: dataEntries, label: "")

    chartData = PieChartData(dataSet: chartDataSet)

    chartDataSet.sliceSpace = 2.0

    chartDataSet.yValuePosition = PieChartDataSet.ValuePosition.outsideSlice

    ...

    pieChartView.usePercentValuesEnabled = true
    pieChartView.drawSlicesUnderHoleEnabled = false
    pieChartView.holeRadiusPercent = 0.40
    pieChartView.transparentCircleRadiusPercent = 0.43
    pieChartView.drawHoleEnabled = true
    pieChartView.rotationAngle = 0.0
    pieChartView.rotationEnabled = true
    pieChartView.highlightPerTapEnabled = false

    let pieChartLegend = pieChartView.legend
    pieChartLegend.horizontalAlignment = Legend.HorizontalAlignment.right
    pieChartLegend.verticalAlignment = Legend.VerticalAlignment.top
    pieChartLegend.orientation = Legend.Orientation.vertical
    pieChartLegend.drawInside = false
    pieChartLegend.yOffset = 10.0

    pieChartView.legend.enabled = true

    pieChartView.data = chartData
}

What I'm trying to achieve is to show the actual costs value inside the pie slice, but also include the percentage outside the slice. The percentage is shown using chartDataSet.yValuePosition = PieChartDataSet.ValuePosition.outsideSlice.
Inspecting the code, I noticed that in PieChartRenderer, there is there function open override func drawValues(context: CGContext) and within it, the code calculates the percentage of each pie slice in valueText:
let valueText = formatter.stringForValue(
                    value,
                    entry: e,
                    dataSetIndex: i,
                    viewPortHandler: viewPortHandler)

Then using an if check, it draws the percentage inside or outside the slice, which in my case is outside:
else if drawYOutside
{
    ChartUtils.drawText(
                        context: context,
                        text: valueText,
                        point: CGPoint(x: 0, y: labelPoint.y + lineHeight / 2.0),
                        align: align,
                        attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]
                        )
}

However, I can't find a way to actual include the costs value that is passed into PieChartDataEntry(value: costs, label: year).
I was told to subclass the Pie Chart and override the methods I found but I'm not exactly sure how to do that.
For example, the value of costs at each index in dataPoints is a double value of 100.0 for the label 2017 and 50.0 for the label 2016. I would like to include both those values in the associated pie slice.
Can anyone experienced with this library assist me?
Thanks!

A: Create a class that inherits from the PieChartRenderer and override the drawValues from the parent class like so:
public class CustomClass: PieChartRenderer
{
    override public func drawValues(context: CGContext)
    {
        // In this body, copy ALL code from parent class drawValues function

        ...
        let decimalFormatter = NumberFormatter()
        decimalFormatter.minimumFractionDigits = 2
        decimalFormatter.maximumFractionDigits = 2
        decimalFormatter.positivePrefix = "$"

        ...

        for i in 0 ..< dataSets.count
        {
            ...

            for j in 0 ..< dataSet.entryCount
            {
                ...

                guard let e = dataSet.entryForIndex(j) else { continue }
                let pe = e as? PieChartDataEntry

                // e.y = the actual value in the costs array, not the percentage
                let twoDecimalValue = NSDecimalNumber(value: e.y)
                let totalCost = decimalFormatter.string(from: twoDecimalValue)

                ...

                if drawXInside || drawYInside
                {
                    ...

                    if drawXInside && drawYInside
                    {
                        ...
                    }
                    else if drawXInside
                    {
                        if j < data.entryCount && pe?.label != nil
                        {
                            ChartUtils.drawText(
                                context: context,
                                text: pe!.label!,
                                point: CGPoint(x: x,
                                               y: y),
                                align: .center,
                                attributes: [NSFontAttributeName: yearValueFont,
                                             NSForegroundColorAttributeName: yearTextColor ?? percentageTextColor]
                            )

                            ChartUtils.drawText(
                                context: context,
                                text: totalCost!,
                                point: CGPoint(x: x,
                                               y: y + lineHeight),
                                align: .center,
                                attributes: [NSFontAttributeName: yearCostsValueFont,
                                             NSForegroundColorAttributeName: yearCostsTextColor]
                            )
                        }
                    }
                }
            }
        }
    }
}

Within the else if drawXInside, the first existing drawText function draws the label value, in my case, the year. Add another drawText function and pass in the totalCost value, which represents the actual value in the array `costs.
Then within the createPieChart function:
func createPieChart(dataPoints: [String: Double])
{
    ...

    pieChartView.data = chartData

    let customClass = CustomClass(chart: pieChartView,
                                  animator: pieChartView.chartAnimator,
                                  viewPortHandler: pieChartView.viewPortHandler)
    pieChartView.renderer = customRenderer
}

The result:

A: You need to change yValuePosition property to insideSlice
pieChartDataSet.yValuePosition = PieChartDataSet.ValuePosition.insideSlice

By default its inside but you specify as out side so its showing outside the chart.
Edit :
As per comment pls check below code which shows values not percentage in PieChart
func setPieChartData(lables: [String]!, values:[Double]!) {

        var valuesArray: [PieChartDataEntry] = []
        var colors: [UIColor] = []
        let valNSArray = values as NSArray

        valNSArray.enumerateObjects({ object, index, stop in
            //your code
            colors.append(self.getRandomColor())

            valuesArray.append(PieChartDataEntry(value: object as! Double, label: lables[index]))

        })

        let pieChartDataSet = PieChartDataSet(values: valuesArray, label: "Pie Data Chart")
        pieChartDataSet.colors = colors

        let piechartData = PieChartData(dataSets:[pieChartDataSet])
        pieChartDataSet.yValuePosition = PieChartDataSet.ValuePosition.insideSlice
        self.data = piechartData

}

Hope this will help.


text:
Q: Memory allocation problems with android application I have an android application that performs image analysis, which is managed with an IntentService - the process takes a couple of seconds each time and works accurately and quickly.
But when the process is repeated in the app around 50 times (as illustrated) it begins to get very slow until the point in which the app and device becomes unusable. When the device is restarted and app opens again it runs as usual.
Inspecting with Android Studio I can see that each time I run the analysis that the memory allocation for the app goes up and up every time by around 1MB. So it is clearly running out of memory when it crashes.
I have used this flag on finishing the analysis and going to the result to try fix background activities;
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

which has had minimal effect, and I understand the IntentService manages itself shutting down. So not sure what else I can do to try and reduce the memory allocation or at least clear down allocation and stop adding to it?

Further details:

*

*The application is using the camera implementation based on Google Camera2

*The analysis is done with a C++ library through the IntentService

A: Try using leakCanary https://github.com/square/leakcanary to find out what is causing the leak and use a weakReference https://developer.android.com/reference/java/lang/ref/WeakReference.html to allow it to be garbage collected when necessary. It may also be that the device you are using does not have enough memory to hold 50 high res images in memory at the same time. You could try lowering the resolution of the images if you are keeping them in memory and be sure you are recycling bitmaps https://developer.android.com/topic/performance/graphics/manage-memory.html
I would also consider using a threadPoolExecutor instead of an intent service, they are much more configurable https://developer.android.com/reference/java/util/concurrent/ThreadPoolExecutor.html

A: It seems you are not handling the resources (variables, image files,etc) properly, and its creating memory leaks in your application.
you can find here in this blog Written by Johan  on handling the memory leaks in your application or see this SO Question.
Avoid memory leaks on Android
If the memory leaks are being generated in the c++ library then you can easily find the resource which is leaking the memory in debug mode.
After the result activity you should call the garbage collector as suggested by Grisgram and close any unused resources.
It would be good if you could provide the stack trace in the question.

A: I wanted to add something to Ali786's answer.
Intent Services are not really the best choice for something that is going to repeat itself. The next time you call the service it goes into a queue.
Intent Services work like HandlerThreads. They have their own MessageQueues and after you start the service with Intent it will wait for the previous one.
Normal services which run on the UI Thread are running in parallel.
I am not sure if you are doing something after you send the information of the analys to your activity, but if you do, the intent service will not die and the next one will have to wait. Intent services are not the best choice for communicating with your UI Thread, Asynctask might be better in your case. If you give us some more information (code) maybe we can give you a more accurate answer.
Hope this helps!

A: One thing may be it happens like this, If your working intent service after job complete may be your not destroy the service
Check in settings running service list for running service of your app

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to import files in python using sys.path.append? There are two directories on my desktop, DIR1 and DIR2 which contain the following files:
DIR1:
file1.py

DIR2:
file2.py  myfile.txt

The files contain the following:
file1.py
import sys

sys.path.append('.')
sys.path.append('../DIR2')

import file2

file2.py
import sys

sys.path.append( '.' )
sys.path.append( '../DIR2' )

MY_FILE = "myfile.txt"

myfile = open(MY_FILE)

myfile.txt
some text

Now, there are two scenarios.  The first works, the second gives an error.
Scenario 1
I cd into DIR2 and run file2.py and it runs no problem.
Scenario 2
I cd into DIR1 and run file1.py and it throws an error:
Traceback (most recent call last):
  File "<absolute-path>/DIR1/file1.py", line 6, in <module>
    import file2
  File "../DIR2/file2.py", line 9, in <module>
    myfile = open(MY_FILE)
IOError: [Errno 2] No such file or directory: 'myfile.txt'

However, this makes no sense to me, since I have appended the path to file1.py using the command sys.path.append('../DIR2').
Why does this happen when file1.py, when file2.py is in the same directory as myfile.txt yet it throws an error?  Thank you.

A: Replace
MY_FILE = "myfile.txt"
myfile = open(MY_FILE)

with
MY_FILE = os.path.join("DIR2", "myfile.txt")
myfile = open(MY_FILE)

That's what the comments your question has are referring to as the relative path solution.  This assumes that you're running it from the dir one up from myfile.txt... so not ideal.
If you know that my_file.txt is always going to be in the same dir as file2.py then you can try something like this in file2..
from os import path

fname =  path.abspath(path.join(path.dirname(__file__), "my_file.txt"))
myfile = open(fname)

A: You can create a path relative to a module by using a module's __file__ attribute.  For example:
myfile = open(os.path.join(
    os.path.dirname(__file__),
    MY_FILE))

This should do what you want regardless of where you start your script.


text:
Q: How to compute $\chi_1$, a Lorentzian absorption in the following paper? I have the following paper:
https://arxiv.org/abs/1508.01213
on the third page, where they take: $$\chi_2(\omega)= \frac{-k\gamma}{(\omega-\omega_0)^2+\gamma^2},$$ I don't see how to explicitly compute $\chi_1$.
Can someone please show me the way?

A: I realised after writing this that the OP probably doesn't need this answer any more, but anyway:
You need to use the Kramers-Kronig relations which connect the real and imaginary parts of any complex function $\chi(\omega) = \chi_1(\omega) + i \chi_2(\omega)$ that is analytic in the upper half-plane.
In particular, the relation you need (as described in the paper) is:
$$\chi_1(\omega) = \frac{1}{\pi} \mathcal{P} \int_{-\infty}^\infty \frac{\chi_2(\omega')}{\omega'-\omega} \text{d}\omega',$$
where $\mathcal{P}$ denotes the "Cauchy principal value".


text:
Q: SQL find part of string I met following problem:
I've got table 'students' with columns: 'id_student', 'name' and 'surname'.
Then I got a variable that contains full_name (example: 'James Bond')
I need to make a query that selects 'id_student' where 'name' and 'surname' matches whole name.
I tried to do this in several ways, like:
SELECT id_student FROM students WHERE name+' '+surname LIKE full_name

but it doesn't work. Any idea?

A: Your code should work in a database where + is used for string concatenation.  The LIKE is fine, but = seems sufficient:
SELECT id_student
FROM students
WHERE CONCAT(name, ' ', surname) = full_name;

Note that unexpected characters and small differences in spelling would cause the comparisons to fail.

A: MySQL does not support string concatenation using plus, at least not by default.  Instead, we can use the CONCAT function.  The LIKE expression you want here is:
full_name LIKE 'James%Bond'

Here we want any record which starts with James and ends with Bond.
SELECT id_student
FROM students
WHERE full_name LIKE CONCAT(name, '%', surname);

A: Maybe you should try something like:
SELECT id_student
FROM students
WHERE CONCAT_WS(" ", name, surname)
LIKE full_name

CONCAT_WS or CONCAT is the MySQL function to join strings. The former allows you to define a separator, a space in your case.


text:
Q: Ruby, max value from an hash of arrays I have this hash
FORMATS = {
    'vertical_4'   => %w[vertical small small small small],
    'horizontal_4' => %w[horizontal small small small small],
    'horizontal_2' => %w[large small small],
    'mixed_3'      => %w[vertical horizontal small small],
    'huge'         => %w[horizontal small small horizontal small small small]
  }

I need the max value, so I use
MAX_ELEMENTS   = FORMATS.map {|_,v| v}.max.size

Why it returns 5 instead of 7?

A: The array with the greatest number of elements
FORMATS.values.max_by(&:count)

A: You asked why, so I'm going to break this down step by step, first we know map returns an array of values (same as FORMATS.values)
FORMATS.map {|_,v| v}
=> [
 ["vertical", "small", "small", "small", "small"],
 ["horizontal", "small", "small", "small", "small"],
 ["large", "small", "small"],
 ["vertical", "horizontal", "small", "small"],
 ["horizontal", "small", "small", "horizontal", "small", "small", "small"]
]

We then call Array#max without any arguments or a block which according to the docs:

Returns the object in ary with the maximum value. The first form assumes all objects implement Comparable;

In your case, each element is an array and since array does respond to the comparable operator <=>
it runs each element against each other like this:
FORMATS.map {|_,v| v}.max { |a, b| a <=> b }

However Array#<=> does it's own comparison element by element:

Arrays are compared in an "element-wise" manner; the first element of ary is compared with the first one of other_ary using the <=> operator, then each of the second elements, etc… As soon as the result of any such comparison is non zero (i.e. the two corresponding elements are not equal), that result is returned for the whole array comparison.

However when we call max we get back the first item in the array, why?
FORMATS.map {|_,v| v}.max
=> ["vertical", "small", "small", "small", "small"]

That's because if we look at this element-by-element, the first value is "vertical" and "vertical" is >= every first element for the other arrays which then leaves us only with the first element:
 ["vertical", "small", "small", "small", "small"]

and the 4th element
 ["vertical", "horizontal", "small", "small"]

If we then compare the second elements, small is > horizontal and we're done, the first element is the max.
You then call size on the max element which is 5.

A: If you want the max of the size of the arrays you need:
FORMATS.map {|_,v| v}.map(&:size).max

Map the value of the arrays to their size and select max of that array.
UPDATE better answer no need for 2nd map:
FORMATS.map{|_,v| v.size}.max

To explain why your code gave you the result it did, .max uses logic to get the max on enumerable.  So if it compares array of strings it will look for the max by alphabetic sort.
[['aaa','bbb'],['ddd','ccc'], ['bbb','ccc']].max #=> returns ["ddd", "ccc"]

Your code was mapping the values to array, calling .max on that, which would give the highs max by alpha sort, then calling .size on that, just gives size of array.

A: You can make use of max iterator with a block
FORMATS.values.max { |values| values.length }.size


text:
Q: seeding java.security.SecureRandom unnecessary? I am using Java 1.7 and as the code below demonstrates (compiled with Oracle's Java 7 compiler in Ubuntu) seeding java.security.SecureRandom appears to be unneccessary as the code produces two different BigIntegers for the starting value of the two pseudo-random sequences:
import java.security.SecureRandom;
import java.math.BigInteger;

public class SessionIdTest {

    public static void main (String args[]) {
    long seed = System.currentTimeMillis();
        {
            SecureRandom random = new SecureRandom();
            random.setSeed(seed);
            BigInteger a = new BigInteger(130, random);
            System.out.println(a);
        }
        {
            SecureRandom random = new SecureRandom();
            random.setSeed(seed);
            BigInteger a = new BigInteger(130, random);
            System.out.println(a);
        }
    }
}

What's the purpose of setSeed then? Or is SecureRandom also using, in addition to the seed, some other source of randomness?

A: The javadoc says:

Many SecureRandom implementations are in the form of a pseudo-random number generator (PRNG), which means they use a deterministic algorithm to produce a pseudo-random sequence from a true random seed. Other implementations may produce true random numbers, and yet others may use a combination of both techniques.

So, counting on a secure random to generate a deterministic sequence of values by seeding it won't necessarily work, as documented.

A: JavaDoc says:
Reseeds this random object, using the eight bytes contained
in the given long seed. The given seed supplements,
rather than replaces, the existing seed. Thus, repeated calls
are guaranteed never to reduce randomness.

A: Seeding a SecureRandom by calling java.security.SecureRandom#setSeed is not necessary, and actually, shouldn't be done unless you have a really good source of entropy and java.lang.System#currentTimeMillis definitely is not one.
Now, from your example where it was producing two different outputs even when the seed was the same. It is a behaviour that I observed in the DRBG SecureRandom implementation in Java 10, where both random numbers produced will differ during one execution but will remain constant if the program restarts:
public class SessionIdTest {

    public static void main (String args[]) throws NoSuchAlgorithmException {
        // Hardcoded seed to evidence the deterministic behavior when the program restarts.
        long seed = 1000;
        {
            SecureRandom random = SecureRandom.getInstance("DRBG");
            random.setSeed(seed);
            BigInteger a = new BigInteger(130, random);
            System.out.println(a);
        }
        {
            SecureRandom random = SecureRandom.getInstance("DRBG");
            random.setSeed(seed);
            BigInteger a = new BigInteger(130, random);
            System.out.println(a);
        }
    }
}

So the previous will always generate something like this:
724996208419722369188940556616693042555
796664555436785984208644362540465534270

And the differing values in one execution have its cause in a global state being updated every time a DRBG implementation is created.
Now, if you try the SHA1PRNG implementation, both random numbers will be the same and they will remain constant through program restarts:
public class SessionIdTest {

    public static void main (String args[]) throws NoSuchAlgorithmException {
        // Hardcoded seed to evidence the deterministic behavior when the program restarts.
        long seed = 1000;
        {
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(seed);
            BigInteger a = new BigInteger(130, random);
            System.out.println(a);
        }
        {
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(seed);
            BigInteger a = new BigInteger(130, random);
            System.out.println(a);
        }
    }
}

So the previous will always generate something like this:
251586625089438840547467272692377284989
251586625089438840547467272692377284989

Finally, in both cases you can confirm that there is a deterministic behavior based on the provided seed, so, do not seed these SecureRandoms manually unless you have a very good source of entropy and again, the current time is not one!. Just let them seed themselves which is safer.


text:
Q: Redirecting node.js output to text file using shell script I want to redirect the output of node.js to txt file.I am able to get the output in console for node.js.
Please help me in this issue.
This is the snippet:
node.forEach(function(elem)
{
var toString=elem.path.toString;
console.log(toString);
}

Output looks something like this
ui.apps/src/main/content/jcr_root/components/content/smartcart/deviceselector/cq_editConfig.xml
ui.apps/src/main/content/jcr_root/components/content/smartcart/deviceselector/deviceselector.html

A: Writing a string to a file
If you are just trying to save the output from that one particular function, you can use the fs node core module
var fs = require("fs");

var output = "";
for (var i = 0; i < node.length; i++) {
    var elem = node[i];
    output += elem.path.toString() + "\n";
}

fs.writeFile("output.txt", output, function (err) {
    if (err) {
        return console.log(err);
    }
    console.log("output.txt saved");
});

Writing all output to a file
If you are trying to capture everything that is logged to a log file, you have a number of options:

*

*Use a loggin package such as winston.js which provides ways of writing logs to a specified file

*On a unix-based system, pipe the output of node to a file
node my-file.js > output.txt

A: fs = require('fs');
fs.appendFile(__dirname + '/textFileName.txt', toString, function (err) {
    if (err) return console.log(err);
    console.log('Hello World > helloworld.txt');
});


text:
Q: How to use sleep in qt creator I am using Qt Creator C++. I want to see these two pictures after each other every 3 seconds. But according to my code, it shows just the last image on the screen. Does anybody have any idea what I am doing wrong?

A: I think that exec(); is the moment where program starts, so you have to change pictures after that. I Would pastle this code inside youre main class, or inside some other function (for example button slot).

A: You shall use QElapsedTimer() and implement a slot which you shall then connect to QElapsedTimer's signal that is emitted after desired time. See Qt help for more information on that.
In the slot, you shall implement your logic of showing the images.


text:
Q: Is it possible to define jetty server in eclipse runtime environment? I have created a REST WS application using eclipse WTP. So far, I was using Tomcat 7 to deploy my application. I could define Tomcat into Server runtime environments. Now i want to use jetty for to deploy that application, I downloaded jetty 8 and I have eclipse Indigo .. tried to define jetty the way i did for Tomcat but it did not work because the available adapter is for jetty6 and when I try to run my application using this adapter, I get a message saying  the server does not suport version 3.0 of J2EE Web module specification
How can I run my application on jetty from eclipse?

A: jetty 6 supports only jsp/servlets 2.5 specification, so you need to use jetty8 with servlets/jsp 3.0 support
use maven to add jetty 8 like this
<dependency>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-server</artifactId>
        <version>${jetty.revision}</version>
    </dependency>
    <dependency>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-webapp</artifactId>
        <version>${jetty.revision}</version>
    </dependency>
    <dependency>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-servlet</artifactId>
        <version>${jetty.revision}</version>
    </dependency>

where jetty version is for example this one
8.1.5.v20120716


text:
Q: Absolute convergence of $\sum_{n=1}^{\infty} \frac{\sin(2n)}{\sqrt{n}}$ I have to discuss the conditional and absolute convergence of the series:
$$\sum_{n=1}^{\infty} \frac{\sin(2n)}{\sqrt{n}}$$
I believe such a series is conditionally convergent but not absolutely convergent, but I lack some evidence.

A: It is not absolutely convergent. It follows from the equidistribution of the sequence $\{e^{in}\}_{n\in\mathbb{N}}$ in $S^1$, or from the Dirichlet box principle: among three consecutive integer numbers, $\left|\sin(2n)\right|\geq\frac{1}{2}$ holds for at least one of them, hence:
$$ \sum_{n=1}^{3N}\frac{|\sin(2n)|}{\sqrt{n}}\geq \frac{1}{2}\sum_{i=1}^{N}\frac{1}{\sqrt{3i}}\geq \sqrt{\frac{N}{3}}-\frac{1}{2}.$$
On the other hand, the series is conditionally convergent by Dirichlet's test, since $\frac{1}{\sqrt{n}}$ decreases to zero and the partial sums of $\sin(2n)$ are bounded.

A: Another way to show that the series does not converge absolutely is to use
$\displaystyle\frac{\lvert \sin 2n\rvert}{\sqrt{n}}\ge\frac{\sin^2 2n}{\sqrt{n}}=\frac{1}{2}\left(\frac{1-\cos 4n}{\sqrt{n}}\right)=\frac{1}{2}\left(\frac{1}{\sqrt{n}}-\frac{\cos 4n}{\sqrt{n}}\right)$,
where $\displaystyle\sum_{n=1}^{\infty}\frac{1}{2}\left(\frac{1}{\sqrt{n}}-\frac{\cos 4n}{\sqrt{n}}\right)$ diverges
since $\displaystyle\sum_{n=1}^{\infty}\frac{1}{\sqrt{n}}$ diverges and $\displaystyle\sum_{n=1}^{\infty}\frac{\cos 4n}{\sqrt{n}}$ converges by Dirichlet's test.

A: The absolute series diverges.  To see this we just need to argue that Sin(2n) isn't near 0 terribly often, which is the same as asking that 2n not be near a multiple of $\pi$ terribly often.  An ungraceful way to see that is to note that if, say, |2n - k$\pi$| < .01 then neither 2n - 2 nor 2n + 2 can be within .01 of any multiple of $\pi$ (as multiples of $\pi$ are separated by something greater than 3).  Thus deleting all the terms corresponding to  |2n - k$\pi$| < .01 means that, at worst, you are only taking out 1 term in 3.  And the surviving terms are each ≥ $\frac{sin(.01)}{\sqrt{n}}$.  The comparison now goes in the correct direction.
Note:  I did warn that this was ungraceful.  I expect it diverges conditionally as well, but do not know for certain.

A: An idea: You can try Dirichlet test. You have that $\frac{1}{\sqrt{n}}$ converges to zero monotonically, and the only trouble is partial sums of the sine. Here the complex exponential and geometrical series may be of help.


text:
Q: Problemas con Vectores ,Maps y Pairs en c++; Hola buenas me gustaría saber como acceder al contenido de este template en c++;
vector<map<pair<int, int>, double>> m_deltaQ;

con dos numeros int por ejemplo 3 , 4 como sacar el valor double

A: personalmente preferiría usar una clase para ese tipo de diseño, sin embargo, si deseas acceder deberías tener el cuenta que lo primero que debes identificar es el mapa donde se encuentra el dato que buscas. El siguiente código te devuelve el valor, teniendo en cuenta que solo hay un mapa y es el primero del vector.
vector<map<pair<int, int>, double>> m_deltaQ;
map<pair<int, int>, double> mapa;
pair<int, int> pareja(3,4);

mapa.insert(pair<pair<int,int>,double>(pareja,10.5));
m_deltaQ.push_back(mapa);

cout<< m_deltaQ[0].find(pair<int, int>(3, 4))->second <<endl;

A: En primer lugar, sería aconsejable crear alias de tipos para dar un significado semántico a cada estructura de datos:
using key = std::pair<int, int>;
using delta = std::map<key, double>;
using delta_pack = std::vector<delta>;

Con estos alias, podrías insertar datos así:
delta_pack m_deltaQ;
//                       delta
//                  vvvvvvvvvvvvvv
m_deltaQ.push_back({{{3, 4}, 10.5}});
//                   ^^^^^^
//                     key

Para acceder al double de delta:
std::cout << m_deltaQ[0][{3, 4}]; // Muestra 10.5

El problema del ejemplo anterior es que si el elemento {3, 4} no existiera, se crearía con valor 0.0, si quieres evitar crear elementos accidentalmente debes evitar el operador de indizado ([]) de std::map:
const delta &d = m_deltaQ[0];
const delta::const_iterator k = d.find({3, 4});

if (k != d.end())
    std::cout << k->second; // Muestra 10.5


text:
Q: Remine installation on Fedora 27 Greats everybody,
I have a problem with the gem nokogiri when i ask rake to generate secret token for redmine...
Here is the console dialog :

[root@macbeth redmine]# /usr/local/bin/rake generate secret token
[!] There was an error parsing Gemfile: Illformed requirement ["1.8.2 ruby java x64-mingw32 x86-mingw32"]. Bundler cannot continue.
                                                                                #  from /var/www/redmine/Gemfile:116
   #  -------------------------------------------
   #
   gem 'nokogiri', '1.8.2 ruby java x64-mingw32 x86-mingw32'
   #  -------------------------------------------

Any help welcome !
Thanks, Regards,
Franck

A: Well sorry for inconvenience my informations were out of date...
Better results with redmine-3.4.4.zip file and this procedure actualised :
http://www.redmine.org/projects/redmine/wiki/redmineinstall


text:
Q: Ruby On Rails retrieve mysql database data 'a' distinct 'b' My database have a device reading list,
columns are id ,device_id ,device_reading ,update_time
How can I select all latest reading for each device?
that means,I need sort data according to update_time first
then I need to filter database use some unique method(unique device_id)
then the I can retrieve device_reading from rows filtered just now.
That is to say, retrieve column a from table where b is distinct
how can I achieve this? in ruby on rails
thanks in advance

A: Supposing that model name is DeviceReading
DeviceReading.distinct(:device_id).order('update_time DESC').pluck(:device_reading)

You can use ASC in place of DESC if you want to sort by ascending order
Source: Distinct and pluck sort/order
EDIT: The distinct only works in rails 4 so if you are using rails 3 you should do something like this:
DeviceReading.select(:device_id).uniq.pluck(:device_reading)

However when I chain .order('update_time DESC') in above I get mysterious error. I am trying to find solution. meanwhile I Hope this helps you.
Source: distinct undefined error

A: This questions looks quite similar to the one below:
Select first row in each GROUP BY group?
In the case when no elegant solution can be found the Rails way, you can first figure out the correct sql and use find_by_sql to retrieve the dataset.


text:
Q: CS231n: Total memory of VGGnet I'm reading this CS231n tutorial, about convolutional neural networks. They give an example about VGGNet:
http://cs231n.github.io/convolutional-networks/

VGGNet in detail. Lets break down the VGGNet in more detail as a case
  study. The whole VGGNet is composed of CONV layers that perform 3x3
  convolutions with stride 1 and pad 1, and of POOL layers that perform
  2x2 max pooling with stride 2 (and no padding). We can write out the
  size of the representation at each step of the processing and keep
  track of both the representation size and the total number of weights:

Then they give a detailed calculation of the network structure:

But the thing is, for total memory, the tutorial gives the result of 24M, but when I calculated it I only got about 15M ! I simply added all of the memories:
>>> 224*224*(3+64*2)+112*112*(64+128*2)+56*56*(128+256*3)+28*28*(256+512*3)+14*14*(512*4)+7*7*512+4096+4096+1000
15237608

Please help me.

A: Nice catch! Your calculation is correct, total memory of VGG representation is indeed
15.2M * 4 bytes ~= 61Mb

In fact, this error has been reported long time ago, but unfortunately CS231n staff doesn't spend too much time on website maintenance...
However, note that if you code VGG network in any framework (Caffe, Tensorflow, etc), the total model size will include the parameters and this part is much larger, as the authors also show in their calculations (which seems right).


text:
Q: Python 3.x: Pandas DataFrame How to overwrite csv files (batch process) I have a bunch of csv files in a folder. I was batch-processing the csv files.
But when I read it using my pandas dataframe, it reads the files as the followings.
0     -1     4650.0         NaN
1      0        0.0         NaN
2      1        0.0         NaN
3      2        0.0         NaN
4      3        0.0         NaN
5      4        0.0         NaN
6      5        0.0         NaN

I have many many csv files in this directory. I want to delete the last columns and overwrite it in the same filename. Any idea? I can't possibly open all the files and store it as variables and delete the column.

A: I think you could just not read the last column.
If your original file has 3 columns, then pd.read_csv('filepath', usecols=[0, 1]) should do the trick.
This way, you would be using only columns 0 (first) and 1 (second).

A: The answer posted by @victor-valente is the better approach to processing those csv files. However, if you still want to remove that Nan column from the files altogether, you can do something like this -
import glob
import pandas as pd
csv_files = list(glob.glob("path/to/directory/*.csv"))
for i in csv_files:
    pd.read_csv(i, usecols=[0,1,2]).to_csv(i)

This should overwrite the existing files after having removed that 4th empty column.
Something simpler would be to just do a df.dropna(axis='columns', how='all', inplace=True) on the df you have built after batch processing your csv files. This would drop any columns that only contain NaN values.


text:
Q: SwitchTo for ui-dialog with webdriver c# The login section of the website i'm testing appears in a dialog that doesn't seem to be a new window pop-up or an alert ( i have tried to SwitchTo()Alert() but it doesn't detect it as Alert; i don't know the name of the iframe or window to switch to it like that as it doesn't seem to be that kind of a dialog).
Is there a way i can switch to something defined like this in order to find the username and password text fields so i can login?

Should i rather try finding the elements (username and password) directly with FindElement(By.xpath())?
My code is this:
        IWebElement login = driver.FindElement(By.Id("login-button"));
        login.Click();

        WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
        wait.Until<bool>((d) =>
        {
            return driver.FindElement(By.Id("username")).Displayed;
        });
        IWebElement username = driver.FindElement(By.Id("username"));

        nickname.SendKeys("some_user");
        IWebElement password = driver.FindElement(By.Id("pass"));
        password.SendKeys("some_password");

If i don't wait for the username to be displayed it will show me this:
        NoSuchElementException was unhandled: Unable to locate element: {"method":"id", "selector":"username"}.

Otherwise the wait times out.


text:
Q: Нужно ли загружать на сайт шрифты open-sans, sans-serif? будет выглядеть так
font-family: open-sans, sans-serif;
Эти шрифты предустановлены в ОС, так что нужно ли их всё равно грузить через @font-face?

A: Не только этот, но и любой другой @font-face надо описывать так, чтобы он в начале искал шрифт в самой системе. Гугл-шрифты так и делают, кстати:
@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 400;
  src: local('Open Sans Regular'), local('OpenSans-Regular'), url(https://fonts.gstatic.com/s/opensans/v15/K88pR3goAWT7BTt32Z01mxJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
  unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}

А Open Sans, кстати, предустановлен не в любой ОС, потому да, его необходимо описывать в @font-face.


text:
Q: New Windows XP updates started to show up in fall 2014 Since Windows XP support ended in April 2014, my automatic update client went quiet. But about two months ago updates started to show up in it again!
Naturally, I was suspicious that Microsoft might be trying to break existing installations and examined what was listed there (my settings are "ask to download and ask to install"):

*

*Most of them are old security updates for "Windows XP" and .NET Framework, mostly from 2013 (examples: KB2893984, KB2833940). These do fit the "break existing installations" pattern since installing them over newer ones will re-introduce security holes that were patched later on;

*Some are updates for MS Office 2007 (e.g. KB2883032). These seem legit since it is still supported;

*Some are OS-independent, like the malicious software removal tool. Same as the previous one.
The questions are:

*

*Did any security specialists analyze these strange new updates? (assuming I'm not the only one who experiences this phenomenon)

*Can anyone shed more light on what is going on?

A: Examining system metadata on the installed updates with wmic qfe list brief shows no updates for WinXP and .NET Framework. This must be the reason.
Description                                                                                FixComments  HotFixID             InstallDate  InstalledBy  InstalledOn  Name  ServicePackInEffect  Status
                                                                                File 1                                                            KB2936068-IE7
                                                                                File 1                                                            KB2964358-IE7
                                                                                File 1                                                            KB835221WXP
                                                                                Q147222
Исправление для MSXML 2 (KB887606)                                                                Update       KB887606_26                       SYSTEM       7/15/2008          SP6
Security update for MSXML4 SP2 (KB954430)                                                                                Q954430                                        16.02.2009
Security update for MSXML4 SP2 (KB973688)                                                                                Q973688                                        30.10.2010
Security update for MSXML4 SP3 (KB2758694)                                                                                Q2758694                                       06.10.2016
Microsoft Internationalized Domain Names Mitigation APIs                                                                     IDNMitigationAPIs                                                 SP1
Microsoft National Language Support Downlevel APIs                                                                           NLSDownlevelMapping                                               SP1
Hotfix for Windows Media Format 11 SDK (KB929399)                                                                            KB929399
Обновление безопасности для проигрывателя Windows Media - (KB2378111)                  KB2378111_WM9
Обновление безопасности для проигрывателя Windows Media - (KB2834904-v2)               KB2834904-v2_WM11
Обновление безопасности для проигрывателя Windows Media - (KB952069)                   KB952069_WM9
Обновление безопасности для проигрывателя Windows Media - (KB954155)                   KB954155_WM9
Обновление безопасности для проигрывателя Windows Media - (KB973540)                   KB973540_WM9
Обновление безопасности для проигрывателя Windows Media - (KB975558)                   KB975558_WM8
Обновление безопасности для проигрывателя Windows Media - (KB978695)                   KB978695_WM9
Hotfix for Windows Media Player 11 (KB935957)                                                                                KB935957
Исправление для проигрывателя Windows Media 11 - (KB939683)                                       KB939683
Обновление безопасности для проигрывателя Windows Media 11 - (KB954154)                KB954154_WM11
Обновление безопасности для проигрывателя Windows Media 6.4 - (KB925398)               KB925398_WMP64
Обновление безопасности для проигрывателя Windows Media 9 - (KB936782)                 KB936782_WMP9
Обновление безопасности для Windows Internet Explorer 7 (KB2964358)                    Update       KB2964358-IE7                     SYSTEM       5/3/2014           SP0
High Definition Audio Driver Package - KB835221                                                                 Update       KB835221WXP                       Admin        10/16/2016         SP10
XML Paper Specification Shared Components Pack 1.0                                                                           XpsEPSC

After having the updates downloaded, I checked a few ones and did see that the files on my system have earlier versions than the ones in updates. So I indeed don't have them installed, it's not just broken metadata.
Most probably, I did a system restoration from the installation media at some point -- that's how they went missing. Judging by the older file versions and the fact that updates for libraries like MSXML that are not installed by the system setup are intact, this does seem to be the case.

A: Even though Microsoft doesn't release new updates for Windows XP, they still supply existing updates. - They are available if somebody wants to make a new installation of Windows XP (about 250 updates!).
If you have installed other Microsoft programs lately, like MS Office, which is still supported, you might receive updates, that could be related to Windows XP.
As you have noticed, the "Malware-remover" (Windows Defender), still goes out monthly.
If you've changed from Windows Update to Microsoft Update (there's a link on Windows Update homepage), you might get a lot of "new" updates. - If not, you better do. Nobody knows how long they will be available. ;o)
Microsoft Update works a little slower, but it will update ALL Microsoft software.


text:
Q: Mocking Unirest with mockito I am in my starting programming phase and I wanted to ask about mocking Objects with Mockito, more specifically is the Unirest response.
Let's say I have a database, and I dont what to bother it every time I do testing, and I want to use Mockito for that, but the problem is I am not sure how to create the fake "httpResponse" object that will come back.
To give some context, I have attached my code:
    /**
 * This method lists the ID of the activity when requested.
 *
 * @return the list of all activities
 */
public  JSONArray getActivites() {
    HttpResponse<JsonNode> jsonResponse = null;
    try {
        jsonResponse = Unirest
                .get("http://111.111.111.111:8080/activity")
                .header("accept", "application/json")
                .asJson();
    } catch (UnirestException e) {
        System.out.println("Server is unreachable");
    }

    JSONArray listOfActivities = jsonResponse.getBody().getArray();
    return listOfActivities;
}

So what I had in mind, is to mock Unirest, and then when a .get method gets invoked, I would return a fake HttpResponse, problem is, I am not sure how to, I have looked online and couldn't really make much sense of it.
Is it possible to do it 1 time with the actual Database, and then "Extract" the information and to use that every time for testing?

A: Sample Snippet with   PowerMockRunner, PowerMockito and Mockito
@RunWith(PowerMockRunner.class)
    @PrepareForTest({ Unirest.class})
    public class TestApp{

      @Before
      public void setup() {
        PowerMockito.mockStatic(Unirest.class);
      }

      @Test
      public void shouldTestgetActivites() throws UnirestException {
        when(Unirest.get(Client.DEFAULT_BASE_URL)).thenReturn(getRequest);
        when(getRequest.asJson()).thenReturn(httpResponse);
        when(httpResponse.getStatus()).thenReturn(Integer.valueOf(200));

        assertThat(something).isEqualTo(true);
      }

    }

A: Instead of directly calling a static member, you could wrap the call in a wrapper class that can supply an HttpResponse based on some arguments. This is an interface that can easily be mocked in Mockito.
/**
 * This is a wrapper around a Unirest API.
 */
class UnirestWrapper {

    private HttpResponse<JsonNode> getResponse(String accept, String url) {
        try {
            return Unirest
                .get(url)
                .header("accept", accept)
                .asJson();
        } catch (UnirestException e) {
            System.out.println("Server is unreachable");
        }
        // Or create a NULL HttpResponse instance.
        return null;
    }
}

private final UnirestWrapper unirestWrapper;

ThisClassConstructor(UnirestWrapper unirestWrapper) {
    this.unirestWrapper = unirestWrapper;
}

/**
 * This method lists the ID of the activity when requested.
 *
 * @return the list of all activities
 */
public JSONArray getActivites() {
    HttpResponse<JsonNode> jsonResponse = this.unirestWrapper.getResponse("http://111.111.111.111:8080/activity", "application/json");

    if (jsonResponse == null) {
        return null;
    }

    JSONArray listOfActivities = jsonResponse.getBody().getArray();
    return listOfActivities;
}

Or you could use power mocks...

A: In the meantime the orignal authors provide mocking support with unirest-mocks:
Maven:
<dependency>
    <groupId>com.konghq</groupId>
    <artifactId>unirest-mocks</artifactId>
    <version>LATEST</version>
    <scope>test</scope>
</dependency>

Usage:
class MyTest {
    @Test
    void expectGet(){
        MockClient mock = MockClient.register();

        mock.expect(HttpMethod.GET, "http://zombo.com")
                        .thenReturn("You can do anything!");

        assertEquals(
            "You can do anything!",
            Unirest.get("http://zombo.com").asString().getBody()
        );

        //Optional: Verify all expectations were fulfilled
        mock.verifyAll();
    }
}

A: You can mock the HttpResponse with Mockito.mock(HttpResponse.class) and put to when get the body of this response to get your json. For example:
HttpResponse response = Mockito.mock(HttpResponse.class);
when(response.getBody()).thenReturn(readFileContent("my_response.json"));

this 'readFileContent' is just a method to read a file where I put my response. You can put your json to compare there

A: I solved similar task by using JUnit5 and Mockito.
Class under test:
@Service
@RequiredArgsConstructor
@Profile("someProfile")
@Slf4j
public class SomeService {

    @Value("${value1}")
    private final String value1;

    @Value("${value2}")
    private final String value2;

    private final ObjectMapper mapper;
    private final CommonUtil commonUtil;

    public boolean methodUnderTest(String inputValue) {
        HttpResponse<String> result;
        //some logic
        try {
            result = Unirest.get("url")
                    .header(header, value)
                    .routeParam("param", paramValue)
                    .asString();
            if (result.getStatus() != 200) {
                throw new MyException("Message");
            }
            //some logic
        } catch (Exception e) {
            log.error("Log error", e);
            //some logic
        }
    }
}

And test:
@ExtendWith(MockitoExtension.class)
class SomeServiceTest {
    @Mock
    private CommonUtil commonUtil;
    @Mock
    private ObjectMapper mapper;
    @Mock
    HttpResponse httpResponse;
    @Mock
    GetRequest request;

    private SomeService serviceUnderTest;

    @BeforeEach
    void setUp() {
        this.serviceUnderTest = new SomeService("url", "valu1", mapper, commonUtil);
    }

    @Test
    void methodUnderTest_whenSmth_ThenSmth() throws UnirestException {
        try (MockedStatic<Unirest> unirest = Mockito.mockStatic(Unirest.class)) {
            unirest.when(() -> Unirest.get(anyString()))
                    .thenReturn(request);

            Mockito.when(commonUtil.encodeValue(Mockito.anyString())).thenReturn("123");

            Mockito.when(request.header(anyString(), anyString())).thenReturn(request);
            Mockito.when(request.routeParam(anyString(), anyString())).thenReturn(request);
            Mockito.when(request.asString()).thenReturn(httpResponse);

            Mockito.when(httpResponse.getStatus()).thenReturn(200);
            Mockito.when(httpResponse.getBody()).thenReturn("true");
            assertTrue(serviceUnderTest.methodUnderTest("123"));
        }
    }
 }


text:
Q: Intermittent javax.net.ssl failure bad_record_mac I have a Java Spring web app running on Tomcat through an Apache https proxypass which fails intermittently when it tries to access a secure IBM Watson service. Apache is secured with a LetsEncrypt cert, redirecting to Tomcat port 8080.
Environment:

*

*Java: jdk1.7.0_80

*Solaris 10

*Tomcat 8.0.33

*Apache 2.4.18

I turned on javax.net debug and I can see it gets through ServerHelloDone. Here is the rest of the log up to the exception.
ServerHelloDone
[read] MD5 and SHA1 hashes:  len = 4
0000: 0E 00 00 00                                        ....
ECDHClientKeyExchange
ECDH Public value:  { 4, 1, 15, 216, 52, 12, 28, 142, 36, 18, 118, 235, 237, 15, 74, 34, 33, 56, 45, 207, 106, 156, 33, 190, 210, 211, 175, 194, 89, 194, 183, 108, 144, 243, 51, 244, 179, 187, 96, 144, 10, 108, 146, 141, 244, 76, 71, 228, 210, 106, 52, 6, 241, 210, 130, 225, 126, 88, 210, 15, 184, 97, 206, 93, 65, 141, 34, 0, 3, 64, 70, 132, 192, 245, 110, 15, 18, 172, 202, 220, 232, 174, 254, 75, 160, 45, 48, 33, 180, 50, 39, 38, 122, 56, 13, 5, 15, 164, 61, 213, 135, 95, 115, 152, 246, 74, 157, 17, 26, 141, 90, 77, 105, 197, 209, 32, 163, 122, 22, 23, 152, 214, 79, 36, 192, 196, 109, 212, 137, 103, 125, 159, 17 }
[write] MD5 and SHA1 hashes:  len = 138
0000: 10 00 00 86 85 04 01 0F   D8 34 0C 1C 8E 24 12 76  .........4...$.v
0010: EB ED 0F 4A 22 21 38 2D   CF 6A 9C 21 BE D2 D3 AF  ...J"!8-.j.!....
0020: C2 59 C2 B7 6C 90 F3 33   F4 B3 BB 60 90 0A 6C 92  .Y..l..3...`..l.
0030: 8D F4 4C 47 E4 D2 6A 34   06 F1 D2 82 E1 7E 58 D2  ..LG..j4......X.
0040: 0F B8 61 CE 5D 41 8D 22   00 03 40 46 84 C0 F5 6E  ..a.]A."..@F...n
0050: 0F 12 AC CA DC E8 AE FE   4B A0 2D 30 21 B4 32 27  ........K.-0!.2'
0060: 26 7A 38 0D 05 0F A4 3D   D5 87 5F 73 98 F6 4A 9D  &z8....=.._s..J.
0070: 11 1A 8D 5A 4D 69 C5 D1   20 A3 7A 16 17 98 D6 4F  ...ZMi.. .z....O
0080: 24 C0 C4 6D D4 89 67 7D   9F 11                    $..m..g...
recipeorganizer.net-startStop-1, WRITE: TLSv1 Handshake, length = 138
[Raw write]: length = 143
0000: 16 03 01 00 8A 10 00 00   86 85 04 01 0F D8 34 0C  ..............4.
0010: 1C 8E 24 12 76 EB ED 0F   4A 22 21 38 2D CF 6A 9C  ..$.v...J"!8-.j.
0020: 21 BE D2 D3 AF C2 59 C2   B7 6C 90 F3 33 F4 B3 BB  !.....Y..l..3...
0030: 60 90 0A 6C 92 8D F4 4C   47 E4 D2 6A 34 06 F1 D2  `..l...LG..j4...
0040: 82 E1 7E 58 D2 0F B8 61   CE 5D 41 8D 22 00 03 40  ...X...a.]A."..@
0050: 46 84 C0 F5 6E 0F 12 AC   CA DC E8 AE FE 4B A0 2D  F...n........K.-
0060: 30 21 B4 32 27 26 7A 38   0D 05 0F A4 3D D5 87 5F  0!.2'&z8....=.._
0070: 73 98 F6 4A 9D 11 1A 8D   5A 4D 69 C5 D1 20 A3 7A  s..J....ZMi.. .z
0080: 16 17 98 D6 4F 24 C0 C4   6D D4 89 67 7D 9F 11     ....O$..m..g...
SESSION KEYGEN:
PreMaster Secret:
0000: 00 65 8C 39 8F 65 BD D3   AC EF B3 D8 AF 7D 62 CA  .e.9.e........b.
0010: DE 38 F7 FC B3 68 CD 17   4B A9 2E E3 57 76 E6 ED  .8...h..K...Wv..
0020: 44 C3 39 47 9C 6D 9B 11   EE 36 01 50 78 DC E2 6B  D.9G.m...6.Px..k
0030: 79 EF A2 86 B8 5A D2 0F   84 F8 48 23 3D 18 57 9E  y....Z....H#=.W.
0040: 59 FB                                              Y.
CONNECTION KEYGEN:
Client Nonce:
0000: 58 44 7E ED EE F3 E8 DA   8A 53 52 00 3B 11 2B E2  XD.......SR.;.+.
0010: 7D 41 F8 C0 0D CD BB C7   7D 97 32 CB BA 5D BF 22  .A........2..]."
Server Nonce:
0000: 54 AC E4 66 B7 28 95 0B   60 02 C3 3B 6C A8 D7 4E  T..f.(..`..;l..N
0010: 89 B6 26 85 3D 38 00 1A   2F 3F B1 4B D1 57 40 8B  ..&.=8../?.K.W@.
Master Secret:
0000: EF A0 29 3D 09 06 17 55   DB B9 96 5E 0F E4 58 86  ..)=...U...^..X.
0010: 38 42 88 15 DA 86 95 91   6B 6E 06 8C 33 D3 3D 09  8B......kn..3.=.
0020: D3 7E 1C E6 D6 10 53 7A   B2 A4 B7 E0 4A FB E0 BA  ......Sz....J...
Client MAC write Secret:
0000: 89 E4 9D 64 8B 81 87 CB   F8 4B 2B 18 49 08 E7 0E  ...d.....K+.I...
0010: D5 E7 69 DB                                        ..i.
Server MAC write Secret:
0000: F2 6A 0D C4 9B 2C 4D F2   64 9F DC DD 42 7A 67 4F  .j...,M.d...BzgO
0010: 25 7C 0E 4C                                        %..L
Client write key:
0000: C8 BD B9 72 CB CE 7B 09   40 E1 98 7D 8E 65 43 F3  ...r....@....eC.
Server write key:
0000: E9 E7 11 F1 FB BB AD 02   A1 43 BA 60 8F C2 68 83  .........C.`..h.
Client write IV:
0000: E2 A3 08 8D 1E A8 2B 64   DA B5 C2 8D F3 50 E9 59  ......+d.....P.Y
Server write IV:
0000: B5 3C 89 77 2E 4E 17 D5   74 25 3A 2A 92 6E D9 8B  .<.w.N..t%:*.n..
recipeorganizer.net-startStop-1, WRITE: TLSv1 Change Cipher Spec, length = 1
[Raw write]: length = 6
0000: 14 03 01 00 01 01                                  ......
Finished
verify_data:  { 118, 161, 158, 7, 159, 29, 185, 175, 148, 167, 176, 216 }
[write] MD5 and SHA1 hashes:  len = 16
0000: 14 00 00 0C 76 A1 9E 07   9F 1D B9 AF 94 A7 B0 D8  ....v...........
Padded plaintext before ENCRYPTION:  len = 48
0000: 14 00 00 0C 76 A1 9E 07   9F 1D B9 AF 94 A7 B0 D8  ....v...........
0010: 9C A6 C7 9D 1A D7 DC B9   96 A2 83 CA 9A 50 BD 3D  .............P.=
0020: 7D D9 72 4A 0B 0B 0B 0B   0B 0B 0B 0B 0B 0B 0B 0B  ..rJ............
recipeorganizer.net-startStop-1, WRITE: TLSv1 Handshake, length = 48
[Raw write]: length = 53
0000: 16 03 01 00 30 4A DD E4   1A B2 30 CF 7A 65 A4 3F  ....0J....0.ze.?
0010: 3F 90 1D 48 98 54 E4 E7   42 F6 1C 87 AA 70 3C 9E  ?..H.T..B....p<.
0020: F6 47 5E EC 40 D1 12 C3   EF 82 5E 44 09 F0 C9 A0  .G^.@.....^D....
0030: BB E4 E8 8C CF                                     .....
[Raw read]: length = 5
0000: 15 03 01 00 02                                     .....
[Raw read]: length = 2
0000: 02 14                                              ..
recipeorganizer.net-startStop-1, READ: TLSv1 Alert, length = 2
recipeorganizer.net-startStop-1, RECV TLSv1 ALERT:  fatal, bad_record_mac
%% Invalidated:  [Session-1, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA]

When the [Raw read]: length = 2 equals 2 it fails but if it equals 1 it succeeds. I am not a security expert at all so I'm not sure what might be causing this.  Google and SO searches have not turned up anything useful. I did find one post that suggested I replace the local_policy and US_export_policy jars with the unlimited strength ones, but that did not fix the issue.

A: I believe I found the cause of the failure.  This bug report appears to describe correctly the issue I was encountering: Inconsistent length for the generated secret using DH key agreement impl from SunJCE and PKCS11 .  Every failure I examined had a PreMaster Secret key with 00 in the first byte, while every success had something else in the first byte (usually 01). The bug report indicates the fixed version is Java 8, so I'm assuming it was never fixed in Java 7, the version I'm using.
Until I'm able to upgrade to Java 8 I was able to force the JVM to not use any of the Diffie-Hellman cipher suites with a change to the java.security file:
jdk.tls.disabledAlgorithms=SSLv3, DH, DHE, ECDH, ECDHE

The file is located in the jre/lib/security subdirectory of the Java JDK directory on the server. An examination of the logs indicates one of the RSA cipher suites is now being used and the failure no longer occurs.
My only hesitation in declaring this the absolute cause is that one analysis of this bug indicated it should happen only 1 out of 256 handshakes, but I was seeing it occur almost 40-50% of the time.  Regardless, after bypassing the DH cipher suites the exception no longer occurs.


text:
Q: Javascript Workday Progress Bar I'm trying to develop a progress bar which gets filled by the amount of time that has passed in two shifts at work.
The first one starts from 7:00 am to 17:00 pm and the second one is from 17:00 pm to 2:00 am from the next day.
I investigated and found this fiddle.
in this part:
  $self.prev(".percent").text("0%");
  $.ease(0, targetVal, 10000, "swing", function (i) {
  $self.progressbar("option", "value", parseInt(i));
  $self.prev(".percent").text(parseInt(i) + "%");

The problem is that it fills the progress bar continuously, but I need it to stop the progress bar when there are lunch breaks, (9:30am to 10:00am, and 12:00pm to 12:30pm by example, in the first shift) and I truly don't know how to do it.
Which is the best approach possible to do it? I tried to convert the working hours to minutes (substracting the lunch breaks) but it still is incorrect.
Thanks in advance.


text:
Q: Maximum value of $n$ for which $8n^3+16n^2+72n+64$ is a perfect cube
What is the maximum value of $n$ for which
  $$8n^3+16n^2+72n+64$$
  is a perfect cube?

I know how this could be done for a quadratic but how to extend it for a cubic.

A: Hint 1: $8n^3+16n^2+72n+64 = 2^3(n^3+2n^2+9n+8).$
Hint 2: $n^3+2n^2+9n+8>n^3$, so it can't be perfect cube if $(n+1)^3>n^3+2n^2+9n+8.$

A: I shall find all integers (not necessarily positive) $n$ such that $$8n^3+16n^2+72n+64=2^3\,\left(n^3+2n^2+9n+8\right)$$
is the cube of an integer.  Clearly, $p(n):=n^3+2n^2+9n+8$ must be a perfect cube.  Note that
$$p(n)-(n-1)^3=5n^2+6n+9=\frac{(5n+3)^2+36}{5}>0$$
and
$$(n+3)^3-p(n)=7n^2+18n+19=\frac{(7n+9)^2+52}{7}>0\,.$$
Thus,
$$(n-1)^3<p(n)<(n+3)^3\,.$$

 Therefore, $p(n)=n^3$, $p(n)=(n+1)^3$, or $p(n)=(n+2)^3$.  In the first case, $p(n)=n^3$ iff  $2n^2+9n+8=0$, or equivalently, $n=\dfrac{-9\pm\sqrt{17}}{4}$, none of whose values is an integer.  In the second case, $p(n)=(n+1)^3$ iff $n^2-6n-7=0$, or equivalently, $n=-1$ or $n=7$.  In the final case, $p(n)=(n+2)^3$ iff $4n^2+3n=0$, which is the same as saying that $n=0$ or $n=-\dfrac{3}{4}$.  Consequently, all integer solutions are $n=-1$, $n=0$, and $n=7$.


text:
Q: How to use matplotlib to plot stress function graph? everyone!
I'm new to python and PyQT.
I want to calculate stress tensor components using this formula
Stress tensor component
where lambda, mu, and alpha - are constants, and T - is the change of temperature.
and then plot it using matplotlib, with temperature change on the x-axis, and the change of stress on the y-axis.
I've made a GUI in QT Designer with three buttons, to calculate for different materials. And so far, i am only able to calculate stress at some point of temperature.
But now i'm stuck at plotting, because i've never used matlib for plotting, and i hope you can help me.
import sys
from PyQt4 import QtCore, QtGui, uic

qtCreatorFile = "Application.ui"

Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)

class MyApp(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self):
    QtGui.QMainWindow.__init__(self)
    Ui_MainWindow.__init__(self)
    self.setupUi(self)
    self.clcbtn.clicked.connect(self.CalculateStress)
    self.clcbtn_2.clicked.connect(self.CalculateStress1)
    self.clcbtn_3.clicked.connect(self.CalculateStress2)

def CalculateStress(self):
   t = int(self.textEdit.toPlainText())
   lam = 55500000000
   theta = 10
   mu = 26100000000
   alpha = 0.0000222
   str11 = 3
   total_stress = lam * theta + 2 * mu * str11 - (3 * lam + 2 * mu) * alpha * t
   total_stress_string = "The total stress is: " + str(total_stress)
   self.results_window.setText(total_stress_string)

def CalculateStress1(self):
   t = int(self.textEdit.toPlainText())
   lam = 104400000000
   theta = 10
   mu = 82000000000
   alpha = 0.000013
   str11 = 5
   total_stress1 = lam * theta + 2 * mu * str11 - (3 * lam + 2 * mu) * alpha * t
   total_stress_string = "The total stress is: " + str(total_stress1)
   self.results_window.setText(total_stress_string)

def CalculateStress2(self):
   t = int(self.textEdit.toPlainText())
   lam = 5450000000
   theta = 10
   mu = 1480000000
   alpha = 0.0000702
   str11 = 3
   total_stress2 = lam * theta + 2 * mu * str11 - (3 * lam + 2 * mu) * alpha * t
   total_stress_string = "The total stress is: " + str(total_stress2)
   self.results_window.setText(total_stress_string)

if __name__ == "__main__":

app = QtGui.QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())

A: You will need a widget with a FigureCanvas to do so. I can share a customized QWidget of mine, that is based on an example from the matloplib reference.
class MplCanvas(FigureCanvas):
    """Represents a canvas in QtGui.QWidget"""

    def __init__(self):
        self.fig = Figure()
        FigureCanvas.__init__(self, self.fig)

        FigureCanvas.setSizePolicy(self,
                                   QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

class MplWidget(QtGui.QWidget):
    """Represents a customized Matplotlib QWidget"""

    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.canvas = MplCanvas()
        self.axes = self.canvas.fig.add_subplot(1, 1, 1)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.canvas)

    def draw_array(self, label, a):
        line, = self.axes.plot(a[:,0], a[:,1], label=label)
        self.axes.legend()
        self.resize_subplot(self.axes)
        self.canvas.draw()

You can create an instance of that with myMplWidget = MplWidget() add this to a layout or use it as centralWidget in your QMainWindow with setCentralWidget(myMplWidget) and use myMplWidget.draw_array("My array", arr), assuming arr is a 2-dimensional array
Please keep me updated if you won't get the code working. I modified it for this answer and did not test modifications


text:
Q: I generated the multiple pdf from dompdf but how can I save these files locally I generated the multiple pdf from dompdf but how can I save these files locally, because these files only open in the web browser. How can I save them into the server?
my code
include '../../libs/vendor/autoload.php';
include '../../libs/dompdf/autoload.inc.php';

use Dompdf\Dompdf;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();

if (isset($_POST['submit'])) {

    if (isset($_FILES['challan']['tmp_name'])) {
        $challan = $_FILES['challan']['tmp_name'];

        $spreadsheet = $reader->load($challan);

        $sheetData = $spreadsheet->getActiveSheet()->toArray();

        if (!empty($sheetData)) {

        $html = ob_get_clean();
                $html = stripslashes($html);

                $html = <<<HTML

                HTML;

                for ($i=0; $i<count($sheetData); $i++) {
                $name = $sheetData[$i][0];
                $fatherName = $sheetData[$i][1];
                $rollNo = $sheetData[$i][2];
                $class = $sheetData[$i][3];
                $dept = $sheetData[$i][4];
                $dompdf = new DOMPDF();
                $html .= '
Hello World
';
                $dompdf->load_html($html);
                $dompdf->render();
                file_put_contents('pdf', $dompdf->output());
                $dompdf->stream();
                }
      }
    }
}

I updated the code again, please have a look at it.

A: You can use the method output() to get the PDF content and save into a file using file_get_contents():
file_put_contents('/path/to/file.pdf', $dompdf->output());

EDIT after question changed :
for ($i=0; $i<count($sheetData); $i++)
{
    $dompdf = new DOMPDF();
    $dompdf->load_html($html);

    $dompdf->render();
    file_put_contents('pdf' . $i . '.pdf', $dompdf->output());
    $dompdf->stream();
}

But it seems strange to generate N times, the same PDF.


text:
Q: Does IdentityServer require Anomymous Authentication to be enabled in IIS My application uses Net 5.0 Microsoft.AspNetCore.ApiAuthorization.IdentityServer and IdentityServer4. If Windows Authentication is enabled in IIS, it issues an NTLM challenge to acquire a WindowsPrincipal from the HttpContext.User as described in the IdentityServer documentation: https://docs.identityserver.io/en/latest/topics/windows.html. My implementation is very similar though not exactly the same - it falls back to an in-app sign-in form, if Windows Authentication is not enabled in IIS.
This works fine as long as Anonymous Authentication is enabled in IIS, but not if Anonymous Authentication is disabled. To be precise:

*

*Anonymous and Windows Authentication enabled: This works, user is signed in using username recovered from the WindowsPrincipal

*Anonymous Authentication only enabled: This works, user signs in via the sign in form

*Windows Authentication only enabled: This does not work, and this is what my question is about

Firstly, when Windows Authentication is enabled, there is this difference:

*

*If Anonymous Authentication is disabled, there is an automatic negotiation taking place for all requests. This means that the browser and IIS automatically handles the NTLM challenge and negotiation. As a result, the HttpContext of the initial request arriving in the application already has an authenticated Windows Principal assigned to the HttpContext.User.Identity

*If Anonymous Authentication is enabled, then this automatic negotiation does not take place and the application needs to handle the NTLM negotiation itself to get the authenticated WindowsPrincipal (as indeed described in the IdentityServer4 documentation in the link above)
The above is my understanding, please correct me if I am wrong.
Regardless of alternative 1 or 2, the application looks up the name of the WindowsPrincipal in IdentityServer (the Net 5.0 SignInManager) and - if found - does an automatic signin. This works, there is a correct redirect to the IdentityServer callback, and subsequently a redirect to the return url with a Token with all the necessary claims - all honky-dory.
The problem appears when the application running in the browser then makes a request to the IdentityServer userinfo endpoint. Again, no problem if Anonymous Authentication is enabled. But if Anonymous Authentication is disabled, then this request triggers a Windows Authentication 401 challenge causing the browser to prompt for (windows) credentials.
This challenge persists and does not accept any valid Windows credentials. Cancelling the challenge results in a 401, with the response header asking for a NTLM negotiation:
WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM

Importantly, this request to the userinfo does contain a valid bearer token, so the user has been authenticated and a valid token has been issued. It seems like the userinfo endpoint in IdentityServer4 requires Anonymous Authentication to be enabled.
Is there any way out of this? Or is it impossible to use IdentityServer4 in IIS without Anonymous Authentication?


text:
Q: react app browser proxy with http-proxy-middleware I've got problem with proxy in react app.
Target: I've got two react apps, first app is on localhost:3000 and second on localhost:3001. What I want? => When in first app I'll click on:
<a href="/app2">
<button>Second App Open</button>
</a>

Then url will change from localhost:3000 into localhost:3000/app2 and second react app show what has got in url localhost:3001.
I imported http-proxy-middleware library and create in src direction file setupProxy.js and inside:
const {createProxyMiddleware} = require("http-proxy-middleware");

module.exports = function(app) {
    app.use(
        createProxyMiddleware('/app2',{
            target: 'http://localhost:3001',
            changeOrigin: true,
            prependPath: false,
            secure: false,
            logLevel: 'debug',
            ws:true
        })
    );
app.listen(3000)
};

Anyone could help me with this?
Also I tried this code in setupProxy.js:
const express = require('express')
const {createProxyMiddleware} = require("http-proxy-middleware");
app = express()
    app.use(
        createProxyMiddleware('/app2',{
            target: 'http://localhost:3001',
            changeOrigin: true,
            prependPath: false,
            secure: false,
            logLevel: 'debug',
            ws:true
        })
    );
app.listen(3000)

But then I've received error that require(...) is not a function oraz that express is not a function, when I take express into {} then also occurs error.

A: I know it's late and I came across the same issue. Keeping what worked for me so that others can give it a try.This code is tested for react app created with create-react-app.
I proxied this endpoint - https://services.odata.org/V2/Northwind/Northwind.svc/Customers?$format=json
setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = (app) => {
    app.use(createProxyMiddleware('/api2', {
        target: 'https://services.odata.org/V2/Northwind/Northwind.svc/',
        changeOrigin: true,
        pathRewrite: { '^/api2': '' }
    })
    );
}

Your .js file
triggerCORSCall() {
    axios.get(`/api2/Customers?$format=json`)
      .then(response => {
        alert('Success');
      }).catch(error => {
        alert('Failure');
        console.log(error);
      })
  }


text:
Q: Show checked items from dialog box into the previous activity I have a listview of shopping lists in a fragment and when I click one I get a new activity that shows a listview with all the products in the clicked shopping list. What I am trying to do is to add products this list by selecting some checkboxes in the newly created activity and pass them to the previous activity.
public class DisplayShoppingListDetailsActivity extends AppCompatActivity{
    private ShoppingList list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //defines the activity layout
        setContentView(R.layout.shopping_list_details);

        ListView listView = (ListView) findViewById(R.id.shopping_list_details);

        Intent intent = getIntent();
        list = (ShoppingList) intent.getSerializableExtra("ShoppingList");

        ProductsOnListAdapter ad = new ProductsOnListAdapter(this, -1, Service.getService().getProductsOnList(list));
        listView.setAdapter(ad);

        FloatingActionButton button = (FloatingActionButton) findViewById(R.id.floatingButton);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(DisplayShoppingListDetailsActivity.this, ListOfProductsActivity.class));
                //This method here is not working...it says it cannot resolve the method
            }
        });

    }

A: You really should not have one activity try to modify another activity's instance.  That will lead to bugs in your code.
Instead, in the first activity, you can use startActivityForResult() to launch the second activity, then the second activity can use setResult() to return data to the first activity.  This is all documented if you read the javadoc for Activity under the heading "Starting Activities and Getting Results".


text:
Q: All DAGs broken after MWAA update from 2.0.2 to 2.2.2 I am getting the following errors in AWS MWAA UI after I updated from 2.0.2 to 2.2.2
I have exhaustively searched for more details on these errors to no avail
from airflow.providers.slack.operators.slack_webhook import SlackWebhookOperator
ModuleNotFoundError: No module named 'airflow.providers.slack'

Broken plugin: [/usr/local/airflow/plugins/__MACOSX/awsairflowlib/.___init__.py] source code string cannot contain null bytes
Broken plugin: [/usr/local/airflow/plugins/__MACOSX/awsairflowlib/operators/._aws_glue_crawler_operator.py] source code string cannot contain null bytes
Broken plugin: [/usr/local/airflow/plugins/__MACOSX/awsairflowlib/operators/._aws_glue_job_operator.py] source code string cannot contain null bytes
Broken plugin: [/usr/local/airflow/plugins/__MACOSX/awsairflowlib/operators/.___init__.py] source code string cannot contain null bytes
Broken plugin: [/usr/local/airflow/plugins/__MACOSX/awsairflowlib/hooks/.___init__.py] source code string cannot contain null bytes
Broken plugin: [/usr/local/airflow/plugins/__MACOSX/awsairflowlib/sensors/._aws_glue_job_sensor.py] source code string cannot contain null bytes
Broken plugin: [/usr/local/airflow/plugins/__MACOSX/awsairflowlib/sensors/.___init__.py] source code string cannot contain null bytes

The CloudWatch logs from the WebServer are no helpful either:
ValueError: source code string cannot contain null bytes

PFA

My plugins zip file while I was using 2.0.2 was of the following structure and it worked just fine. I believe this is not working for v2.2.2:
s3://{my-bucket-name}
└── DAGS
    ├── dags
    │   └── dag1.py
    └── plugins
        ├── __init__.py
        └── operators
        |   ├── __init__.py
        |   └── aws_glue_operator.py
        |___ sensors
             |__aws_glue_job_sensor.py

Here is my requirements.txt contents
--constraint "https://raw.githubusercontent.com/apache/airflow/constraints-2.2.2/constraints-3.7.txt"
apache-airflow-providers-postgres[amazon]
apache-airflow-providers-cncf-kubernetes
psycopg2-binary==2.8.6
fsspec
s3fs
pandas
sagemaker==v1.72
dag-factory==0.7.2
requests
boto3
botocore
apache-airflow-providers-amazon
PyOpenSSL
oauth2client
gspread

Any help is appreciated

A: With MWAA 2.2.2 the plugins zip file and the requirements.txt need to be downloaded from here
Any version conflicts in requirements.txt and Airflow should be cross-checked from here
With these two files I was able to fix the broken DAGs in 2.2.2

A: Using a public VPC (but tested first on the local runner container) I was able to get Slack to work by just adding the following to the requirements.txt file:
apache-airflow-providers-slack==5.0.0
This version worked without issue.
You can enable logging (in the Monitoring section) and then update and check the logs it produces. You should see a successful installed message in the CloudWatch logs (requirements_install_ Log stream).


text:
Q: Return started Async in F# function from calling a non-async Func from C#? Let's say I want to call, from F#, this C# function:
public static class Foo {
    public Bar Baz()
    {
       ...
    }
}

The problem is this function is CPU intensive and I don't want to block on it. Unfortunately the C# library doesn't have an Task<Bar> BazAsync() overload.
Then I want to provide the asynchronous version myself, by creating an F# function that calls it and returns an (already started) Async<Bar>. That is, I don't want to use System.Threading.Task<Bar>.
I guess what I'm looking for is the equivalent of Task<T>.Run() in the F# Async way of doing things.
I've already looked at the following options:

*

*Async.StartAsTask -> deals with C#ish Task type.

*Async.Start and Async.StartImmediately -> receive Async<unit> not Async<T>
Is Async.StartChild what I'm looking for?
If yes, it would be:
let BazWrapper() =
    let asyncTask: Async<Bar> = async {
        return Foo.Bar()
    }
    Async.StartChild asyncTask

However, if this above is the solution:

*

*Why most documentation around F# async workflows doesn't mention StartChild?

*Why BazWrapper returns Async<Async<Bar>> instead of Async<Bar>?

A: BazWrapper returns Async<Async<Bar>> because that's what StartChild does: it takes an Async<'T> and returns Async<Async<'T>>. The intent is to use it within an async computation expression, so that you can launch multiple "child" asyncs. Example from the Async.Start vs Async.StartChild sample code:
async {
    //(...async stuff...)
    for msg in msgs do
        let! child = asyncSendMsg msg |> Async.StartChild
        ()
    //(...more async stuff...)
}

When you're inside an async computation expression, the let! keyword will "unwrap" an Async<'Whatever> leaving you with a value of type 'Whatever. In the case of calling Async.StartChild, the 'Whatever type is specifically Async<'T>.
Therefore, if you want to return an already-started async via Async.StartChild, the way to do it would be:
let BazWrapper() =
    let asyncTask: Async<Bar> = async {
        return Foo.Bar()
    }
    async {
        let! child = Async.StartChild asyncTask
        return! child
    }

However, I suspect that you'll find that an already-started async isn't as useful to you as a "cold" async (one that isn't started yet), because a "cold" async can still be composed with other async tasks before starting it. (This can be useful for, for example, wrapping logging around your asyncs.) So if I were writing the code for your situation, I'd probably simply do this:
let BazWrapper() =
    async {
        return Foo.Bar()
    }

And now BazWrapper() returns an Async that has not been started yet, and you can either start that with Async.RunSynchronously if you want the value right away, or use it in other async computation expressions.


text:
Q: Как при успешной авторизации вернуть роль пользователя? При успеной авторизации срабатывает :
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {

    clearAuthenticationAttributes(request);
}

Что возвращает клиенту только status 200 OK. Как правильно вернить роль клиента (USER, ADMIN)?
Возможно ошибка кроется гдето сдесь:
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userRepository.findByUsername(username);
    if (user == null) {
        throw new UsernameNotFoundException("No user found with username: " + username);
    }

    List<GrantedAuthority> authorities = buildUserAuthority(user.getRole());

    UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(),
            user.getPassword(), authorities);

    return userDetails;
}

private List<GrantedAuthority> buildUserAuthority(RoleEnum roleEnum) {

    Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

    for (RoleEnum userRole : RoleEnum.values()) {
        setAuths.add(new SimpleGrantedAuthority(userRole.toString()));
    }

    List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);

    return Result;
}

A: Используй этот метод в любом из своих контроллеров
public List<GrantedAuthority> getUserAuthorities() {
    Object principals = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    //Тут нужна эта проверка тк если сразу получить principals без проверки
    //На анонимность пользавателя можем получим NullPointerException
    if (!principals.toString().equals("anonymousUser")) {
        org.springframework.security.core.userdetails.User u =
                (org.springframework.security.core.userdetails.User)
                        principals;

       List<GrantedAuthority> authorities = new LinkedList();
       authorities.addAll(u.getAuthorities());

       return authorities;
    }

    return new List();
}

UPDATE
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
    Authentication authentication) throws IOException, ServletException {
    for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
       String authority = grantedAuthority.getAuthority();
    }
    clearAuthenticationAttributes(request);
}


text:
Q: How to get the Gross Sales from the Square Order API? Qn1) I have tried getting the gross sales from the Order API. However, I could only be able to get each lineitem gross value concatenating with one and another ...
Gross value that is concatenating
Qn2) I tried to echo all the item name, qty and etc to insert it into my database although it works but I am getting an error message shown below
Error message
Here is my code: (Have replaced the access token and the location_id to 'XXXX')
<html>
<?php
require_once(__DIR__ . '/vendor/autoload.php');

use Square\SquareClient;
use Square\Environment;

$client = new SquareClient([
    'accessToken' => 'XXXX',
    'environment' => Environment::PRODUCTION,
]);

$location_ids = ['XXXX'];
$created_at = new \Square\Models\TimeRange();
$created_at->setStartAt('2021-05-17T00:00:00+08:00');
$created_at->setEndAt('2021-05-17T23:59:59+08:00');

$date_time_filter = new \Square\Models\SearchOrdersDateTimeFilter();
$date_time_filter->setCreatedAt($created_at);

$filter = new \Square\Models\SearchOrdersFilter();
$filter->setDateTimeFilter($date_time_filter);

$sort = new \Square\Models\SearchOrdersSort('CREATED_AT');
$sort->setSortOrder('DESC');

$query = new \Square\Models\SearchOrdersQuery();
$query->setFilter($filter);
$query->setSort($sort);

$body = new \Square\Models\SearchOrdersRequest();
$body->setLocationIds($location_ids);
$body->setQuery($query);
$body->setLimit(10000);
$body->setReturnEntries(false);

$api_response = $client->getOrdersApi()->searchOrders($body);

if ($api_response->isSuccess()) {
    $result = $api_response->getResult();
    $orders = $result->getOrders();

    foreach($orders as $x => $val) {
            $lineItems = $result->getOrders()[$x]->getLineItems();
        $orderid = $result->getOrders()[$x]->getId();

        foreach($lineItems as $q => $val2){
            $lineItemsID = $lineItems[$q]->getUid();
            $itemName = $lineItems[$q]->getName();
            $itemQty = $lineItems[$q]->getQuantity();
            $catalogObjID = $lineItems[$q]->getCatalogobjectid();
            $grossSales[] = $lineItems[$q]->getGrossSalesMoney()->getAmount();

            echo (array_sum($grossSales)/100); //Qn1

            echo($orderid. "   ". $lineItemsID ."   ".$catalogObjID."   ".$itemName ."  ".$itemQty." <br/>"); //Qn2
            }
        }
}

else
{
    $errors = $api_response->getErrors();
}

?>
</html>

A: <html>
<?php
require_once(__DIR__ . '/vendor/autoload.php');

use Square\SquareClient;
use Square\Environment;

$client = new SquareClient([
    'accessToken' => 'XXXX',
    'environment' => Environment::PRODUCTION,
]);

$location_ids = ['XXXX'];
$created_at = new \Square\Models\TimeRange();
$created_at->setStartAt('2021-05-17T00:00:00+08:00');
$created_at->setEndAt('2021-05-17T23:59:59+08:00');

$date_time_filter = new \Square\Models\SearchOrdersDateTimeFilter();
$date_time_filter->setCreatedAt($created_at);

$filter = new \Square\Models\SearchOrdersFilter();
$filter->setDateTimeFilter($date_time_filter);

$sort = new \Square\Models\SearchOrdersSort('CREATED_AT');
$sort->setSortOrder('DESC');

$query = new \Square\Models\SearchOrdersQuery();
$query->setFilter($filter);
$query->setSort($sort);

$body = new \Square\Models\SearchOrdersRequest();
$body->setLocationIds($location_ids);
$body->setQuery($query);
$body->setLimit(10000);
$body->setReturnEntries(false);

$api_response = $client->getOrdersApi()->searchOrders($body);

if ($api_response->isSuccess()) {
    $result = $api_response->getResult();
    $orders = $result->getOrders();

    $grossSales = array();

    if (is_array($orders) || is_object($orders)) {
    foreach($orders as $x => $val) {
        $lineItems = $result->getOrders()[$x]->getLineItems();
        $orderid = $result->getOrders()[$x]->getId();

        if (is_array($lineItems) || is_object($lineItems)){
        foreach($lineItems as $q => $val2){
            $lineItemsID = $lineItems[$q]->getUid();
            $itemName = $lineItems[$q]->getName();
            $itemQty = $lineItems[$q]->getQuantity();
            $catalogObjID = $lineItems[$q]->getCatalogobjectid();
            $grossSales[] = $lineItems[$q]->getGrossSalesMoney()->getAmount();
            }
          }
        }
     }
    $sum = 0;
    foreach($grossSales as $key=>$value)
    {
      $sum+= $value;
    }
    echo ($sum/100);
}

else
{
    $errors = $api_response->getErrors();
}

?>
</html>


text:
Q: Flutter bloc accessing the previous state? I'm confused why yielding a new state is not causing the state variable inside by bloc class to actually update. The value of state remains what I initialize it to despite mapping events to to functions that are yielding new states. For example if my state had a count field and was initialized to 0. I would expect if I add an increment event to my bloc I would be able to produce the desired result by doing yield state.copyWith(count: state.count+1) but state.count is always 0 no matter what it never changes no matter how many times I send an increment envent. I was using freezed and swapped to using equatable for defining my state class to see if that would make a difference and it did not. When using a bloc does the state not update between yields ? What am I missing.
I should be seeing state.count increase in my print statement everytime _mapCameraOrientationCheckToState gets fired but state.count is always 0 which is
...Bloc Class Excerpt
  CameraBloc({
    this.resolutionPreset = ResolutionPreset.ultraHigh,
    this.cameraLensDirection = CameraLensDirection.back,
  }) : super(CameraState(
            error: null,
            path: null,
            orientation: null,
            count: 0,
            status: CameraStatus.initializing)) {
  }

  @override
  Stream<CameraState> mapEventToState(
    CameraEvent event,
  ) async* {
    if (event is CameraInitialize) {
      yield* _mapCameraInitializedToState(event);
    } else if (event is CameraCapture) {
      yield* _mapCameraCapturedToState(event);
    } else if (event is CameraStartRecording) {
      yield* _mapCameraRecordingToState(event);
    } else if (event is CameraStopRecording) {
      yield* _mapCameraStoppedToState(event);
    } else if (event is CheckCameraOrientation) {
      yield* _mapCameraOrientationCheckToState(event);
    }
  }

Stream<CameraState> _mapCameraOrientationCheckToState(
      CheckCameraOrientation event) async* {
    try {
      print(state.count);
      yield CameraState(
        error: null,
        path: null,
        count: state.count + 1,
        orientation: null,
        status: CameraStatus.capturing,
      );
      //}
    } catch (e) {
      print(e);
    }
  }

...

enum CameraStatus {
  initializing,
  recording,
  capturing,
  stopped,
  error,
  ready,
}

class CameraState extends Equatable {
  final Object? error;
  final String? orientation;
  final String? path;
  final CameraStatus status;
  final int count;

  const CameraState(
      {required this.error,
      required this.orientation,
      required this.path,
      required this.status,
      required this.count});

  CameraState copyWith(
      {Object? error,
      String? orientation,
      String? path,
      CameraStatus? status,
      int? count}) {
    return CameraState(
        error: error ?? this.error,
        orientation: orientation ?? this.orientation,
        path: path ?? this.path,
        status: status ?? this.status,
        count: count ?? this.count);
  }

  @override
  List<Object?> get props => [error, orientation, path, status, count];
}

abstract class CameraEvent extends Equatable {
  const CameraEvent();

  @override
  List<Object> get props => [];
}

class CameraInitialize extends CameraEvent {}

class CameraStopRecording extends CameraEvent {}

class CameraCapture extends CameraEvent {}

class CameraStartRecording extends CameraEvent {}

class CheckCameraOrientation extends CameraEvent {}


text:
Q: ¿Cómo ejecutar una acción desde touchesEnded en mi subclase de botón en SpriteKit? He creado una subclase de SKNode para crear mis propios botones en mi escena. He conseguido que los botones se muestren correctamente, pero no que funcionen. He creado un método en la clase del botón que toma la acción que quiero añadir al botón. Pero no sé cómo pasar dicha acción al sobrescribir la función touchesEnded(). He buscado y probado varias cosas pero nada funciona. Este es mi código:
var actionTouchUpInside: Selector?
var actionTouchUp: Selector?
var actionTouchDown: Selector?
weak var targetTouchUpInside: AnyObject?
weak var targetTouchUp: AnyObject?
weak var targetTouchDown: AnyObject?

func setButtonAction(target: AnyObject, triggerEvent event:SKButtonActionType, action:Selector) {

    switch (event) {
    case .TouchUpInside:
        targetTouchUpInside = target
        actionTouchUpInside = action
    case .TouchDown:
        targetTouchDown = target
        actionTouchDown = action
    case .TouchUp:
        targetTouchUp = target
        actionTouchUp = action
    }
}
override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let location = touch.location(in: parent!)
        if self.contains(location) {
            // Aquí debería haber algo para ejecutar la acción
        }
    }
}

Gracias de antemano.

A: Solución:
Era problema de pasar una función de obj-c (creada con @objc func) en vez de una función normal. En el ejemplo de código provisto en la pregunta, donde dice:
// Aquí debería haber algo para ejecutar la acción
Se debe, en efecto, escribir el código a ejecutar.
Si se quiere utilizar la función setButtonAction(target: , event: , action: ) hay que cambiar lo siguiente:
var actionTouchUpInside: (() -> Void)?
var actionTouchUp: (() -> Void)?
var actionTouchDown: (() -> Void)?
weak var targetTouchUpInside: AnyObject?
weak var targetTouchUp: AnyObject?
weak var targetTouchDown: AnyObject?

func setButtonAction(target: AnyObject, triggerEvent event:SKButtonActionType, action: @escaping () -> Void) {

    switch (event) {
    case .TouchUpInside:
        targetTouchUpInside = target
        actionTouchUpInside = action
    case .TouchDown:
        targetTouchDown = target
        actionTouchDown = action
    case .TouchUp:
        targetTouchUp = target
        actionTouchUp = action
    }
}
override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let location = touch.location(in: parent!)
        if self.contains(location) {
            // Aquí debería haber algo para ejecutar la acción
        }
    }
}

Teniendo en cuenta que la función que le pasamos a setButtonAction() no acepta parámetros y no devuelve ningún valor. de lo contrario, bastará con cambiar () -> Void para adecuar el código a los tipos de los parámetros de entrada y salida de la función que vayamos a pasarle.


text:
Q: Dynamic retrieve json element .NET 6 I want to retrieve a single value from a json string.
Previously I used Newtonsoft like this:
var jsonString = @"{ ""MyProp"" : 5 }";
dynamic obj = Newtonsoft.Json.Linq.JObject.Parse(jsonString);

Console.WriteLine(obj["MyProp"].ToString());

But I can't seem to get it to work in .NET 6:
I've tried this so far:
var jsonString = @"{ ""MyProp"" : 5 }";
dynamic obj = await System.Text.Json.JsonSerializer.Deserialize<dynamic>(jsonString);

Console.WriteLine(obj.MyProp.ToString());

which results in this error:

Unhandled exception. Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded method match for 'System.Text.Json.JsonElement.this[int]' has some invalid arguments

A: Reading upon this github, I had success using this approach:

NET 6 will include the JsonNode type which can be used to serialize and deserialize dynamic data.

Trying it results in:
using System;

public class Program
{
    public static void Main()
    {
        var jsonString = @"{ ""MyProp"" : 5 }";
        //parse it
        var myObject = System.Text.Json.JsonDocument.Parse(jsonString);
        //retrieve the value
        var myProp= myObject.RootElement
                            .GetProperty("MyProp");

        Console.WriteLine(myProp);
    }
}

Which seems to work in my case.

As by @robnick's comment - you can also chain GetProperty to get nested properties of the data structure.
var quote = rootElement.GetProperty("contents")
                       .GetProperty("quotes")[0]
                       .GetProperty("quote")
                       .GetString();


text:
Q: error: command 'c:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\BIN\\link.exe' failed with exit status I know that the posts aren't missing on this issue, but please bear with me.
I'm trying to install twisted using the command pip install twisted on Django 1.9 and Python 3.4, at first when I tried to install it I got a ValueError: ['path'] error, after browsing on stackoverflow I found out that I need to run "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\vcvars32.bat" and then try the installation again, which gave me this error :

error: command 'c:\Program Files (x86)\Microsoft Visual Studio
  10.0\VC\BIN\link.exe' failed with exit status 1120

I don't know from where this error is coming and seems like it only happens on Windows (currently using Windows 10), how can I resolve this issue ? I've already tried most of the answer on this StackOverflow Post, without success unfortunately.


text:
Q: TFS Database Backup Failed : There is an error in XML document This is very much a duplicate of a question asked in
TFS Database Backup Failed : There is an error in XML document - but which Doc?
and this is the quick summary.
Problem:
[8/25/2017 8:40:02 AM] [Info] Requested Backup Job: Transactional
[8/25/2017 8:40:02 AM] [Info] -------------------------------------------------------------------
[8/25/2017 8:40:02 AM] [Info] Jobs Requested: Transactional. Completed: None. To Run: Transactional.
[8/25/2017 8:40:02 AM] [Info] RunTransactionalBackupJob
[8/25/2017 8:40:02 AM] [Error]
Exception Message: There is an error in XML document (23569, 23). (type InvalidOperationException)
Exception Stack Trace:    at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
   at Microsoft.TeamFoundation.Admin.BackupSets.Load(String folder)
   at Microsoft.TeamFoundation.Admin.Jobs.DatabaseBackupJob.RunTransactionalBackupJob(IVssRequestContext requestContext, BackupSettings settings, ITFLogger logger)
   at Microsoft.TeamFoundation.Admin.Jobs.DatabaseBackupJob.RunBackupJob(IVssRequestContext requestContext, BackupJobType requestedJobType, String& resultMessage)

Inner Exception Details:

Exception Message: Unexpected end of file while parsing Name has occurred. Line 23569, position 23. (type XmlException)
Exception Stack Trace:    at System.Xml.XmlTextReaderImpl.Throw(Exception e)
   at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
   at System.Xml.XmlTextReaderImpl.Throw(Int32 pos, String res, String arg)
   at System.Xml.XmlTextReaderImpl.ParseQName(Boolean isQName, Int32 startOffset, Int32& colonPos)
   at System.Xml.XmlTextReaderImpl.ParseElement()
   at System.Xml.XmlTextReaderImpl.ParseElementContent()
   at System.Xml.XmlTextReaderImpl.Read()
   at System.Xml.XmlReader.MoveToContent()
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderBackupSets.Read5_TfsBackupSet(Boolean isNullable, Boolean checkType)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderBackupSets.Read6_BackupSets(Boolean isNullable, Boolean checkType)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderBackupSets.Read7_BackupSets()

[8/25/2017 8:40:02 AM] [Info] Backup Job Finished. Completed: Transactional. Result = Failed

Explanation:
TFS back failes due to being enabled to successfully parse the XML in the directory where the back ups are saved (BackupSets.xml)

A: Answer:

*

*go to the directory where your back ups are stored

*find "BackupSets.xml"

*rename it to "BackupSets_BACKUP.xml" (or anything else of your liking)

*rerun the full backup procedure in TFS Administration Console

As the result the BackupSets.xml will be recreated, and the problem should go away