text:
Q: Compile error with nested xml comprehensions I'm trying to generate some XML from some nested scala types, e.g.
class Inner(val n:String)

class Outer(val n:String, val i:Seq[Inner])

given Outer(1,[2,3]), i want to generate <root><item>1</item><item>2</item><item>3</item></root> (note that Inners values are not nested inside Outers element in the xml). I have this code
object Xmlizer {

    def main(args: Array[String]) {
        val outers = (1 to 2).map(o => new Outer("outer" + o, List(new Inner("i"))))

        val root = <root>
                    { outers.map(o => <item>{o.n}</item> { o.i.map (i => <item>{i.n}</item>) } ) }
                </root>

        println(root)
    }
}

This generates a compiler error
 error: overloaded method value apply with alternatives:
  (f: scala.xml.Node => Boolean)scala.xml.NodeSeq <and>
  (i: Int)scala.xml.Node
 cannot be applied to (Seq[scala.xml.Elem])
                    { outers.map(o => <item>{o.n}</item> { o.i.map (i => <item>{i.n}</item>) } ) }

I have nested comprehensions working where the nested loop is within a pair of elements, and if i simplify to one comprehension that works, e.g.
val root = <root>
            { outers.map(o => <item>{o.n}</item><item>{o.i.head.n}</item> ) }
        </root>

so its not like the { } needs to return a single container element, but when i expand Inner to be another comprehension it gives the compiler error. Is there some trick to getting this working, or do i need to somehow flatten the scala data into a single list first?

A: You should create a flat collection of items:
<root>
  { outers.flatMap(o => <item>{o.n}</item> +: o.i.map{ i => <item>{i.n}</item> } ) }
</root>
// <root><item>outer1</item><item>i</item><item>outer2</item><item>i</item></root>

With <item>{o.n}</item><item>{o.i.head.n}</item> you are creating a combination of 2 objects of the same type, compiler is smart enough to create it.
But this code:
<item>{o.n}</item> { o.i.map (i => <item>{i.n}</item>) }

actually looks like this:
<item>{o.n}</item>{Seq(<item>{o.i.head.n}</item>)}

You are trying to combine 2 object of completely different types. You should tell to compiler how to combine Node with Seq[Node]:
<item>{o.n}</item> +: o.i.map (i => <item>{i.n}</item>)


text:
Q: Convert XML file to PDF using XSLT and CSS (with free software license) I'm trying to convert XML report into PDF using XSLT and CSS. This PDF should include specific page numbering in the footer and e.g. page break after a particular table.
From what I found this can be achieved using CSS3 "at-attributes" for "paged media" (e.g. @page). However, if I understand correctly, I might have a problem finding a tool that interprets these attributes to create PDF (not to mention that it needs to converts from XML first).
I found that I could use paged.js script to have it working in a browser, but it works only if I run local server (e.g. live-server) because of some local file restriction in all web browsers. I can (kind of) overcome this using command line switches like --allow-file-access-from-files but it prints the document before rendering is complete (it looks like the browser do not wait for the paged.js script to finish). I tried different switches: chrome.exe --headless --disable-gpu --allow-file-access-from-files --run-all-compositor-stages-before-draw --virtual-time-budget=100000 --print-to-pdf="<destination>" "<source>". Perhaps some switches for node engine could help?
My question is how can I programmatically convert the XML file to PDF, using XSLT to extract data of interest from XML, and CSS to format PDF as the proper paged document, using software with a free commercial license? Do I need paged.js to accomplish it?
About my files:
In my XML file, I reference local XSL files that extract particular data from XML; they remove duplicates and sort them by date. This XSL file reference local CSS file to provide nice formatting and also "paged" attributes. XSL reference also paged.js script and associated CSS, as in the script documentation.
I tried, between the other, weasyprint, htmldoc, html5-to-pdf and wkhtmltopdf without success.
I'm open for any suggestion.

EDIT: I was experimenting with XSL-FO (as suggested in the comment) and I have to admit that it works pretty well. It seems to me that page control is even more readable than in CSS. The only problem I see now is that it requires additional installations (Apache FOP and Java Runtime Environment). In my scenario it would be better to have FOP in .NET.
Anyway, I decided to describe in more detail my CSS-based solution with Chrome as a renderer because it does not requires additional installers (or at least that what I think). I already spend some time with it and it seems that it's almost working. Perhaps someone will spot where the problem is and then it would become a pretty nice solution for paged media with CSS.
Complete transform.xsl file is:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">

            <title>Summary</title>
            <link href="css/style.css" rel="stylesheet" type="text/css"/>
            <link href="css/interface.css" rel="stylesheet" type="text/css"/>

redpajama_set_name: RedPajamaStackExchange


text:
Q: The graph of $f$ is a connected subset of $\mathbb{R}^2$. Let a function $f:[0,1]\to\Bbb R$ given by $f(x)=\sin(\frac lx)$ for $x\ne 0$ and $f(0) = 0$. Show that although $f$ is not continuous, the graph of $f$ is a connected subset of $\mathbb{R}^2$.
I was wondering on how to prove this.
I have read that the closure of a connected set is also connected, so if I can show the given set is a closure of some connected set then I am done.
Could you please help me out.


text:
Q: Añadir diccionarios dentro de una lista (Python) tengo que crear un programa que me ayude a llevar un registro de gastos. El programa tiene que hacer 3 preguntas para cada gasto: el motivo, el lugar y la cantidad. Tras cada gasto introducido, el programa preguntará si quiero introducir otro gasto más. Al finalizar, el programa debe imprimir todos los gastos en el mismo orden que los introduje y la cantidad total de dinero gastado.
Bien, he hecho un código y al ejecutarlo parece que funciona, excepto porque solo si queda el último gasto introducido. Creo que el error viene de que no estoy introduciendo bien los diccionarios dentro de la lista.
Aquí os dejo el código:

Y este es un ejemplo del resultado que obtengo:


text:
Q: Emgu CV undistort image gives blank result sometimes Im undistorting an image using intrinsic values of camera martix and distortion coeeficient. It corrects the distortion perfectly. But if I load same image twice, sometimes it gives out a blank gray image. Not sure why this is happening.
 void distort()
    {

            Mat cameraMatrix = new Mat(3, 3, DepthType.Cv64F,1);

            Mat distCoeffs = new Mat(8, 1, DepthType.Cv64F, 1);

            //Camera matrix values
            double fx = 5715.63;
            double fy = 5788.09;
            double cx = 1339.66;
            double cy = 941.89;
            //double skew = 0.11273;

            //Optical distortion coefficient values
            double k1 = -2.006166;
            double k2 = 5.478401;
            //double k3 = 0.001513;
            double p1 = 0.007517;
            double p2 = -0.007439;

            //Set the camera matrix
            cameraMatrix.SetValue(0, 0, fx);
            cameraMatrix.SetValue(1, 1, fy);
            cameraMatrix.SetValue(1, 0, 1);
            cameraMatrix.SetValue(0, 2, cx);
            cameraMatrix.SetValue(1, 2, cy);
            cameraMatrix.SetValue(2, 2, 1);

            //Set the distortion matrix
            distCoeffs.SetValue(0, 0, k1);
            distCoeffs.SetValue(1, 0, k2);
            distCoeffs.SetValue(2, 0, p1);
            distCoeffs.SetValue(3, 0, p2);

            //Read the input image

            image = CvInvoke.Imread(@"33.bmp", ImreadModes.Color);

            Correct the input image
            Mat outFrame = image.Clone();
            CvInvoke.Undistort(image, outFrame, cameraMatrix, distCoeffs);

            //save the corrected image
            image = outFrame.Clone();
            imageBox1.Image = image.Bitmap;

            image.Dispose();
            outFrame.Dispose();

    }


text:
Q: Generating PDFs using Phantom JS on .NET applications I have been looking into phantomJS and looks like it could be a great tool to use generating PDFs. I wonder if anyone have successfully used it for their .NET applications.
My specific question is: how would you use modules like rasterize.js on the server, receive requests and send back generated pdfs as a response.
My general question is: is there any best practice for using phantomJS with .NET Applications. What would be the best way to achieve it?
I am fairly new in .NET World and I would appreciate the more detailed answers. Thanks everyone. :)

A: I don't know about best practices, but, I'm using phantomJS with no problems with the following code.
public ActionResult DownloadStatement(int id)
{
    string serverPath = HttpContext.Server.MapPath("~/Phantomjs/");
    string filename = DateTime.Now.ToString("ddMMyyyy_hhmmss") + ".pdf";

    new Thread(new ParameterizedThreadStart(x =>
    {
        ExecuteCommand("cd " + serverPath + @" & phantomjs rasterize.js http://localhost:8080/filetopdf/" + id.ToString() + " " + filename + @" ""A4""");
    })).Start();

    var filePath = Path.Combine(HttpContext.Server.MapPath("~/Phantomjs/"), filename);

    var stream = new MemoryStream();
    byte[] bytes = DoWhile(filePath);

    return File(bytes, "application/pdf", filename);
}

private void ExecuteCommand(string Command)
{
    try
    {
        ProcessStartInfo ProcessInfo;
        Process Process;

        ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);
        ProcessInfo.CreateNoWindow = true;
        ProcessInfo.UseShellExecute = false;

        Process = Process.Start(ProcessInfo);
    }
    catch { }
}

public ViewResult FileToPDF(int id)
{
    var viewModel = file.Get(id);
    return View(viewModel);
}

private byte[] DoWhile(string filePath)
{
    byte[] bytes = new byte[0];
    bool fail = true;

    while (fail)
    {
        try
        {
            using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                bytes = new byte[file.Length];
                file.Read(bytes, 0, (int)file.Length);
            }

            fail = false;
        }
        catch
        {
            Thread.Sleep(1000);
        }
    }

    System.IO.File.Delete(filePath);
    return bytes;
}

Here is the action flow:
The user clicks on a link to DownloadStatement Action. Inside there, a new Thread is created to call the ExecuteCommand method.
The ExecuteCommand method is responsible to call phantomJS. The string passed as an argument do the following.
Go to the location where the phantomJS app is and, after that, call rasterize.js with an URL, the filename to be created and a print format. (More about rasterize here).
In my case, what I really want to print is the content delivered by the action filetoupload. It's a simple action that returns a simple view. PhantomJS will call the URL passed as parameter and do all the magic.
While phantomJS is still creating the file, (I guess) I can not return the request made by the client. And that is why I used the DoWhile method. It will hold the request until the file is created by phantomJS and loaded by the app to the request.

A: If you're open to using NReco.PhantomJS, which provides a .NET wrapper for PhantomJS, you can do this very succinctly.
public async Task<ActionResult> DownloadPdf() {
    var phantomJS = new PhantomJS();
    try {
        var temp = Path.Combine(Path.GetTempPath(),
            Path.ChangeExtension(Path.GetRandomFileName(), "pdf")); //must end in .pdf
        try {
            await phantomJS.RunAsync(HttpContext.Server.MapPath("~/Scripts/rasterize.js"),
                new[] { "https://www.google.com", temp });
            return File(System.IO.File.ReadAllBytes(temp), "application/pdf");
        }
        finally {
            System.IO.File.Delete(temp);
        }
    }
    finally {
        phantomJS.Abort();
    }
}

A: Here's some very basic code to generate a PDF using Phantom.JS but you can find more information here: https://buttercms.com/blog/generating-pdfs-with-node
var webPage = require('webpage');
var page = webPage.create();

page.viewportSize = { width: 1920, height: 1080 };
page.open("http://www.google.com", function start(status) {
page.render('google_home.pdf, {format: 'pdf', quality: '100'});
phantom.exit();
});


text:
Q: OCR Scanning with specific font I am implementing an OCR scanning library for Android App which scans not just numbers but also scan those number with specific fonts which I have defined manually somewhere in library.
I am trying to implement "TESSERACT" library but didn't found font specific scanning implementation. I am using following code to scan OCR not a particular font. My implementation is given below:
 private void processImage(Bitmap bMap, String imagePath) {
        try {
            datapath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tesseract/";
            checkFile(new File(datapath + "tessdata/"));
            TessBaseAPI baseApi = new TessBaseAPI();
            baseApi.init(datapath, "eng");
            baseApi.setImage(bMap);
            String recognizedText = baseApi.getUTF8Text();
            baseApi.end();
            Log.e("log_tag", "onActivityResult recognizedText : " + recognizedText);
            Fragment myFragment = getActiveFragment();
            if (myFragment != null && myFragment.isVisible() && myFragment instanceof ScanPrescriptionFragment7c) {
                ((ScanPrescriptionFragment7c) myFragment).displaySelectedImage(recognizedText, imagePath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

Is there any way i can achieve font independent OCR implementation or atleast can provide a custom font to scan for during initialization of OCR?
Thanks!

A: I do not understand exactly why do you need to specify a font to recognize the characters, do you want to scan different languages or something like that?
I have been developing an Android app with OCR using Tesseract and I wrote down my conclusions and included an example in this post, have a look at it, might be useful to solve your case.


text:
Q: iOS 7 change UITableViewCell font color to blue like in Settings app I have a UITableview in grouped style and there is one cell that I want to use like a button. My problem is, the font color of this cell is by default black. I want to have the same blue as font color as the cells used as buttons in the settings app (e.g. in settings/safari the delete history cell is used as a button and has this light iOS 7 styled blue as font color). I would love it if anybody could help me.
Much love, Timm

A: You can use this line of code in your cellForRowAtIndexPath method to set up UITableViewCell's font color:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    // (cell creation)...

    // set to the color that Apple uses
    cell.textLabel.textColor = [UIColor colorWithRed:0.204 green:0.459 blue:1.000 alpha:1.0];
    return cell;
}

Let me know if this helped you.

A: If you're using a storyboard or xib and you have a prototype cell, go in to it and select the label. Then you can set the color of the text.
If you want to do it programmatically, add the following to your tableView:cellForRowAtIndexPath: method:
cell.textLabel.textColor = [UIColor blueColor];

blueColor isn't exactly the same as the blue used by buttons in iOS 7, but you could manually pick a color that closely approximates it if you wanted instead.
EDIT:
This will give you the exact color you want:
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
cell.textLabel.textColor = [button titleColorForState:UIControlStateNormal];

It's getting the color from a UIButton.


text:
Q: Changing AVPlayerView background color Is it possible to change the background color of a AVPlayerView when used in a macOS application. I want to do this to remove the black bars when playing a video.
I've tried the following:
videoView.contentOverlayView?.wantsLayer = true
videoView.contentOverlayView?.layer?.backgroundColor  = NSColor.blue.cgColor

also tried adding these:
view.wantsLayer = true
videoView.wantsLayer = true

but the background is still black.

A: AVPlayerView does not have layer after the initialization or setting wantsLayer property, but creates it later at some point. I was able to change the background with the next code in my AVPlayerView subclass:
override var layer: CALayer? {
    get { super.layer }
    set {
        newValue?.backgroundColor = CGColor.clear
        super.layer = newValue
    }
}

A: videoView.contentOverlayView?.layer?.setNeedsDisplay()

try this maybe you just need to update the view. However if you would post more of your code I could try to help more.


text:
Q: Relocatable selfcontained homebrew archive with all dependencies included I'm new to the homebrew ecosystem and I'm struggling with the following task:
I want to make an archive (tar.bz2) from a homebrew formula with all its dependencies included. This archive is going to be moved to another machine where I don't have any access to internet. I also don't want to unpack it in /opt/ but in a temporary directory.
(I'm using dcraw here as an example as it doesn't have that many dependencies.)
My current attempt is to use https://github.com/timsutton/brew-pkg to make a pkg that contains all libraries.
brew pkg --with-deps --without-kegs dcraw

I unpack the pkg using:
pkgutil --expand-full dcraw-9.28.0_1.pkg dcraw

I now have all the files I want in ~/draw/Payload/.
If I then uninstall dcraw and little-cms2 just to make sure it runs the "relocated" dcraw I get this:
cd ~/draw/Payload/opt/homebrew/bin/
./dcraw

How can I get dcraw to search for libraries in ../lib/ instead?
How can I solve this? Or is there a better approach?


text:
Q: Embed processing 3 into swing I'm trying to integrate Processing 3 into a swing application, but because PApplet doesn't extend Applet anymore I can't just add it as a component right away.
Is there anyway of embeding a Processing 3 sketch into Swing, it would be enough if I could just open the sketch in a seperate window without the PDE.

A: You can run a sketch from Java by extending PApplet and then using the runSketch() function to run that PApplet. It'll look something like this:
String[] args = {"MyPapplet "};
MyPapplet mp = new MyPapplet ();
PApplet.runSketch(args, mp);

public class MyPapplet extends PApplet {

  public void settings() {
    size(200, 100);
  }
  public void draw() {
    background(255);
    fill(0);
    ellipse(100, 50, 10, 10);
  }
}

Then if you want to get at the underlying component, you have to write code that depends on which renderer you're using. Here's how you'd do it with the standard renderer:
PSurfaceAWT awtSurface = (PSurfaceAWT)mp.surface;
PSurfaceAWT.SmoothCanvas smoothCanvas = (PSurfaceAWT.SmoothCanvas)awtSurface.getNative();

Once you have the SmoothCanvas, you can remove it from its frame and add it to yours.


text:
Q: Is it possible to associate custom test with TFS/MTM Test case? I have created a VSIX based test adapter using visual studio test platform(vstest) API. It will read my custom test item(in xml) where my test information is there and it will enable the unit test explorer in visual studio to list my tests written in custom test file. (I referred the following blog to create the adapter
https://devblogs.microsoft.com/devops/writing-a-visual-studio-2012-unit-test-adapter/#)
I am able to get my custom tests discovered under Unit Test Explorer. But I am not able to associate those tests with TFS/MTM manual test cases. When I right click the test case, the "Associate to Test Case" option is disabled.
Is it possible to get that option enabled to associate with a manual TFS test case ?
NOTE: I am able to associate a .net based unit test method by this way. My VS version is 15.9.2


text:
Q: Utilizar el SSRS (SQL Server Reporting Services) con MariaDB 10.1.21 Me gustaría saber que version del SSDT (SQL Server Data Tools) tengo que instalar con el Visual Studio para poder utilizar el SSRS con MariaDB 10.1.21.
Y que version del driver ODBC necesito para la conexion del Visual Studio con la base de datos MariaDB.
Aqui os dejo un enlace con las posibles descargas:
SSDT
Gracias

A: Para usar SSRS con mariadb 10.1.21 Puedes usar las SSDT para VS2015 y el driver odbc 5.1.13 para mysql


text:
Q: JS execution & scope I'm a JS beginner. I'm trying to understand why calling fn() produces "undefined" when I use var to declare letVar and gives a ReferenceError when I use let to declare letVar.
Using var:
var letVar = "Outer";

function fn() {
    console.log(letVar); // undefined
    var letVar = "Inner";
}

fn();

Using let:
let letVar = "Outer";

function fn() {
    console.log(letVar); // ReferenceError
    let letVar = "Inner";
}

fn();

From my understanding, using var initializes letVar with a value of undefined when the program is compiled. However, when the program is executed, wouldn't letVar be  assigned the value "Outer", meaning that fn() should produce "Outer"?
Furthermore, in the code that uses let, shouldn't console.log(letVar); have access to letVar = "Outer" because let letVar = "Outer"; is a global declaration & assignment? Thus, shouldn't calling fn() also produce "Outer"?
Thank you in advance :)


text:
Q: How do I click on an image change to other image and click to a video I'm having a problem on processing with keyPressed/mousePressed.
If for example I have some data file of Images apple, dog & cat, with two videos forest & garden.
The problem is I want to press a button and change to an image and when pressed again to change to a video.
For example start with
video = "forest.mp4" > keyPressed = UP > apple.jpg ;
with two selection of LEFT or RIGHT >

*

*if keyPressed = LEFT > dog.jpg

*if keyPressed = RIGHT > cat. jpg
both of them keyPressed = UP > video = "garden"
Movie myMovie[];
int index = 0;
boolean start = false;
float t0; //Movie Begin
float t; //current time

void setup(){
 size(1280,720);

img = new Image[2];
img = new Image(this, "apple.jpg");
img = new Image(this, "dog.jpg");
img = new Image(this, "cat.jpg");

myMovie = new Movie[3];
myMovie[0] = new Movie(this, "forest.mp4");
myMovie[1] = new Movie(this, "garden.mp4");
}
void draw(){
image (img, 0 ,0);
image(img, 0 ,height, img.height, img, height);

if (myMovie[index].read();
}

if (start){
 image(myMovie[index],0,0,width,height);

This is something like a old version of RPG game, adventure type of game.
While the player click on different selections would appear different results.

A: Step 1: Store your state in a variable.
boolean showingMovie = true;

Step 2: In the draw() function, check that variable and draw the correct thing.
void draw(){
   if(showingMovie){
      //draw your movie
   }
   else{
      //draw your image
   }
}

Step 3: Change that variable in the keyPressed() or mousePressed() functions to switch which thing is showing.
void keyPressed(){
   showingMovie = !showingMovie;
}

You might have to have some logic for only reading the movie when the variable indicates that the movie is playing, and you might have to add some logic to only switch the variable when the mouse is clicked in the correct location, or the correct key is pressed. You also might have to have multiple variables if you have multiple movie/image combinations. If you have a lot of these, you might even use an array or a class to hold all your data.


text:
Q: Cannot copy long path files in Windows 10 within Dockerfile COPY I build an image from a base image. In the Dockerfile of the base image I run a command ONBUILD COPY . /workspace. When I build my image from this base image then it copy all the files from current directory to the /workspace directory of the result image.
Then I run mvn clean install from the Dockerfile with an error: cannot find symbol. The problem is that all the .java files that has long path names are not copied from current directory to the /workspace directory and so the error.
I tried to activate long pathns in Local Computer Policy, I also checked it in the registry, but it does't helped. I tried to run CMD as Administrator and then also tried to build from Git Bash command line, none fixed the problem.
Does anyone knows what could be the problem and how to resolve it?


text:
Q: Asyncio gather difference From my understanding, both the code blocks are doing the same thing. Why there is a difference in execution time?
import asyncio
import time
...

# Block 1:
start_time = time.time()
tasks = [
    get_from_knowledge_v2(...),
    get_from_knowledge_v2(...),
    get_from_knowledge_v2(...),
]
data_list = await asyncio.gather(*tasks)
print("TIME TAKEN::", time.time() - start_time)

# Block 2:
start_time = time.time()
data1 = await get_from_knowledge_v2(...)
data2 = await get_from_knowledge_v2(...)
data3 = await get_from_knowledge_v2(...)
print("WITHOUT ASYNCIO GATHER TIME TAKEN::", time.time() - start_time)

Result:
TIME TAKEN:: 0.6016566753387451
WITHOUT ASYNCIO GATHER TIME TAKEN:: 1.7620849609375

A: The asyncio.gather function runs the awaitables you pass to it concurrently. That means, if I/O is happening in at least one of them that allows for useful context switches by the event loop. That in turn leads to a certain degree of parallelism.
In this case I assume that get_from_knowledge_v2 does some HTTP request in a way that supports asynchronous execution.
In the second code block you have no concurrency between the three get_from_knowledge_v2 calls. Instead you just execute them sequentially (with respect to each other). In other words, while you are awaiting the first one of them, the second one will not start. Their context is blocked.
Note: This does not mean that outside of that code block no concurrency is happening/possible. If this sequential code block is inside an async function (i.e. coroutine), you can execute that concurrently with some other coroutine. It is just that inside that code block, those get_from_knowledge_v2 coroutines are executed sequentially.
The time you measured confirms this rather nicely since you have three coroutines and gather allows them to be executed almost in parallel, while the other code block executes them sequentially, thus leading to an almost three times longer execution time.
PS
Maybe a minimal concrete example will help illustrate what I mean:
from asyncio import gather, run, sleep
from time import time

async def sleep_and_print(seconds: float) -> None:
    await sleep(seconds)
    print("slept", seconds, "seconds")

async def concurrent_sleeps() -> None:
    await gather(
        sleep_and_print(3),
        sleep_and_print(2),
        sleep_and_print(1),
    )

async def sequential_sleeps() -> None:
    await sleep_and_print(3)
    await sleep_and_print(2)
    await sleep_and_print(1)

async def something_else() -> None:
    print("Doing something else that takes 4 seconds...")
    await sleep(4)
    print("Done with something else!")

async def main() -> None:
    start = time()
    await concurrent_sleeps()
    print("concurrent_sleeps took", round(time() - start, 1), "seconds\n")

    start = time()
    await sequential_sleeps()
    print("sequential_sleeps took", round(time() - start, 1), "seconds\n")

    start = time()
    await gather(
        sequential_sleeps(),
        something_else(),
    )
    print("sequential_sleeps & something_else together took", round(time() - start, 1), "seconds")

if __name__ == '__main__':
    run(main())

Running that script gives the following output:
slept 1 seconds
slept 2 seconds
slept 3 seconds
concurrent_sleeps took 3.0 seconds

slept 3 seconds
slept 2 seconds
slept 1 seconds
sequential_sleeps took 6.0 seconds

Doing something else that takes 4 seconds...
slept 3 seconds
Done with something else!
slept 2 seconds
slept 1 seconds
sequential_sleeps & something_else together took 6.0 seconds

This illustrates that the sleeping was done almost in parallel inside concurrent_sleeps, with the 1 second sleep finishing first, then the 2 second sleep, then the 3 second sleep.
It shows that the sleeping is done sequentially inside sequential_sleeps and in the call order, meaning it first slept 3 seconds, then it slept 2 seconds, then 1 second.
And finally, executing sequential_sleeps concurrently with something_else shows that they are executed almost in parallel, with the 3-second-sleep finishing first (after 3 seconds), then one second later something_else finished, then another second later the 2-second-sleep, then after another second the 1-second-sleep. Together they still took approximately 6 seconds.
That last part is what I meant, when I said you an still execute another coroutine concurrently with the sequential block of code. In itself, the code block will still always remain sequential.
I hope this is clearer now.
PPS
Just to throw another option into the mix, you can also achieve concurrency by using Tasks. Calling asyncio.create_task will immediately schedule the coroutine for execution on the event loop. The task it creates should be awaited at some point, but the underlying coroutine will start running almost immediately after calling create_task. You can add this to the example script above:
from asyncio import create_task
...
async def task_sleeps() -> None:
    t3 = create_task(sleep_and_print(3))
    t2 = create_task(sleep_and_print(2))
    t1 = create_task(sleep_and_print(1))
    await t3
    await t2
    await t1

async def main() -> None:
    ...
    start = time()
    await task_sleeps()
    print("task_sleeps took", round(time() - start, 1), "seconds\n")

And you'll see the following again:
...
slept 1 seconds
slept 2 seconds
slept 3 seconds
task_sleeps took 3.0 seconds

Tasks are a nice option to decouple the execution of some coroutine from its surrounding context to an extent, but you need to keep track of them in some way.


text:
Q: Using StringBuffer and Generics I was trying to use StringBuffer and Generics, but the code won't compile:
[Gen.java]
class Gen<T>
{
T ob;
//Constructor
Gen (T o)
{
 ob = o;
}

void showtype()
{
    System.out.println("Type of T is:"+ob.getClass().getName());
}

T getOb()
{
    return ob;
}

}

[GenDemo.java]
public class GenDemo
{
public static void main(String[] args)
{

    Gen<StringBuffer> objStr;
    objStr = new Gen<StringBuffer> ("Hello"); //doesn't compile here.
    objStr.showtype();
    StringBuffer str = objStr.getOb();
}
}

I am a beginner. So, I apologize if this question is too basic for you. Can someone please help me? The code compiles well if I replace "StringBuffer" with "String"
Thanks

A: You can't assign between incompatible types in Java. e.g. you can't do this
StringBuilder sb = "Hello"; // the object String is not a StringBuilder

What you can do is pass a reference of one type to the constructor of another e.g.
StringBuilder sb = new StringBuilder("Hello");

and you could do
Gen<String> str = new Gen<>("Hello");

or
Gen<StringBuilder> sb = new Gen<>(new StringBuilder("Hello"));

However, Java doesn't support implicit conversions of objects or references.

A: You're trying to initialise a Gen<StringBuffer> with a String. Change the initialisation to objStr = new Gen<StringBuffer>(new StringBuffer("Hello")) and everything should be fine.


text:
Q: How can export to PDF a visualization that is larger than a regular page? Issue mentioned on Export PDF I have a Page in Spotfire which sometime has a size larger than a regular page, when I export it using IronPython it is exported but the visualization gets cut and is added in a single page, how can extend the export to several pages(I can modify the page size but I would rather to keep it in A4 page size in Portrait Orientation )
I have review the Spotfire API https://docs.tibco.com/pub/doc_remote/sfire_dev/area/doc/api/TIB_sfire-analyst_api/html/T_Spotfire_Dxp_Application_Export_PdfExportSettings.htm?_ga=2.144772595.67263854.1559743187-1213380950.1541709588
but even if I change the "Scope" or "UseEntirePage" properties I get this behaviour
pdfexpsettings = PdfExportSettings()
pdfexpsettings.UseEntirePage = True
pdfexpsettings.IncludePageFooter=True
pdfexpsettings.Scope = ExportScope.ActiveVisualization
pdfexpsettings.IncludeNonVisibleContent = True
if Document.Properties["Orientation"] == 0:
    pdfexpsettings.PageOrientation = PageOrientation.Portrait
else:
    pdfexpsettings.PageOrientation = PageOrientation.Landscape
pdfexpsettings.IncludeFilterSettings = False
pdfexpsettings.IncludePageTitles = False
pdfexpsettings.IncludeVisualizationTitles = True
pdfexpsettings.IncludeVisualizationDescriptions = False
size = Document.Properties["Size"]
if size == 0:
    pdfexpsettings.PaperSize = PaperSize.A4
elif size ==1:
    pdfexpsettings.PaperSize = PaperSize.Letter
elif size ==2:
    pdfexpsettings.PaperSize = PaperSize.A0
elif size ==3:
    pdfexpsettings.PaperSize = PaperSize.A1
elif size ==4:
    pdfexpsettings.PaperSize = PaperSize.A2
elif size ==5:
    pdfexpsettings.PaperSize = PaperSize.A3
elif size ==6:
    pdfexpsettings.PaperSize = PaperSize.A5
elif size ==7:
    pdfexpsettings.PaperSize = PaperSize.Legal
if Document.Properties["Orientation"] == 0:
    pdfexpsettings.PageOrientation = PageOrientation.Portrait
else:
    pdfexpsettings.PageOrientation = PageOrientation.Landscape


text:
Q: Why does the conductivity $\sigma$ decrease with the temperature $T$ in a semi-conductor? We performed an undergrad experiment where we looked at the resistance $\rho$ and Hall constant $R_\text H$ of a doped InAs semiconductor with the van der Pauw method. Then we cooled it down to around 40 K and did temperature-dependent measurements up to around 270 K. We were asked to create the following three plots from our measurements and interpret them.
This is conductivity $\sigma = 1 / \rho$ versus the inverse temperature $T^{-1}$. I see that increasing the temperature (to the left) decreases the conductivity. I do understand that higher temperatures do that since the electrons (or holes) have more resistance due to phonon scattering. However, since higher temperatures mean a higher amount of free electrons, I would think that $\sigma$ should go up, not down.
http://chaos.stw-bonn.de/users/mu/uploads/2013-12-07/plot1.png
The density of holes $p = 1/(e R_\text H)$ does increase with the temperature, that is what I would expect:
http://chaos.stw-bonn.de/users/mu/uploads/2013-12-07/plot2.png
And the electron mobility $\mu = \sigma R_\text H$ decreases with the temperature as well:
http://chaos.stw-bonn.de/users/mu/uploads/2013-12-07/plot3.png
Now, I am little surprised that even though $p$ goes up with $T$, $\mu$ and $\sigma$ go down with $T$. Are the effects of phonon scattering and other things that increase the resistance that strong?

A: Phonon scattering goes up a lot as temperature increases -- faster than electron numbers increase in the conduction band.
Keep in mind that phonons obey the Bose-Einstein distribution, so their numbers scale like
$$N_{BE}=\frac{1}{e^{\frac{\hbar\omega}{k_b T}}-1}$$
In the large $T$ limit, this becomes
$$\frac{k_b T}{\hbar\omega}$$
So their numbers roughly scale linearly with temperature at "high temperature". For phonons, "high temperature" means above the Debye temperature, but that's only ~650K for silicon; you're a good chunk of the way there at room temperature.
However, electrons follow a Fermi-Dirac distribution, so you'd expect their numbers to scale like.
$$N_{FD}=\frac{1}{e^{\frac{\epsilon}{k_b T}}+1}$$
In the large T limit, this goes to $\frac{1}{2}$.
There's also a chemical potential for the electrons that limits their numbers. Phonons have no such restriction; given the energy, you can have as many phonons as you want.
Even if you're not talking about high temperatures, note that the $N_{BE}>N_{FD}$ is always true.


text:
Q: How to make a webpage look like a popup? I have a web page on which an anchor tag  links to another page.
I want this other-page.php appear like a pop-up on the page which contains the aforementioned  tag.
Is it possible using CSS and/or JQuery?
If yes, what is the general idea? How to do it?

A: If you want the link to open up a new browser window, you need the 'target' attribute on the anchor tag, like this:

If you don't want a full browser window, just a pop-out window with an 'x' close tab, you're looking for a "modal" window. There are modal jquery libraries that will do that. Check out simplemodal. That's just one of many libraries, but now you have a search term.

A: You have 2 choices:
- The firstone is act like that, just 1 page, put all the content in just 1 html. Put display: none; to all the other divs(all what you don't want show to the user) and then via JS change the visibility via
$('div').show;
/* or*/
 $('div').hide;

- The secondone: is display:none or visibility:hidden to a global div (within all the page content) in visibility: hidden, or display:none and change it via:
$(document).ready(function(){
 $(divToShow).show('slow');
/* or */
 $(divToShow).slideup('slow');
/* or some effect */
});

The lastone it make a modal but depend the content It's
non-viable
Hope I helped,


text:
Q: How to Style text in Textarea Container? I have a textarea tag in My modal for editing.
When I want to show my note in textarea, it shows text in center of the textarea box.
I try text-alighn,direction and float,also I tried to put my note in p tag,but I does not work.
all that I do,is shown I picture.

How can i fix this problem?

A: Can you try to add dir="rtl" to the div wrapper of the textarea:

    <textarea></textarea>

A: this CSS code can align your text from the right for Farsi
   textarea {
        white-space: normal;
        text-align: right;
        -moz-text-align-last: right; /* Firefox 12+ */
        text-align-last: right;
        direction: rtl;
    }

and your HTML can be like this

  <textarea class="area" col="2" row="5">این نوشته از راست است.</textarea>

A:    use text-align:left !important
   or float:left !important


text:
Q: Android Lifecycle management of Fragments within ViewPager and FragmentPagerAdapter I have been struggling to find out what the correct management of Fragments within a FragmentActivity with a ViewPager is. Before I go into details, a quick summary of the issue that I am facing is the following:
I have a FragmentActivity with a ViewPager. The ViewPager uses a custom, yet very simple FragmentPagerAdapter. Each Fragment within the ViewPager comprises of an ExpandableListView. I also have an action bar button called "Refresh". For now, let's assume that the ViewPager has only one Fragment. The activity is created, and the Fragment's ExpandableListView is populated (so far so good). When the Refresh button is clicked, the handling method within the FragmentActivity iterates over the list of Fragments that are assigned to the FragmentPagerAdapter and calls refresh() on each Fragment to populate its ListView. However, when the orientation of the device changes (e.g. from portrait to landscape), the Activity is recreated and so are the fragments. Clicking the Refresh button now will iterate over non-initialised Fragments.
I know that I am being quite vague, especially without sample code, but please bear with me. I have traced the problem and method calls as follows from the start of the application/activity:

*

*FragmentActivity.onCreate()

*FragmentActivity.setContentView()

*FragmentActivity.createPagerFragments() <-- this creates an ArrayList of Fragments and assignes them to a new FragmentPagerAdapter which is in turn assigned to the ViewPager.

*Fragment.onAttach()

*Fragment.onCreate() <-- nothing special here, just calling the super method.

*Fragment.onCreateView() <-- nothing special here either, just inflating the layout

*Fragment.onActivityCreated() <-- nothing here either.

*<< All good, orientation changes here >>

*FragmentActivity.onCreate()

*Fragment.onAttach()

*Fragment.onCreate()

*FragmentActivity.setContentView()

*FragmentActivity.createPagerFragments()

*Fragment.onCreateView()

*Fragment.onActivityCreated()

*<< Refresh button clicked >>

*FragmentActivity.refresh() <-- iterates over the newly created Fragments from #13 (not these by Android!).

*<< Crash: NullPointerException for mExpandableListView in Fragment. >>

So the problem, as I see it, is as follows:
When Android re-creates the FragmentActivity and its Views after a change of screen orientation (calls #9-15 above), it creates new Fragment objects with their state restored to what the original ones were. However, these ones appear to be completely managed by the FragmentManager, and not by the FragmentPagerAdapter. In contrast, when the FragmentPagerAdapter is re-created along with the Fragments in the activity's onCreate method (see call #13) the Fragments that get assigned to the adapter never have their Fragment.onCreate() or Fragment.onCreateView() methods called at all. So when the refresh() method is called (see #17) the method iterates over these Fragments that have not been initialised. Therefore, when they try to populate the ExpandableListView, the view's instance variable is NULL. This is to be expected as the instance variable is only assigned in the Fragment.onCreateView() method that never gets called on these Fragments.
So my question is: how does one properly make re-use of the re-recreated (by Android) Fragments after the screen orientation has changed in order to avoid creating new ones that don't get initialised? I need to have a valid reference to them, in order to call their refresh() method that populates them on-demand. Ideally, they should also be assigned to the FragmentPagerAdapter as well.
I hope I have been clear in describing the issue, and the reason that I have not provided sample code is because the problem (as can be seen) is not from the code itself but from a rather incorrect (seemigly) re-creation of Fragments rather than re-use. But if needed, I can give you sample code, I just through this way would be clearer.
Thank you!

A: It's lot to read, but after reading just introduction and the question and having experience with FragmentStatePagerAdapter, which is similar to FragmentPagerAdapter I can tell you that:
After rotation your adapter will AUTOMAGICALLY attach old fragments. So it seems that although activity creating adapter is being recreated, FragmentManager, which is global and it's instance preserve activity's recreation will detect that new FragmentStatePagerAdapter is combined with the same ViewPager and is asking for the same Fragments and will simply fetch them from Fragment's BackStack.
You as designer of Fragments can notice this behavior by continues invocation of Fragment.onAttach() and Fragment.onDetach(). When onAttach() occurs it's either creation of your Fragment or reusing it after rotation. You should be able to distinguish that Fragment was rotated with use of callback onRestoreRnstanceState().
You will see in your logs many onCreate() and other states logs simultaneously, because  FragmentStatePagerAdapter always fetches/creates min 3 Fragments (except if you set that they are only 2 or 1), so also after screen rotation 3 fragments will be reattached from backstack.
I hope that it helped.

A: I believe that this question, about retrieving the current fragment from a ViewPager, will help you. As already pointed out, fragments are managed by the Fragment(State)PagerAdapter and NOT Activity's or Fragment's lifecycle.

*

*The first time the activity is created, fragments are returned by the getItem method. This method is called only once per fragment, even if the activity gets recreated.

*Subsequent times, the fragments are returned by the instantiateItem method. Most probably, this is the place, where you need to get hold of your fragments and call their refresh methods.

A: How about adding this to Activity Tag in your manifest:
android:configChanges="orientation"

or this for API 13 or higher
android:configChanges="orientation|screenSize"

so it won't recreate your fragments when it changes orientation..


text:
Q: How can I dump a SELECT statement to the "Messages" pane in SQL Server mgmt studio from a stored procedure? I can use the PRINT statement in a stored procedure to debug my code.  I see the output in the Messages tab of SQL Server Management Studio.  How can I dump one or more entire SELECT statement outputs to that Messages tab?
My stored procedure returns several output variables so returning a single dataset isn't an option here. I am struggling with finding a good way to debug my complex procedures.

A: Getting the entire contents of a query to print to the messages window would probably be more trouble than it's worth.  Instead, I would recommend debugging the procedure from a query window.  What you can do is add an optional parameter to your procedure, with a default of NULL.  Your app won't be passing it, so you can use this to your advantage.  Ex:
Alter Procedure Foo(@Col1 int, @col2 varchar(20), @Debug Bit = NULL)
As
SET NOCOUNT ON

If @Debug = 1
  Begin
    Select * From SomeTable Where Col1 = @Col1
  End

-- The rest of your code here

Then, when you call this procedure from a query window, simply pass in a value of 1 to the procedure for that @Debug parameter

A: You might populate a temporary table, or table variable, from within your problematic stored procedure, then select from those tables after calling the stored procedure.  Make sure to drop and recreate any temporary tables in the sp.
CREATE TABLE ##t1 (x int)
GO

CREATE PROCEDURE Foo AS
BEGIN
  TRUNCATE TABLE ##t1
  INSERT INTO ##t1 SELECT column FROM table;
END
GO

exec Foo;
select x from ##t1;

A: Set the "Results to Text" option and your Results and Messages tabs will be consolidated to a single tab, combining your PRINT and SELECT statements.
To set Results to Text, either:

*

*Control-T

*Query menu \ Results To \ Results to Text

A: Does it have to be in the messages pane ? I always find it convenient to just run the select query, which outputs the results into the Results pane, with the actual output in another result set. Sometimes I include an 'identifier' column that helps identify the results. For instance:
select 'checkpoint1',a,b,c from table1
....
select 'table @a', *  from @a
....
<actual query here>

When the stored proc is ready to go just remove these scaffolding statements


text:
Q: Problems with Lazy Load and Mix It Up plugins I have a problem with my lazy-load target positioning.
Everytime I filter my list (which uses Mix It Up plugin), my images won't load on scrolldown, 'cause LazyLoad is targeting its old positioning.
How can I force Lazyload to properly target my images?

A: The old jquery lazyload isn't really made for dynamic webpages. In general the plugin only checks for user scroll. Additionally it has some flaws with runtime performance and managing memory.
I created a lazyloader, which is truly different from all other lazyloader: It uses a) highly efficient code and b) detects any visibility changes to current and future DOM elements automatically.
Here is a simple demo with mixitup:
http://codepen.io/aFarkas/pen/wByKeL
Everything you need to do is to add the lazySizes script and write the following markup:
<img data-src="img.jpg" class="lazyload" />

A: One option might be to use the callback features of MixItUp. Here is the MixItUp documentation, https://mixitup.kunkalabs.com/docs/#group-callbacks. I used onMixEnd to call my lazy loading functionality. This should ensure that all the images are in the correct place before the lazy load functionality takes over.
$(document).ready(function () {
    $('.container').mixItUp({
        callbacks: {
            onMixEnd: function () {
                $("img.lazy").lazyload();
            }
         }
     });
 });


text:
Q: Шасси и карты На работе часто встречается выражение "шасси, на которых крепятся карты, на которых находятся порты". Подскажите нубу, кое-какую информацию по подобной тематике (ссылки рекомендуются).
A: Если правильно понял вопрос, здесь под "шасси" имеются ввиду разъёмы на материнской плате для подключения периферийных устройств (например слоты PCI).![alt text][1]А вот, например, карта на которой находятся порты USB:![alt text][2]  [1]: http://i.imgur.com/uBGtD.jpg  [2]: http://i.imgur.com/AOm66.jpg


text:
Q: Document should never be Deleted if it is Referred to another Document in Mongodb I am new in MongoDB and stuck in one problem. Basically, when one document(i.e A) is referred to another document (i.e B). The document A should never get deleted. But if I first delete the B then only I should able to delete A because now A is not referred to any other document.
I have tried with pre middleware in here is my code

    model.collection('inventory').pre('deleteOne', function(next) {
       model.collection('inventory').Inventory.deleteOne({_id: this.id}, { _id: { $ne: this.id } }, {multi:
        true});
    });

below is the schema
```
schema 1:
{
_id: 1,
parent_id: null;
name: A
}

schema 2:
{
_id: 2,
parent_id: 1;
name: B
}
```

I think it can be achieved by pre middleware approach. Please help me with the code to achieve my outcome. I am also open to the other approach.
Thank You


text:
Q: Why do the EMNIST ByMerge and Balanced datasets have exactly 47 classes each? I am using EMNIST as a dataset for a text detection and recognition using deep learning. I downloaded the datasets from https://pypi.org/project/emnist/ (using pip install emnist). The datasets are from https://www.nist.gov/itl/products-and-services/emnist-dataset it describes them as follows:

EMNIST ByClass: 814,255 characters. 62 unbalanced classes.
EMNIST ByMerge: 814,255 characters. 47 unbalanced classes.
EMNIST Balanced:  131,600 characters. 47 balanced classes.
EMNIST Letters: 145,600 characters. 26 balanced classes.
EMNIST Digits: 280,000 characters. 10 balanced classes.
EMNIST MNIST: 70,000 characters. 10 balanced classes.

Most of these make sense for example 62 classes is made up of 10 digits, 26 capital letters and 26 lower case. But for ByMerge and Balanced we have 47.
I have looked into the data myself and find 10 digits, 26 letters (mixture of uppercase and lowercase) and then as far as I can tell the remaining 11 are random lowercase letters ('a','b','d','e','f','g','h','n','q','r','t').
Does anyone know why these extra 11 have been specifically included?

A: I have since found an answer to this question by looking into the paper EMNIST: an extension of MNIST to handwritten letters by G. Cohen (available here: https://arxiv.org/pdf/1702.05373v1.pdf).
This explains that many letters have problems in character recognition that the upper and lower case variants are very similar. This causes problems in trying to classify these letters. To counteract this they have merged the letters they thought this was a problem for.
From the paper:

The merged classes, as suggested by the NIST, are for the letters C,
  I, J, K, L, M, O, P, S, U, V, W, X, Y and Z.

This accounts for the missing classes (although I would have liked to see a 62 balanced class option or a 36 class option with all the letters merged).

A: I'm not sure if this is the correct answer, but here's my guess. Characters such as "C" or "S" have very similar looking uppercase and lowercase letters. Even for humans if you see a single "C" or "S" by itself it can be hard to differentiate between uppercase and lowercase letters. This is why I believe that the creators of the ByMerge split of EMNIST decided to exclude letters like that and only include letters like "A" or "R", which look very different from their lowercase counterparts.
For reference:
A, B, C, D, E, F, G, H, I, J, K
a, b, c, d, e, f, g, h, i, j, k
Some of these letters look very similar(e.g. C and K) whereas some others don't(e.g. b and g).


text:
Q: Wrong regular expression works Why is this happening? regular expression ignores tag <a and goes to the previous tag <a
$url = 'urband.net';
$p = '%(.{0,5})(.*?)(.{0,5})%imm';

$s = file_get_contents("http://boringmachines.blogspot.com/2006/12/bitbin-herb-recordings.html");
$out = preg_match_all($p, $s, $matches, PREG_SET_ORDER);
print_r($matches);

I get array:
Array
(
    [0] => Array
        (
            [0] => /div>Due to last weeks bad weather here in Glasgow, I was unable to connect to the web and keep up those regular Herb Recordings mp3's. Instead, I posted a video of one of their earlier releases, BitBin. Thankfully, some good has came from thsoe storms, as Herb have kindly donated another mp3, in the form of "May" by BitBin.

BitBin is a London based artist and had his "Alias" ep released by Herb earlier this year. He influences are both broad, and for and electronic producer, quite unusual. The likes of Brian Eno, Bola and Warp Records, sit side by side with Brian Wilson, Captain Beefheart and dEUS. His bio may explain a few things, as BitBin claims he is all about "glitching his way through any field of music and reality"

"May" itself is an expansive and dark slice of electronica reminiscent of Bola and Gescom. For me, however, this is akin to the music Thom Yorke has been pushing Radiohead towards over the last few years. The beats echo those of "Idioteque", and believe, me that is no bad thing.

The "Alias" ep can be ordered here, however, the cd release will feature 3 extra tracks, "making it, one longer trip". An interview and podcast with
            [1] => /div>
            [2] => interview and podcast
            [3] =>  with
        )

)

Although had to get:
Array
(
    [0] => Array
        (
            [0] => . An interview and podcast with
            [1] => . An
            [2] => interview and podcast
            [3] =>  with
        )

)

A: Welcome to the joys and wonders of using regexes on HTML. Try using DOM instead to find what you're looking for in the HTML.
An XPath query like //a[contains(@href,'urband.net')] would be far more accurate than the regex.

A: Try:
$url = 'urband\.net';
$p = '%(.{0,5})(.*?)(.{0,5})%imm';
edit - tested with Perl:
$/ = undef;

my $str = <DATA>;
my $count = 0;

while ($str =~ /(.{0,5})(.*?)<\/a>(.{0,5})/sg)
{
   print "Array\n";
   print "(\n";
   print "    [$count] => Array\n";
   print "        (\n";
   print "            [0] => $&\n";
   print "            [1] => $1\n";
   print "            [2] => $2\n";
   print "            [3] => $3\n";
   print "        )\n";
   print "\n";
   print ")\n";
   ++$count;
}

Output:
Array
(
    [0] => Array
        (
            [0] => . An interview and podcast with
            [1] => . An
            [2] => interview and podcast
            [3] =>  with
        )

)


text:
Q: Is it normal for relay to have quiet buzzing noise? I just noticed that a relays (SPST) that I am using for my project have constant but really quiet buzzing noise. The buzzing noise stops when relay is active.
Is this normal?

A: It's not nominal but not uncommon, so it'll depend on your definition of normal.
Most likely you are not providing enough power to hold the relay in whatever state it's in when powered. If it's close to the correct value, it'll operate, but will rattle or buzz.


text:
Q: I have problems to add a value from a variable to a total I have this script that calulates the total sum "totalsumma" when I fill a form. It works except from that I can not manage to add value from annonssumma to "totalsumma". I get error message NaN. see my attempts at the bottom of the script.
    <form method="post">
        <input type="hidden" name="do" value="1">
        <input type="hidden" name="typ_av_kund" value="<?if($_REQUEST['i']){?>intresserad<?}else{?>ny<?}?>">

Utställare

                        Företag *

                        <input type="text"  name="ut_foretag" style="width:90%;" value="<?if($_REQUEST['i']){echo $intresse_foretag;}else{echo $_REQUEST['ut_foretag'];}?>">

                        Namn *

                        <input type="text"  name="ut_kontakt" style="width:90%;" value="<?if($_REQUEST['i']){echo $intresse_kontakt;}else{echo $_REQUEST['ut_kontakt'];}?>">

                        E-post *

                        <input type="text"  name="ut_epost" style="width:90%;" value="<?if($_REQUEST['i']){echo $intresse_epost;}else{echo $_REQUEST['ut_epost'];}?>">

                        Telefon *

                        <input type="text"  name="ut_tel" style="width:90%;" value="<?if($_REQUEST['i']){echo $intresse_tel;}else{echo $_REQUEST['ut_tel'];}?>">

<?if($_REQUEST['h']==2){?>
                        Adress

                        <input type="text"  name="ut_adress" style="width:90%;" value="<?=$_REQUEST['ut_adress']?>">

                        Postnummer och Ort

                        <input type="text"  name="ut_postnr" style="width:22%;" value="<?=$_REQUEST['ut_postnr']?>"><input type="text"  name="ut_stad" style="width:68%;" value="<?=$_REQUEST['ut_stad']?>">

                        Land
                        <input type="text"  name="ut_land" style="width:90%;" value="<?=$_REQUEST['ut_land']?>">

                        Hemsida
                        <input type="text"  name="ut_www" style="width:90%;" value="<?=$_REQUEST['ut_www']?>">

                        Organisationsnummer
                        <input type="text"  name="ut_org" style="width:90%;" value="<?=$_REQUEST['ut_org']?>">

<?}?>
<?if($_REQUEST['h']==1){?>
                        Önskad storlek på monter (kvm)
                        <input type="text"  name="onskad_m2" style="width:90%;" value="<?=$_REQUEST['onskad_m2']?>">
<?}?>

<?if($_REQUEST['h']==2){?>

Fakturamottagare (om annan än utställare)

                        Företag

                        <input type="text"  name="fa_foretag" style="width:90%;" value="<?=$_REQUEST['fa_foretag']?>">

                        Namn

                        <input type="text"  name="fa_kontakt" style="width:90%;" value="<?=$_REQUEST['fa_kontakt']?>">

                        E-post

                        <input type="text"  name="fa_epost" style="width:90%;" value="<?=$_REQUEST['fa_epost']?>">

                        Telefon

                        <input type="text"  name="fa_tel" style="width:90%;" value="<?=$_REQUEST['fa_tel']?>">

                        Adress

                        <input type="text"  name="fa_adress" style="width:90%;" value="<?=$_REQUEST['fa_adress']?>">

                        Postnummer och Ort

                        <input type="text"  name="fa_postnr" style="width:22%;" value="<?=$_REQUEST['fa_postnr']?>"><input type="text"  name="fa_stad" style="width:68%;" value="<?=$_REQUEST['fa_stad']?>">

                        Land
                        <input type="text"  name="fa_land" style="width:90%;" value="<?=$_REQUEST['fa_land']?>">

                        Hemsida
                        <input type="text"  name="fa_www" style="width:90%;" value="<?=$_REQUEST['fa_www']?>">

                        Organisationsnummer
                        <input type="text"  name="fa_org" style="width:90%;" value="<?=$_REQUEST['fa_org']?>">

<?}?>

                    <?=$produktinfo?>
                    <textarea name="produkter" style="width:99%; height:100px;"><?=$_REQUEST['produkter']?></textarea>

    <?if($_REQUEST['h']==2){?>

Monterstorlek och priser

                        Ändra pris/m²

                        <input id="m2pris2" name="m2pris2" type="text" style="width:50px;" value="<?=$m2pris?>" />

                        Ändra grundpris

                        <input id="grundpris2" name="grundpris2" type="text" style="width:50px;" value="<?=$grundpris?>" />

                    Pris/m²

                    <input id="m2pris" name="m2pris" type="text" style="width:50px;" value="<?=$m2pris?>" disabled/>

                    Grundpris

                    <input id="grundpris" name="grundpris" type="text" style="width:50px;" value="<?=$grundpris?>" disabled/>

                                 Önskad bredd

                                 <input id="bredd" name="bredd" type="text" style="width:40px;" value="<?if($_REQUEST['bredd']){echo $_REQUEST['bredd'];}else{echo "0";}?>" /> meter

                                 Önskat djup

                                <input id="djup" name="djup" type="text" style="width:40px;" value="<?if($_REQUEST['djup']){echo $_REQUEST['djup'];}else{echo "0";}?>" /> meter

                    Antal m²

                    <input id="m2" name="m2" type="text" style="width:50px;" disabled /> m²     <input type="checkbox" name="eget_talt" value="1" <?if($_REQUEST['eget_talt']){?>checked<?}?> > Eget tält

                    Pris för ytan

                    <input id="ytpris" name="ytpris" type="text" style="width:75px;" disabled /> kr

                    Totalsumma + moms

                    <input id="totalsumma" name="totalsumma" type="text" style="background-color:#ffa; font-weight:bold; width:75px;" disabled  /> kr

Allmänna villkor

                        <?=nl2br($villkor)?>

                    <input type="checkbox" name="villkor" value="1" <?if($_REQUEST['villkor']){?>checked<?}?> > Ja! Jag godkänner Sunne Jaktmässas Allmänna villkor

    <?}?>

    <?if($hide_submit){}else{ // Om formuläret är korrekt postat så döljer vi ruta för veckodag och skicka-knappen?>

                    Dagens veckodag (för att slippa spam)

                    <input type="text" name="dag" style="background-color:#ffa; font-weight:bold; width:75px;"  value="<?=$_REQUEST['dag']?>" />

                    <input type="submit" name="b1" value="<?=$knapp?>">

    <?}?>

<input type="checkbox" name="ad11" class="add" value="<?=$ad14?>" />
<input type="checkbox" name="ad11" class="add" value="<?=$ad12?>" />
<input type="checkbox" name="ad11" class="add" value="<?=$ad11?>" />
1

    </form>

A: you are missing a ; after you initialise annonssumma
change to var annonssumma = 0;

A: i believe the error is $("#annonssumma").text(annonssumma); should be changed to
$("#annonssumma").val(annonssumma);

A: According to our long discussion, I understand that you should have additional event for checkbox changing.
I have changed your js script to the following:
$(document).ready(function(){
    window.onload = function() { calculate() }
    $('#bredd').keyup(calculate);
    $('#djup').keyup(calculate);
    $('#m2pris2').keyup(calculate);
    $('#grundpris2').keyup(calculate);
});

var annonssumma = 0;

$('input[type="checkbox"].add').change(function(){
    calculate_annonssumma();
    // You should also call calculate() function to recalculate your totalsumm when checkbox state is changed
    calculate();
});

function calculate_annonssumma(){
    $("input[type='checkbox'].add").each(function(){
        if($(this).is(":checked")){
            if(!$(this).hasClass("added")){
                annonssumma += parseInt($(this).val());
                $(this).addClass("added");
            }
        } else{ if($(this).hasClass("added")){
                    annonssumma -= parseInt($(this).val());
                    $(this).removeClass("added");
              }
        }

   }) ;
   $("#annonssumma").text(annonssumma);
}

function calculate(e) {
    var bredd = parseFloat($('#bredd').val().replace(",", "."));
    var djup = parseFloat($('#djup').val().replace(",", "."));
    $('#m2').val(bredd * djup);
    $('#grundpris').val($('#grundpris2').val());
    $('#m2pris').val($('#m2pris2').val());
    $('#ytpris').val($('#m2').val() * $('#m2pris2').val());

    $('#totalsumma').val(parseFloat($('#ytpris').val()) + parseFloat($('#grundpris2').val()) + parseFloat($('#annonssumma').text()));
}

So, You should also call calculate() function to recalculate your totalsumm when checkbox state is changed (in your change event for checkbox)
Hope it will help you to resolve your problem.
Also, here is a DEMO


text:
Q: How to send current user's(person using the app), Firebase Id token,from the Flutter app, to restapi, using http POST method? I have created an app using flutter for UI and Restapi in nodejs as the backend. Now i want to verify the user, who signuped with the firebase authentication,the sending the current user's firebase Id token. In order, to do this I am sending the id token using the HTTP Post method. But got an error.
Sample code:
        import 'package:http/http.dart' as http;

    FirebaseUser user = await FirebaseAuth.instance.currentUser();
       if(user!=null){
  Future<IdTokenResult> idtoken = user.getIdToken();
    }
 http.Response response = await http.post("https://www.something.com/something/something",
                              body:jsonEncode({
                                "name": name.text,
                                "pincode": "$pincode",
                                "token": idtoken,
                                "phone": "${widget.phoneNo}",
                              }),
                                  headers: {'Content-Type': 'application/json'},
                              );

Got Error:
     Unhandled Exception: Converting object to an encodable object failed: Instance of 'Future<IdTokenResult>'

P.S: Suggest an edit, if something wrong with the question, I am for ideas (Thanks for the help in advance :) )

A: You need token(String) not idtoken(IdTokenResult)
import 'package:http/http.dart' as http;

FirebaseUser user = await FirebaseAuth.instance.currentUser();

if(user!=null){
  IdTokenResult idtoken = await user.getIdToken();
  // get String token
  String token = idtoken.token;
}
 http.Response response = await http.post("https://www.something.com/something/something",
                              body:jsonEncode({
                                "name": name.text,
                                "pincode": "$pincode",
                                "token": token,
                                "phone": "${widget.phoneNo}",
                              }),
                                  headers: {'Content-Type': 'application/json'},
                              );

A: I think the problem is getIdToken() part.
Can you try below code please:
FirebaseAuth.instance.currentUser().then(user => {
        if (user != null) {
           user.getIdToken().then(token => {
              http.Response response = await http.post("https://www.something.com/something/something",
                              body:jsonEncode({
                                "name": name.text,
                                "pincode": "$pincode",
                                "token": token,
                                "phone": "${widget.phoneNo}",
                              }),
                                  headers: {'Content-Type': 'application/json'},
                              );
        }
});


text:
Q: Get value by key in Array Object to Array in mongodb & mongoose by query I have a question about mongodb.
I have a collection with documents:
{
    "_id" : ObjectId("5b5445b44ae5aa0c0c625378"),
    "skills" : [
        {
            "skillId" : 11,
            "level" : 10,
            "available" : 1,
            "_id" : ObjectId("5b5445b44ae5aa0c0c62537c")
        },
        {
            "skillId" : 12,
            "level" : 10,
            "available" : 1,
            "_id" : ObjectId("5b5445b44ae5aa0c0c62537b")
        },
        {
            "skillId" : 13,
            "level" : 1,
            "available" : 0,
            "_id" : ObjectId("5b5445b44ae5aa0c0c62537a")
        },
        {
            "skillId" : 14,
            "level" : 1,
            "available" : 0,
            "_id" : ObjectId("5b5445b44ae5aa0c0c625379")
        }
    ]
}

Now, I want to select all skill -> level  in this document to an array in new object with current id
Ex :
{
 "_id" : ObjectId("5b5445b44ae5aa0c0c625378"),
"skills": [10, 10,1,1]
}

Result is same as aggregate query [{$project:{  "skills": "$skills.level" }}]
but aggregate is not recommended in this case!
Can you tell me how I using find in Mongoose to do that?


text:
Q: Get correct data from input type="date" with javascript I'm trying to understand how to retrieve the date from an input type="date"
My HTML code is <input type="date" class="form-control" id="id_date" name="date" value="">
I have a JS that read when the input type change and print on the console the timestamp
const date_value = document.getElementById('id_date')
date_value.addEventListener('change', function (e){
    console.log(e)
    console.log(e.timeStamp)
    var date = new Date(e.timeStamp);

})

For some reason, I can get the actual date chosen from the input form as my function returns always the 1st Jan 1970. I know that Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC but the form should return the milliseconds from that date to the date I have selected but it won't-
Below is a screen of my output. How do I manage this data?

A: Goodday
As I can understand you just need to fetch the selected date from the input field and print it in the console.
then simply just do this...
const date_value = document.getElementById('id_date');
date_value.addEventListener('change', function (){
    console.log(date_value.value);
})

Whenever the user selects a date, the function will be called and it will console the update date value from the field.
I hope this will help you, still if you have any doubt please let me know comment below.


text:
Q: Alter table in mysql, add column error 1064 (42000)? I am trying to add column in mysql table but following error thrown.
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ALTER TABLE cm_article  ADD COLUMN active INT NOT NULL DEFAULT '0' AFTER description'
My Sql Statement is:
ALTER TABLE cm_article ADD COLUMN active INT NOT NULL DEFAULT '0' AFTER description;

A: There are two different types of quotation marks in MySQL. You need to use ` for column names and ' for strings. Since you have used ' for the filename column the query parser got confused.
ALTER TABLE `cm_article` ADD COLUMN `active` INT NOT NULL DEFAULT '0' AFTER `description` ;

A: I would do :
ALTER TABLE cm_article
ADD COLUMN active INT NOT NULL DEFAULT(0)
AFTER description;

If it doesn't work, modify 'ADD COLUMN' with just 'ADD'


text:
Q: Fake click event - jasmine I have this function
daysClick: function(e) {

    var parent = $(e.currentTarget).closest('.days');

    if (!$(parent).hasClass('disabled') && !$(parent).hasClass('readonly')) {
        $(e.currentTarget).toggleClass('selected');
    }
}

How can I test this using jasmine?
I'm not sure how to fake click event basically.

A: Have a look at uitest.js.
It allows you to incorporate event handling and other UI features into your automated Jasmine tests.
var uit = uitest.current;

describe('someSuite', function() {
    uit.url('someUrl');

    it('should do smth when clicked on the button', function() {
        uit.runs(function($) {
            $(".btn").click();
        });
    });
});


text:
Q: In dotnetcore, startup.cs, ConfigureServices, DbContext options is missing UseOracle() Where is the option for "UseOracle" ?
services.AddDbContext(options => options.useoracle()
I believe I've included the required DLL's.
Screenshot provided:
https://pasteboard.co/HuVDEfB.png
Any help is much appreciated.

A: Try this
using Oracle.EntityFrameworkCore;


text:
Q: Add content to widget title in admin area within the widget? Is it possible to add content (icon & text) to widget title in admin area and customizer based on other value from the widget?
Widgets are custom and developed by me (not WP default one)
Ideally it should work bot in admin area & customizer.
On frontend extra content is now shown.

Then user changes an option in the widget and upon the save title changes to

I've managed to achieve this with JS and .on('widget-updated widget-added') event, but looking for more robust approach as it doesn't work in customizer.

A: You can add filter for widget_title hook.
Or change the $instance['title'] on update.

A: As per my understanding I can suggest you that you can probaly use something like font-awesome. This will help you to display a image sort of thing using simple CSS class.
So you may please check my solution and let me know your views over it.

A: Let me describe every situation.

*

*If you would like to change "Search" on the above screenshot, I should disappoint you, you can look in /wp-admin/includes/widgets.php (line 232) and in any widget class (I opened /wp-includes/widgets/class-wp-widget-search.php) and you will find out that there are no filter hooks for it. It could be changed only in your custom widgets.

On my custom widget I change it in this part of the widget class code:
    function __construct() {
         parent::__construct(
            'misha_widget',
            'Widget title', // here it is
            array( 'description' => 'Widget description' )
        );
    }

*If you would like to change "My search" on widget in admin area, JavaScript is good enough way to do it because WordPress also do it with JS. The widget_title hook will be applied only for website appearance not for admin area or customizer:
add_filter('widget_title', 'misha_change_title1', 10, 3 );
function misha_change_title1( $title, $instance, $id ){
    if( $id == 'search' ) {
        return ''. $title;
    }
    return $title;
}

What about customizer, you can find the instruction how to run custom JS code here https://codex.wordpress.org/Theme_Customization_API#Step_2:_Create_a_JavaScript_File


text:
Q: Trigger materialize.css toast on document load I'm trying to trigger a toast when the the page load using materialize.css and jquery, but it's now working, here my code:
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
<script>
    $(document).ready(function(){
       Materialize.toast('I am a toast!', 4000);
    });
</script>

This code is inside head tags.

A: Seems like you're missing Materialize js file. For me, your code is properly working.
Just add this to your head as well.
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/js/materialize.js"></script>

Demo


text:
Q: All subgroups of index 2 Can we construct examples of non-abelian groups G (finite or infinite) such that for all of it's non-trivial subgroups has index 2 in G?.

A: Here is another way to prove that in the finite case $G$ has to be abelian: apparently $G$ has even order, whence a Sylow 2-subgroup $S$ is non-trivial. Assume $S \lt G$. Then by the condition it has index $2$, which is impossible, since for the Sylow group $S$, index$[G:S]$ is odd. Hence $G=S$, so $G$ is a 2-group. But then its center $Z(G)$ is non-trivial and has index $2$. So $G/Z(G)$ is cyclic and that implies $G$ is abelian. Further, it is then easy to see that $G \cong C_4$ or $C_2 \times C_2$, the Klein 4-group.Observation: if $G$ is infinite non-abelian with every non-trivial subgroup having index $2$, then the only subgroups are the trivial ones, $G$ and $\{1\}$. For suppose $H$ is a subgroup, with $H \gt 1$, so index$[G:H]=2$. Pick an $x \in H-\{1\}$, then $\langle x \rangle \subseteq H$, and also index$[G:\langle x \rangle]=2$. Hence $H=\langle x \rangle$. Since $G$ is infinite, $\langle x^2 \rangle$ cannot be trivial (otherwise $x$ would have finite order $2$ and $G$ would be finite). So $\langle x \rangle=\langle x^2 \rangle$. Hence $x=x^{2n}$ for some integer $n$, and this implies that $x$ has finite order after all, a contradiction. We conclude that $G=H$. So $G$ has only two subgroups and this means $G \cong \mathbb{Z}$, which is abelian, a contradiction. So the infinite case is refuted.

A: Not of finite order. Suppose $G$ has subgroup of index 2. Then order of $G$ is even, as it's a union of two cosets of such subgroup. By Cauchy's Theorem, $G$ has member of order two.  If $|G|>4$, index of the subgroup generated by this element is greater than 2. If $G$ has no subgroups at all, it is cyclic (of prime order), hence abelian.
Will think about general case.


text:
Q: Very slow subqueries when using "NOT IN" I'm working on generating reports for data contained within a large pre-existing Access database (~500 mb after compact & repair), and I'm having trouble with a slow subquery.
The database has a big table which contains a record of every customer purchase. Here's a simple query which finds customers who have bought a blue widget. It completes within a few seconds and returns about ten thousand records.
SELECT DISTINCT CustomerId
FROM ProductSales
WHERE Product = 'BLUE'

Here's a query which tries to find customers who have bought a blue widget, but not a red widget. It takes about an hour to run.
SELECT DISTINCT CustomerId FROM ProductSales
WHERE Product = 'BLUE'
AND CustomerId NOT IN (
    SELECT CustomerId
    FROM ProductSales
    WHERE Product = 'RED'
)

Is there a way to refactor the second query to make it take a few minutes instead of an hour?

A: Access' database engine can't use an index for Not In, so it's bound to be slow.  With an index on CustomerId, this query should be much faster because the db engine can use the index.
SELECT DISTINCT blue.CustomerId
FROM
    ProductSales AS blue
    LEFT JOIN
        (
            SELECT CustomerId
            FROM ProductSales
            WHERE Product = 'RED'
        ) AS red
    ON blue.CustomerId = red.CustomerId
WHERE
        blue.Product = 'BLUE'
    AND red.CustomerId Is Null;

You could probably also try a Not Exists approach, but index use there is not guaranteed.  Also, please see the comment below from David Fenton which discusses performance impact in more detail.

A: Add an index, of course, if you don't have one.  If that's a problem, it's probably just that there are lots of customers with orders for something other than RED but not so many with BLUE; this (untested) query tries to fix that.
SELECT DISTINCT CustomerId FROM ProductSales
LEFT JOIN (
  SELECT DISTINCT CustomerId cid FROM ProductSales
  LEFT JOIN (
    SELECT DISTINCT CustomerId
    FROM ProductSales
    WHERE Product = 'BLUE'
  ) foo ON CustomerId = cid
  WHERE Product = 'RED'
) bar USING (CustomerId)
WHERE cid IS NULL


text:
Q: join() argument must be str, bytes, or os.PathLike object, not 'dict' Проблема: при открытии любой из категорий у меня ошибка которая в заголовке.
У меня есть страница с категориями:

Electronics

Cars

Sports

Food

Accessories

Books

Функция:
@login_required(login_url='/login')
def categor(request, cat):
    cat_list = Listing.objects.filter(category=cat)
    empty = False
    if len(cat_list) == 0:
        empty: True
    return render("auctions/incateg.html", {
        "cat": cat,
        "empty": empty,
        "items": cat_list
    })

И цикл в incateg.html который должен показать все итемы в категории которая открыта:
{% for item in items_list reversed %}
          {% if item.categor == cat %}
          {% endif %}
            {% if empty %}

There is no avaliable listings in this category

            {% endif }
{% endfor %}

A: Первым параметром в render должен передаваться request, вторым - путь к шаблону, третьим - данные (контекст), см. документацию. Вы request не передаете, получается путь к шаблону передается вместо request, а данные для шаблона вместо пути шаблона.
Другие проблемы в коде, которые я вижу:

*

*В словаре есть ключ items, но нет items_list, который указан в шаблоне.

*empty: True никак не модифицирует переменной empty, нужно заменить на присваивание empty = True.

*У объектов в вашем списке, насколько я понимаю, есть поле category (судя по имени параметра, используемому при фильтрации), а в шаблоне проверяется поле categor.

*По логике проверять значение empty в шаблоне нужно вне цикла, т.е. сделать, чтобы for был вложен в if, а не наоборот (как сейчас). Сейчас у вас при пустом списке for ни разу не выполнится, и
There is no avaliable listings in this category
 не отобразится.


text:
Q: RMI bind object to Registry and access from Client I am struggling with accessing a Remote Object from my Registry. I don't quite get how to access a binded object at the client. What i did is:
// export for RMI
IRemote remoteObject = new RemoteObject();
IRemote stub = (IRemote) UnicastRemoteObject.exportObject(remoteObject, 0);

// bind to registry so clients can find it
Registry registry = LocateRegistry.createRegistry(port); registry.bind(bindingName, stub);

A: RMI
// Server
// export for RMI
IRemote remoteObject = new RemoteObject();
IRemote stub = (IRemote) UnicastRemoteObject.exportObject(remoteObject, 0);

// bind to registry so clients can find it
Registry registry = LocateRegistry.createRegistry(port);
registry.bind(bindingName, stub);

// unexport
UnicastRemoteObject.unexportObject(remoteObject, true);

// Client
// lookup remote object on server
Registry registry = LocateRegistry.getRegistry(host, port);
IRemote remoteObject = (IRemote) registry.lookup(name);


text:
Q: How to cleanup the graphite whisper's data? I want to delete the graphite's storage whisper's data but there ain't anything in the graphite docs.
One way I did is deleting the the files at /opt/graphite...../whispers/stats... manually.
But this is tedious, so how do I do it?

A: As people have pointed out, removing the files is the way to go.  Expanding on previous answers, I made this script that removes any file that has exceeded its max retention age.  Run it as a cronjob fairly regularly.
#!/bin/bash
d=$1
now=$(date +%s)

MINRET=86400

if [ -z "$d" ]; then
  echo "Must specify a directory to clean" >&2
  exit 1
fi

find $d -name '*.wsp' | while read w; do
  age=$((now - $(stat -c '%Y' "$w")))
  if [ $age -gt $MINRET ]; then
    retention=$(whisper-info.py $w maxRetention)
    if [ $age -gt $retention ]; then
      echo "Removing $w ($age > $retention)"
      rm $w
    fi
  fi
done

find $d -empty -type d -delete

A couple of bits to be aware of - the whisper-info call is quite heavyweight.   To reduce the number of calls to it I've put the MINRET constant in, so that no file will be considered for deletion until it is 1 day old (24*60*60 seconds) - adjust to fit your needs.  There are probably other things that can be done to shard the job or generally improve its efficiency, but I haven't had need to as yet.

A: Currently, deleting files from /opt/graphite/storage/whisper/ is the correct way to clean up whisper data.
As for the tedious side of the process, you could use the find command if there is a certain pattern that your trying to remove.

find /opt/graphite/storage/whisper -name loadavg.wsp -delete

Similar Question on answers.launchpad.net/graphite

A: I suppose that this is going into Server Fault territory, but I added
the following cron job to delete old metrics of ours that haven't been
written to for over 30 days (e.g. of cloud instances that have been
disposed):

find /mnt/graphite/storage -mtime +30 | grep -E \
"/mnt/graphite/storage/whisper/collectd/app_name/[^/]*" -o \
| uniq | xargs rm -rf

This will delete directories which have valid data.
First:
find whisperDir -mtime +30 -type f | xargs rm

And then delete empty dirs
find . -type d -empty | xargs rmdir

This last step should be repeated, because may be new empty directories will be left.


text:
Q: Actual difference between UIAccessibilityLayoutChangedNotification and UIAccessibilityScreenChangedNotification? I'm trying to ascertain what exactly happens differently when posting a UIAccessibilityLayoutChangedNotification, and a UIAccessibilityScreenChangedNotification. From what I can see, I can use them interchangeably everywhere and nothing different happens.
The Apple documentation simply says to use LayoutChanged when (for example) an element has been hidden or shown, and to use ScreenChanged if the entire screen changes, but I'm interested in what THEY do when I provide this information, and what I should see differently when using one or the other.
Can anyone give a clear explanation of implementation differences between the two?

A: These two notifications are for dynamic content on views, and communicating these changes to VoiceOver for screenreader users.  There is little difference between these two notifications, except for their default behavior, and the silly little "boop beep" for ScreenChange notifications.
In both instances, the argument
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, arg);

Represents a string to be read out, or an on screen element, which VoiceOver will shift its focus to.  In the event of dramatic context changes, it is important to send focus to a place that makes sense, or announce that such changes have taken place.  Either approach is acceptable from an accessibility point of view, though I prefer approaches that involve the least amount of change possible.  In the event of simple layout changes, it is almost always best just to announce the context change, and leave focus where it was.  Though sometimes, the element that caused the context change is hidden, and then it is clearly necessary to direct voiceover to highlight new content, because the default behavior in this case is undefined, or perhaps deterministic, but determined by a framework that knows absolutely nothing about your app!
The difference between the two events, given that they both do exactly the same thing, is in their default behavior.  If you supply nil to the UIAccessibilityLayoutChangedNotification it is as if you have done nothing.  If you supply a nil argument to the UIAccessibilityScreenChangedNotification it will send focus to the first UIObject in your view hierarchy that is marked as an accessibilityElement, once all view hierarchy changes and drawings are complete.
UIAccessibilityLayoutChangedNotification
A good use case example for UIAccessibilityLayoutChangedNotification is for dynamic forms.  You want to let users know that, based on decisions they've made in the form, new options are available.  For example, if in a form you select that you are a Veteran, additional areas of the form may pop up to provide more input, but these areas may have been hidden to other users who did not care about them.  So you could shift focus to these elements after user interaction:
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, firstNewFormElement);

Which would shift focus to the provided element, and announce it's accessibilityLabel.
Or just tell them that the new form elements are there:
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, @"Veterans form elements available");

Which would leave focus where it is, but VoiceOver would announce "Veterans form elements available".
Note: This particular behavior is bugged on my iPad (8.1.2).
Or finally you could do this:
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil);

Which does absolutely nothing :).  Seriously, I don't even think the a11y framework backend cares.  This particular line of code is a complete waste!
UIAccessibilityScreenChangedNotification
A good use case example for the UIAccessibilityScreenChangedNotification is customized tabbed browsing situations.  When the entire screen, with the exception of your navigation area, changes.  You want to let voiceover know that essentially the entire screen changed, but NOT to focus the first element (your first tab) but to focus the first content element.
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, firstNonGlobalNavElement);

Which would play the "boop beep" sound and then shift focus to just beneath your global navigation bar.  Or you could do this:
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, @"You're on a new tab");

Which would wait for the new tab to load, play the "beep boop" sound, announce "You're on a new tab" in voiceover, then shift focus to the first element on the screen, then announce the accessibilityLabel for that element. (PHEW! That's a lot!  This is jarring for screen reader users.  Avoid this scenario, unless absolutely necessary).
And finally you can of course do this:
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil);

Which is equivalent to:
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, firstA11yElement);

Both of which will play the "beep boop" sound, shift VoiceOver focus to the first element on the screen, and then announce it.
Finally
In a comment somebody mentioned caching, and I occasionally comment in my answer about things the A11y Backend may or may not care about.  While it is certainly possible that there is some backend magic happening, I don't believe in either of these circumstances, the back end cares at all.  The reason I say this is because:
If you've ever used the UIAccessibilityContainer protocol, you can watch as your container of views gets queried.  There is no caching going on.  Even the accessibilityElementCount property gets pinged each time VoiceOver changes focus to a new AccessibilityElement within your container.  Then it goes through the process of checking which element it is on, asking for the next element, and so on.  It is designed at its core to handle dynamic situations.  If you were to insert a new element into your container after interaction, it would still go through all of these queries and be just fine about it!  Furthermore, if you override the properties of the UIAccessibility protocol, in order to provide dynamic hints and labels, you can also see that these functions get called every time!  As such, I believe that the A11y Framework backend gleans ABSOLUTELY ZERO information from these notifications.  The only information VoiceOver needs to do its job is it's currently focused Accessibility Element, and this elements Accessibility Container.  The notifications are simply there for you to make your app more usable for VoiceOver users.
Imagine if this weren't the case how many times Safari would post these notifications!!!! :)
These particular statements can only be confirmed by someone with backend knowledge of the framework, who works with the code, and should be viewed as conjecture.  It could be the case that this is highly version/implementation dependent.  Definitely open to discussion on these points!  The rest of this post is pretty concrete.
For Your Reference
Most of this comes from experience working with the frameworks, but here is a useful reference if you wish to dig further.
https://developer.apple.com/documentation/uikit/accessibility/uiaccessibility
https://developer.apple.com/documentation/uikit/uiaccessibilitylayoutchangednotification
https://developer.apple.com/documentation/uikit/uiaccessibilityscreenchangednotification
And finally, an open source repo of the silly little app I put together to test all this stuff.
https://github.com/chriscm2006/IOS-A11y-Api-Test

A: UIAccessibilityScreenChangedNotification is to indicate that the whole screen has changed and VoiceOver should reset.
UIAccessibilityLayoutChangedNotification is to indicate that one or more, but not all, elements on the screen have changed.
when your UI changes dramatically. Usually when a user moves into a different part of your app (navigates to a different screen). VoiceOver notifies the user with a tone, and it clears its caches and does other preparations to deal with a new set of accessibility data. It alerts VoiceOver that the screen has changed and there may be new elements on the screen so VoiceOver will rebuild it's index of accessibility elements.
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil);

If some part of your UI changes, but the user hasn't necessarily jumped to an entirely different part of your app. (Example: in the iTunes Store app, tapping on the price label ($0.99, etc.) next to a song changes it to a "Buy" button.) This notification tells VoiceOver to re-read the current state of all accessible items that are on-screen, and by doing this it figures out what has changed and informs the user of those changes. It alerts VoiceOver that the layout has changed and that it's current index is out of date because the items on the screen have reordered themselves.
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil);


text:
Q: Homogeneity of a function within a region I have 2 functions;
funtion 1:
ctr = {(Exp[Pi*0.5] + 1)/2, 0};
radius = (Exp[Pi*0.5] - 1)/2;
pp = PolarPlot[
  Evaluate@Table[Exp[(t + 2*Pi*i/120)*0.5], {i, 1, 120}], {t, -Pi,
   Pi}, RegionFunction -> (Norm[{#, #2} - ctr] <= radius &)]
Total[ArcLength /@ Cases[pp, _Line, All]]

and function 2:
ctr = {(Exp[Pi*0.5] - 1)/2, 0};
radius = (Exp[Pi*0.5] - 1)/2;
pp2 = ParametricPlot[
  Evaluate[Table[{t, t (Tan[2 j Pi / 120])}, {j, 1, 60}]], {t, -5, 5},
   RegionFunction -> (Norm[{#, #2} - ctr] <= radius &),
  PlotRange -> All]
Total[ArcLength /@ Cases[pp2, _Line, All]]

I want to show that function 1 is distributed within the circle more homogeneously than function 2 as it is inferred by the graphs. It is clearly seen that function 1 is more homogeneous but I need to support it by the data. How can I show it in mathematica?
Maybe, the area between the lines in the intersection circle give me what I want as below:

I can show that the maximum missing spaces between the lines are less in function 1.


text:
Q: Why do we ignore the proton when computing relativistic correction in the Hydrogen atom? I have read a number of textbooks (e.g. Sakurai), and they all seem to say that the unperturbed Hamiltonian of hydrogen is:
$$
H_0 = \frac{p^2 }{2m_e} - \frac{e^2}{r} \tag{1}
$$
and the relativistic correction is given by:
$$
T = \sqrt{p^2c^2 + m_e^2c^4} - m_e c^2 \approx \frac{p^2}{2m_e} - \frac{p^4}{8m_ec^3}
$$
and hence the perturbed Hamiltonian is:
$$
H = H_0 + H_p
$$
where $H_p$ is the perturbation given by:
$$
H_p = - \frac{p^4}{8m_ec^3}.
$$
I really cannot bring myself to agree with (1), isn't the Hamiltonian of the unperturbed hydrogen:
$$
H_0 = \frac{p^2 }{2\mu} + \frac{e^2}{r} \tag{2}
$$
where $\mu$ is the reduced mass, and thus the perturbation should be:
$$
H_p = - \frac{p^4}{8 \mu c^3}.
$$
Why are the textbooks ignoring the mass of the proton? My guess is that they are doing an approximation, but is this approximation really valid?

A: Well, the difference between $m_e$ and $\mu$ is really small, so I suspect most places just assume $\mu \approx m_e$.
Remember, since the electron is around a 1000 times less massive than the proton, $$\frac{\mu}{m_e} = \frac{m_p}{m_p+m_e} \approx 0.9995,$$ which is pretty darn close to 1! :)
EDIT: @EmilioPisanty has brought up an important point that I didn't consider: while the correction due to the mass of the proton is tiny, the relativistic correction is even tinier. (1 part in $10^7$, as pointed out.) As a result, it doesn't make sense to speak of the perturbed Hamiltonian as
$$\hat{H} = \frac{\hat{p}^2}{2 m_e} + V(r) - \frac{\hat{p}^4}{8 m_e^3 c^2},$$ since we're ignoring a term of the order $\sim 10^{-3}$ but considering one of the order $\sim 10^{-7}$. When taking the relativistic corrections into account, the correct method would be to use the reduced mass $\mu$ everywhere to avoid this.
However, practically, it doesn't seem to be a problem since (at least to first order) the shift in energy due to this perturbation depends on the mass only through $E_n$:
$$\Delta E_{nlm} = E_n \frac{\alpha^2}{n^2}\left( \frac{n}{l + 1/2} -\frac{3}{4}\right),$$
where $\alpha = \frac{e^2}{4\pi\epsilon_0 \hbar c} \approx \frac{1}{137}$ is the fine-structure constant, and $n,l,m$ represent the usual quantum numbers.

EDIT: An interesting side-note is that it is important to consider $\mu$ when we're dealing with "hydrogen-like" systems where one of the masses isn't so much larger than the other. One example is for positronium, a system consisting of an electron and a positron. If you used the "naive" Hamiltonian given above with $m_e$ instead of $\mu$, you might think that the energy spectrum of positronium is the same as that of the Hydrogen atom, but it isn't! In fact, since in this case $\mu = m_e/2$, the frequencies of the spectral lines are less than half of those for the corresponding Hydrogen lines.


text:
Q: Qual o ciclo de vida de uma requisição HTTP nos padrões MVC? Eu desenvolvo em ASP.NET MVC5 já faz 1 ano e 2 meses, e até hoje não consegui entender direito quem chama quem.
Pesquisando mais, encontrei essa resposta que diz(em tradução livre):

Ciclo de vida de uma requisição HTTP:
O usuário faz a requisição HTTP;
O controller intercepta;
O controller chama o serviço apropriado;
O serviço chama o DAO apropriado que retorna algum dado persistente(por exemplo);
O serviço trata o dado e retorna para o controller;
O controller guarda os dados no model e chama a view;
A view popula com os dados do model e returna a requisição HTTP.

O que seria esse serviço ? Atualmente eu chamo classes estáticas que fazem o processamento, guarda e recupera dados do banco, isso seria a mesma coisa que esses serviços?

A: Serviço é uma das 3 camadas da aplicação
A pergunta que você postou como referência para a sua pergunta, chama de "serviço" a camada intermediária da aplicação. Essa camada intermediária é descrita dentro de uma arquitetura de 3 camadas (dados, serviços, apresentação), onde a camada de serviço teria o código que faz acesso à camada de dados, aplica regras de negócio e retorna para a camada de apresentação exibir ao usuário.
A resposta coloca o MVC dentro da camada de apresentação. A chamada feita ao controller, passa à camada de serviço que chama a camada de dados (DAO), faz um tratamento com esses dados e aplica regras de negócio, e retorna para continuar e ser direcionada para a View, onde seria formatada (HTML) para apresentação ao usuário.
Essa separação de camadas é uma separação lógica dentro do sistema, porém é possível ter uma implementação onde a camada de serviço tivesse que ser acessada através de uma chamada a uma API que reside em outra máquina e após o retorno enviar os dados recebidos para a View.