text:
Q: Approximate a function using another function Problem
Find the best approximation of $f(t)=t^2$ with $h(t)=ae^t+be^{2t}+c$ everywhere on the interval $[0,4]$.
Attempt
I know how to solve this problem given sample points, by using least squares, but I am having a hard time figuring out how to setup this problem. I know that I need to use the inner product, $\int_0^4f(t)h(t)dt$. The issue I'm having is with putting this problem in the form of $Ax=b$. Normally I would construct the Gram matrix using the inner product and basis vectors, but no basis vectors were given.
How do I proceed with setting this up?

A: You are asked to approximate $f$ by functions in the form of $h$, so you are already given three basis "vectors" $e^t, e^{2t}$ and $1$ in the function space endowed with an inner product $\langle p,q\rangle = \int_0^4 p(t)q(t)dt$. Since $1, e^t, e^{2t}$ do not form an orthonormal basis, you should first apply the Gram-Schmidt process to find an orthonormal basis $\{g_1,g_2,g_3\}$ for the function space spanned by $1, e^t, e^{2t}$. Then the required approximation is just the projection of $f$ into $\operatorname{span}\{g_1,g_2,g_3\}$, i.e. $\langle f,g_1\rangle g_1+\langle f,g_2\rangle g_2+\langle f,g_3\rangle g_3$.


text:
Q: Significant factor in 2-way repeated ANOVA becomes not significant in 3-way repeated ANOVA? My research design is 2(Ear) x 3(Factor A) x 3(Factor B) with repeated measures on all factors. For 2 way-repeated ANOVA, I used laterality index (normal distribution, calculated from % of responses from both ears) as dependent variable (DV) while Factor A and B are independent variables (IV). I obtained significant main and interaction effects.
However, when I tried 3-way repeated ANOVA using % scores from each ear as DV, factor B becomes not significant. I'm not sure what could be wrong?

*

*Is it because the % scores in one of the conditions were not normally distributed with p=0.041? The box plot looks alright but histogram has an inverted bell curve shape. I've tried log, square root and 1/x transformation but didn't work. Is it acceptable to run ANOVA since there's no equivalent non-parametric test in SPSS?

*Could it be the way I run the test in SPSS? I followed exactly the same way as I did for 2-way repeated ANOVA because I couldn't find any examples similar to my research design. Most examples have a third between subject factor while mine are all within subject factors.
I'd really appreciate any help or suggestions because I'm confused and new with statistics.
Many thanks.
Kaye

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to integrate swagger with my express application Always I used to share my node side services to some other teams with proper documentation. Based on this documentation, they will use my services.
Regarding this, when I spoke with some other guy. He suggested me to use swagger. But I don't have any idea how to integrate to my application.
My application written in Express. I have did search on this in google, I didn't find any good tutorial. If anyone already implements, can you suggest me. Which module is good and how.
Also just curious to know, are they any other libraries like swagger, which supports Node platform.
Thanks

A: I have experience with documenting an Express API using an express module (swagger-node-express).  I also have experience with documenting an Express API using manual Swagger JSON docs.
I would recommend not tying yourself down to a module for your Swagger docs.  Most of the modules (and especially swagger-node-express) force you to write your Express code differently to handle the documentation.  When manually writing your Swagger docs with JSON, you are able to write Express and decouple the documentation from your routing.
Use Swagger UI to style your documentation and add it to your web page.
Here are some resources you can use when starting out:
Swagger Editor - edit your swagger docs and see your changes live update
Swagger Docs - Swagger specs for JSON
Tutorial - This uses an older version of Swagger, be sure to check out Migrating Swagger to upgrade to the newest version
Also, take a look at this answer explaining the difference between manual and module-based swagger doc generation -> HERE.

A: I have recently come across implementing API documentation using swagger. I have used "swagger-ui-express" npm module to implement it.
Created JSON at runtime i.e., once server starts running, I captured data and modified according to the swagger specifications like below file.
https://editor.swagger.io/ Here you can see the swagger specifications in JSON.
Require the "swagger-ui-express" module, create a JSON and feed the file to swaggerui as below.
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

A: I am not completely clear on what your asking but I think you're looking for something like this: swagger-tools
I use this module and it has been great. It exposes some middleware which you can bind to the Express app that you create. For example, if you have your service documented and that documentation is Swagger compliant, then you can pass that document to the middleware. The middleware does some wonderful things like wiring up request handlers based on the definitions that are found in your documentation and validating requests against definitions found in your documentation.
It has a great tutorial and it is super easy to get setup. I hope this helps and is along the lines of what you were looking for.

A: I use swagger like this because it gives me live docs automatically on my express apps:

*

*API specification: I document my code using OpenAPI (Swagger) specification in YAML format. This is accomplished thanks to swagger-jsdoc.

*Live docs: swagger-ui-express "adds middleware to your express app to serve the Swagger UI bound to your Swagger document. This acts as living documentation for your API hosted from within your app."
Then it's just matter of creating the route where you want your docs to live:
const swaggerSpec = swaggerJSDoc({
  swaggerDefinition: {
    info: {
      title: 'My App API',
      version: '1.0.0'
    }
  },
  apis: ['./routes/index.js']
});

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

See how swagger-ui-express han built-in support for swagger-jsdoc. Read swagger-ui-express and swagger-jsdocs getting started documentation for more info.
API specification example:
Taken from the swagger-jsdocs getting started documentation.
/**
 * @swagger
 * /login:
 *   post:
 *     description: Login to the application
 *     produces:
 *       - application/json
 *     parameters:
 *       - name: username
 *         description: Username to use for login.
 *         in: formData
 *         required: true
 *         type: string
 *       - name: password
 *         description: User's password.
 *         in: formData
 *         required: true
 *         type: string
 *     responses:
 *       200:
 *         description: login
 */
app.post('/login', function(req, res) {
  res.json(req.body);
});

Generated docs example:
They would look almost like the Swagger UI example.

A: I think you are looking for this:
OpenAPI (Swagger) specification generator for ExpressJS applications
https://github.com/mpashkovskiy/express-oas-generator
To make it work, you need to do the following:
1) Install the library: npm i express-oas-generator —save
2) Integrate with ExpressJS:
const express = require('express')
const expressOasGenerator = require('express-oas-generator')

expressOasGenerator.init(app, {});

3) Open the following URL: http://localhost:3000/api-docs  (replace localhost:3000 with your hostname)
It will generate a very nice Swagger output right from the registered routes:


text:
Q: Change loading image? I want to have my loading image be different each time i start the app. Is there a way to change this to something else once the app's started?

A: Not technically, no. The startup images are located inside the application bundle - as part of iOS's sandboxing, applications can't change or modify files inside that bundle (so your Info.plist and your background images).
It would be possible to have your startup image be black, and then swap it out for another splash screen that you hold for a few seconds as soon as your applicationDidFinishLoading method is called - but remember this will degrade the user experience, since you'll be delaying the time it takes to get into the app.


text:
Q: Error OpenCV en transmision web con flask Soy nuevo con Opencv. Es un error un poco raro porque al princio funciona bien, luego de unos segundos es que deja de funcionar.
El error es:
Debugging middleware caught exception in streamed response at a point where response headers were already sent.
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/werkzeug/wsgi.py", line 870, in __next__
    return self._next()
  File "/usr/lib/python3/dist-packages/werkzeug/wrappers.py", line 82, in _iter_encoded
    for item in iterable:
  File "/home/pi/Desktop/facial/app.py", line 227, in gen
    ret, buffer = cv2.imencode('.jpg', image)
cv2.error: OpenCV(4.5.1) /tmp/pip-wheel-qd18ncao/opencv-python/opencv/modules/imgcodecs/src/loadsave.cpp:934: error: (-215:Assertion failed) !image.empty() in function 'imencode'

Este enlace muestra como hacer que una camara se transmita con opencv via Flask: https://manivannan-ai.medium.com/live-webcam-flask-opencv-python-26a61fee831
Aqui el codigo:
from flask import Flask, Response
import cv2
app = Flask(__name__)
video = cv2.VideoCapture(id) #RECIBE LA ID

@app.route('/')
def index():
    return "Default Message"
def gen(video):
    while True:
        success, image = video.read()
        ret, jpeg = cv2.imencode('.jpg', image)
        frame = jpeg.tobytes()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
@app.route('/video_feed')
def video_feed():
    global video
    return Response(gen(video),
                    mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=2204, threaded=True)

Se queda frisada con una imagen luego del error.


text:
Q: Cannot exactly center hyperlinks in home page. (HTML / CSS) As per the image in the link, I am trying to exactly center the hyperlinks that will be used as navigation. However the links are always appearing slightly off center to the left. Below is my code for reference.
I would appreciate any help with this. Thanks in advance.
The image shows how the hyperlinks are slightly off center

.title {
    background-color: #1a1a1a;
    border-top-style: solid;
    border-top-width: 10px;
    border-top-color: #1a1a1a;
    border-bottom-style: solid;
    border-bottom-width: 2px;
    border-bottom-color: #1a1a1a;
    text-align: center;
    color: #e6e6e6;
    margin-top: 0px;
    margin-bottom: 0px;
    margin-left: auto;
    margin-right: auto;
    width: 100%;
    padding-top: 2px;
    padding-bottom: 6px;
}

.page-links-container {
    background-color: #1a1a1a;
    text-align: center;
    border-top-style: solid;
    border-top-width: 2px;
    border-top-color: #e6e6e6;
    border-bottom-style: solid;
    border-bottom-width: 2px;
    border-bottom-color: #e6e6e6;
}

.page-links-item {
    color: #e6e6e6;
    display:inline;
    margin-left: auto;
    margin-right: auto;
    width: 100%;
}

.title-image {
    height: 400px;
    width: 1450px;
    margin: 0px;
    padding-top: 10px;
    padding-bottom: 10px;
}

.title-image-container {
    background-color: #1a1a1a;
    text-align: center;
}

.main {
    padding: 0px;
    margin: 0px;
}
<!DOCTYPE html>

        <title>Tropical Rainforests | Home</title>
        <link href="assets/styles/styles.css" rel="stylesheet" type="text/css">

Tropical Rainforests Trust

Home

History

Education

Community

About Rainforests

Visitor Information

Get involved

Adopt an animal


text:
Q: How do I open the Recovery Console for Windows XP? I'm running BootCamp on my mac but the MBR needs fixing and I get this when I put in the XP disc:

A screen should appear giving me the Install or Repair option, but the Repair option is missing. It wants me to format everything before I start. How can I access the Recovery Console in this situation?

A: You are upfront for one extra step. At the previous step, press R to enter the recovery console, not ENTER to enter Windows XP setup page. Please reboot and try again.


text:
Q: Why Visual Studio doesn't install vcvarsall.bat and DIA SDK I'm using Windows10. I have downloaded Visual Studio Community 2015 with Update 3
from here. I've selected C++ Common Tools as shown in this answer. And they are indeed installed as I can see the system variable
%VS140COMNTOOLS%

pointing to
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\

But the vcvarsall.bat is missing in VC directory as well as bin folder. How can I get this file and other required?
Also, DIA SDK is missing. How can I get this one?

A: For those with Visual Studio 2017:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build


text:
Q: NHibernate context sessions, ASP.NET & threading hodgepodge NHibernate.Context.WebSessionContext, otherwise known as web session context, plays nicely with ASP.NET, but only up to a point. As soon as I spin up a new thread, it is no longer able to retrieve current session from a HttpContext since there's actually no HttpContext for the said thread.
How do you make all this play nicely together?

A: Implement a hybrid session context. See my answer to this question.

A: NHibernate sessions are not thread-safe, so it might be a better idea to start a new session in your thread.


text:
Q: After upgrading Libreoffice to 5.3.1.2, previous working extensions results in error The read text extension was working fine until I upgraded to Version: 5.3.1.2. After upgrading it shows error message
"BASIC syntax error. Expected: )."
Any work around or shall I downgrade? My OS is Ubuntu 16.10
Edit:
Just found that the bug is already reported, see tdf#106529


text:
Q: Model binding for the multiple partial views in dotnet core I want to design common model binding using one common partial view and other multiple partial views based on the model type with different model binding.
I have one base Dialog Model and two derived models.
public class DialogModel
{
    public int DialogType { get; set; }

    public string ViewName { get; set; }
}

public class DialogModel1: DialogModel
{

}

public class DialogModel2: DialogModel
{

}

I have one action method and I am posting JSON data based on model type.
public IActionResult OpenDialog(DialogModel model)
    {
        string view = string.Empty;
        switch (model.DialogType)
        {
            case 1:
                model.View = "MyDialogPartialView1";

                DialogModel1 model1 = (DialogModel1)model;
                //mode1 properties set;

                view = this.RenderViewAsync("CommonDialogPartialView", model1, true).Result;

                break;
            case 2:
                model.View = "MyDialogPartialView2";

                DialogModel2 model2 = (DialogModel2)model;
                //mode2 properties set;

                view = this.RenderViewAsync("CommonDialogPartialView", model2, true).Result;

                break;
            default:
                break;
        }

        return new JsonResult(new { view });
    }

I am setting the view name of partial view based on dialog type and casting into the related model and rendering the common partial view "CommonDialogPartialView" and returning the response text.
I am appending this response text in the client-side.
My common partial view HTML.
    @model ChurchPharmacy3.Models.DialogModel

@Model.Title

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                ×
            </button>

            @await Html.PartialAsync(Model.View)

            <button type="button" class="btn btn-secondary">Cancel</button>

            <button type="button" class="btn btn-primary">Ok</button>

This common partial view getting model of DialogModel and I am rendering another partial view from the common partial view based on view name.
here is my partial view for Dialog type 1.
 @model ChurchPharmacy3.Models.DialogModel1

and same for the partial view for Dialog type 2.
@model ChurchPharmacy3.Models.DialogModel2

When I am casting the model into DialogModel1 or DialogModel2, it throws an exception.

A: I have used IModelBinder and able to fix the above issue.
Here is the solution for the above issue.
public class DialogModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
            throw new ArgumentNullException(nameof(bindingContext));

        JObject jObject = null;
        using (StreamReader reader = new StreamReader(bindingContext.ActionContext.HttpContext.Request.Body))
        {
            using (var jsonReader = new JsonTextReader(reader))
            {
                jObject = JObject.LoadAsync(jsonReader).Result;
            }
        }
        var modelType = (int)jObject.SelectToken("dialogType");

        if (modelType == (byte)DialogType.Dialog1)
        {
            var obj = DeserializeObject<Dialog1>(jObject.ToString());
            bindingContext.Result = ModelBindingResult.Success(obj);
        }
        if (modelType == (byte)DialogType.Dialog1)
        {
            var obj = DeserializeObject<Dialog2>(jObject.ToString());
            bindingContext.Result = ModelBindingResult.Success(obj);
        }
        else
        {
            var obj = DeserializeObject<DialogModel>(jObject.ToString());
            bindingContext.Result = ModelBindingResult.Success(obj);
        }

        return Task.CompletedTask;
    }

    private static T DeserializeObject<T>(string json)
    {
        return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json, new Newtonsoft.Json.JsonSerializerSettings
        {
            TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto
        });
    }

}


text:
Q: When to use a connection pool to MySQL in python? I have a service that runs and executes at most 5-8 threads at the same time. The main thread creates a connection pool and allows the subsequent threads it spawns to get a connection from this.
Should I bother with a pool in this use case or stick to a single connection that I then pass to each thread?


text:
Q: View the history of a file while trying to merge, showing both branches I am trying to handle merge conflicts. Rather than seeing the changes on each branch, as tools typically show, what I really want to see is the tree of the file, starting from the nearest common ancestor, then showing the commits that changed the file, with the option to drill down into the changes from a particular commit if necessary.
Critically, I need to see the commits from each branch that leads up to the prospective merge, not just from my current branch. The accepted answer to View the change history of a file using Git versioning is getting close to my ideal. But to actually use it, I have to create a dummy repo, actually complete the merge in said dummy repo, then apply the accepted answer there to the dummy repo. I'm wondering if there is an easier way.

A: I am not sure it will quite answer, but you can do the following logs:
git log --oneline --graph branch1 branch2 # Show the graph of both branches (including common parents)
git log --oneline --graph branch1...branch2 # show the graph of commits for the commits which are either in branch1 or in branch2 but not both (note the 3 dots)

A: For most content conflicts, having config set with merge.conflictStyle=diff3 is more than enough. There might be cases where you might have to dig deeper but having the common ancestor and the two conflicting pieces of code is enough to figure out what's going on.


text:
Q: Threading + TabControl in C# This is a slightly weird setup, and I'm planning on redoing it, but, if nothing else, I'm hoping that I can learn a lot more about threading as a result of this.
At the moment, I've got an application I'm building which uses a TabControl Windows Form as the basis for its design. I've got a number of different things I need to do, so I figured this might be the best way to do it.
Now, I'm coding in a Macro function into the program, such that a user can record and playback mouse and keyboard actions. That has been perfectly fine, and mixing it with System.Timers.Timer has been ok as well. However, the DLL I'm using uses Thread.Sleep(x) to pause the thread in between keystroke and mouse executions.
At this point, the button is on a different tabpage and switches to a different page. However, the point blank setup resulted in the program hanging while waiting for the macro execution to complete.
To explain a little better:

*

*User clicks button in main tabcontrol.

*Tabcontrol.SelectedIndex is switched to the proper page, but does not refresh page (I tried calling this.Refresh(), it didn't work)

*Macro executes

*Tabcontrol finishes loading the page, but by this point, the necessary macro has already executed and the loaded page is superfluous.

To get around this, I started researching threading and seeing how I could use that. I came up with the following code inside a class:
Class X{
  Thread othread;
  ...
  public void Play()
  {
    if ((othread != null) && !(othread.IsAlive))
    {
        othread = new Thread(playValues);
        GC.Collect();
    }
    else if (othread == null) othread = new Thread(playValues);
    else return;
    othread.Start();
  }

  public void PlayValues(){
  ...
  Thread.CurrentThread.Abort();
  }

}

The reason why the thread is destroyed is because, every time the user clicks "Play" in the main form, X.Play() is called, so I need to either reuse the thread (I researched Monitor.Pulse(), but that gave me asynchronous call errors), or destroy it permanently each time it completes.
Now, at the moment, the code works fine. However, the fact that I'm consistently creating and destroying threads every time I have to play a macro is slightly concerning, and the ridiculous amount of GC calls is also worrying me.
Can I get some pointers on threading, and how I might be able to do this better, without this setup? As a point of fact, the secondary tab is a webpage, and the macros are executed on the webpage's form.

*

*Edit: I don't know if I didn't make this clear, but the macro is using a mouse and keyboard simulator. The other tab is a webbrowser setup, and it nests an applet inside, so I'm emulating the hardware functions in order to perform automated setups. This helps because I don't need to lock anything (all mouse and keyboard calls are operated by the simulators, and have no bearing on values controlled by the tertiary tab), I just need to be able to a) have the thread perform the same function whenever a user presses a button, and b) remove some of the excess materials.

I was also informed that 'Thread.CurrentThread.Abort' is threadsafe and therefore a fine way to end a thread if you wanted to end it forever, but if I can have the thread repeat its functions instead of killing it, that'd be wonderful...

A: To reuse the play thread, you could use an AutoResetEvent that you Set() from the main thread. The same goes for when the thread is idle - the main thread prepares the data required to play, then Set()s a different AutoResetEvent, causing the play thread to start.
So the startPlayingAutoResetEvent in below example causes the thread to wait until the main thread tells it to "go", while the stopPlayingAutoResetEvent causes the play thread to respond to the main thread telling it to "stop" whenever it is not performing a step.
Main thread:
// prepare data to play
startPlayingAutoResetEvent.Set();
// ...
stopPlayingAutoResetEvent.Set();

Play thread:
while (true)
{
    // wait for the main thread to signal "start"
    startPlayingAutoResetEvent.WaitOne();
    // ensure the stopPlaying is in an unsignalled state
    stopPlayingAutoResetEvent.Reset();

    // gather the data the main thread has prepared

    while (stepsToPlay)
    {
        // wait until main thread signals to stop OR timeout has elapsed
        if (stopPlayingAutoResetEvent.WaitOne(timeout))
        {
            // abort current run and put thread in idle mode, waiting for new commands
            break;
        }
        else
        {
            // play next step
        }
    }
}


text:
Q: How can I implement full disk encryption for a disk containing Ubuntu with plausible deniability? I would like to have a disk that:

*

*has Ubuntu installed

*is fully encrypted

*is setup in such a way as to make denial of the existence of the Ubuntu install plausible

Truecrypt provides the last two features but only for Windows: http://www.truecrypt.org/docs/?s=sys-encryption-supported-os
The alternate installer for Ubuntu provides the first two features but not the last.
I imagine that plausible deniability would be achieved by, at least:

*

*Having two installs of Ubuntu and 2 passphrases (or keyfiles) which would unencrypt each one.

*Moving any unencrypted data (such as /boot) onto a USB stick

Are there any programs out there which support this feature set for Ubuntu?

A: Check this out:
http://and1equals1.blogspot.ro/2009/10/encrypting-your-hdd-with-plausible.html
I don't see why you wouldn't be able to use the above tutorial but for an additional OS installed in the free space (under cryptsetup - as described in the tutorial - which does not create a LUKS header) left after installing your main decoy OS.


text:
Q: Adding Header Search Path when trying to incorportate GPUImage in my xcode project? I am trying to add the GPUImage framework/library according to this:
github.com/BradLarson/GPUImage
and I am stuck at the point of setting the Header Search Path. I tried setting a path but when I tried importing#import "GPUImage.h" I got an error saying it is not found. Maybe I put in the wrong path? I'm confused about what I should do because I have never used this before (very new to programming). Any  help would be greatly appreciated.

A: First, if you're developing using Xcode 6, you might look at using the new framework support present in iOS 8 (and back to iOS 7, near as I can tell). The project has a true iOS framework that eliminates the need for setting paths to headers, like static libraries require. See the "Adding this as a framework (module) to your Mac or iOS project" section of the instructions for how to use this.
If you're targeting an older version of iOS and/or using an older version of Xcode, you'll need to set the Header Search Paths value in your build settings to be the path to where you installed GPUImage from where your application resides. For example, the sample applications in the examples/iOS directory use a path of
../../../framework

The .. elements in that tell it to step one directory back from the location of your application project. Since the examples reside in GPUImage/examples/iOS/[project], the above relative path leads to GPUImage/framework. If you placed your project and GPUImage in the same encompassing directory, you might use
../GPUImage/framework

instead.
In that path setting, make sure you set the option on the right to "recursive" as well.
Use the sample applications as templates, and compare how they are set up to your application to find areas where you might have deviated from the listed setup instructions. About the hardest part of those instructions is getting the relative path right.

A: I suggest you use cocoapods. It handles gracefully library dependencies and GPUImage is present there.
cocoapods.org
It is also fairly easy to install and use


text:
Q: Is there a way to manually set order of bar plot in R ggplot2? I'm doing some data analysis for an organization and I'm trying to change the order of the bars in a bar chart. Right now, it is ordered alphabetically but I want to set it to the order of days in a week. I have tried using levels and factor, but I don't think it is working possibly because I am reading the data in from an excel file and each column is the sum of all values of that day. Is there a way to do this through ggplot2 without editing the original excel file?
enter image description here

A: Basically do something like ggplot(df,aes(x=factor(V1,level=unique(V1)),y=V3,fill=V2)) (or add fct_rev to reverse the order):
t=read.table("https://pastebin.com/raw/GyEiXxNs",r=1)
t=t[,c(4,1,3,2)]
colnames(t)=paste0("V",1:ncol(t)) # prevent ggplot from reordering the bars for each column
t=t[order(as.matrix(t)%*%(1:ncol(t))^2),] # reorder rows so that rows with a high percentage of the first column are placed first

w2l=function(x)data.frame(V1=rownames(x)[row(x)],V2=colnames(x)[col(x)],V3=unname(c(unlist(x))))
t2=w2l(t) # wide to long

lab=round(100*t2$V3)
lab[lab<=1]="" # don't display labels for 0% or 1%

ggplot(t2,aes(x=fct_rev(factor(V1,levels=unique(V1))),y=V3,fill=V2))+
geom_bar(stat="identity",width=1,position=position_fill(reverse=T),size=.1,color="gray10")+
geom_text(aes(label=lab),position=position_stack(vjust=.5,reverse=T),size=3.5)+
coord_flip()+
scale_x_discrete(expand=c(0,0))+
scale_y_discrete(expand=c(0,0))+
scale_fill_manual(values=colorspace::hex(colorspace::HSV(head(seq(0,360,length.out=ncol(t)+1),-1),.5,1)))+
# ggh4x::force_panelsizes(cols=unit(3,"in"))+ # make bars always 3 inches wide
theme(
  axis.text=element_text(color="black",size=11),
  axis.text.x=element_blank(),
  axis.ticks=element_blank(),
  axis.title=element_blank(),
  legend.position="none",
  panel.border=element_rect(color="gray10",fill=NA,size=.2)
)

ggsave("1.png",width=4.5,height=.25*nrow(t)+.3,limitsize=F)


text:
Q: How to compress objects into strings without losing too much information Trying to figure out how to make a class that can create objects based on text files. If the interface Readable has the method String asString(), and the method Readable read(String s) in a class is to construct a Readable object based on the string s, so that (read(String s).asString()).equals(s), I've been able to easily write read using reflection if the Readable type being written/read has only primitive arguments, but I'm not sure how to write them to easily convert to and from a string when the constructor takes an arbitrary amount of Readable classes in an arbitrary order. For using only primitives, the asString method reads as follows:
private int n, double d;
...
public String asString(){
    return "@"+getClass().getName()+"#i%d#"+this.n+"%"+this.d;
}

The symbols are arbitrary characters allowing me to use String.split, and i and d give the primitive types of the fields n and d, since Class.forName doesn't work with primitives. This problem requires me to have around 7 layers of nested Readables, however, some of which have containers of arbitrary amounts of Readables. I understand how to write the read method based on the string, but how do I compress an object into a string while retaining all of the necessary information?

A: This can be done with the Java API: ObjectOutputStream and ObjectInputStream.
Your class needs to implement the java.io.Serializable interface to be written to a stream/created from a stream.
Example:
public class WriteMe implements java.io.Serializable {
    private static final long serialVersionUID = 1234567890L; // Should be generated

    private int myInt = 164;
    private Date myDate = new Date();
    private transient int money = 1648; // Will be ignored
}

In your main class:
public class HelloStackoverflow {
    public static void main(String[] args) {
        ObjectOutputStream os = new ObjectOutputStream(System.out); // Print to standard output
        os.writeObject(new WriteMe());
    }
}

You can do the same with ObjectInputStream and .readObject().
If you want to store your object as a String, you should encode it using Base64, because the output will be Java-Bytecode!

A: As Titus already said - why inventing the wheel again.
With ObjectOutputStream and ObjectInputStream java already already have such mechanism


text:
Q: Filtering based on a newly created column (I've looked it up and couldn't find an answer, If this is a duplicate, just point out a link and I'll delete this question)
Let's say I have the following code
select CASE WHEN lower(Http_User_Agent) like '%mobi%' then 'Mobile'
            else 'Desktop' end as Device
from Http_User_Agent
where Device = 'Mobile'

Which returns
Msg 207, Level 16, State 1, Line 4
Invalid column name 'Device'.

What I'm basically trying to do is to filter by the newly created column Device. Is there an easy way to this?
I'm using SQL server 2008 on windows 7

A: You can do this with a subquery:
select ua.*
from (select ua.*,
             (CASE WHEN lower(Http_User_Agent) like '%mobi%' then 'Mobile'
                   else 'Desktop'
              end) as Device
      from Http_User_Agent ua
     ) ua
where Device = 'Mobile';

Or by repeating the condition:
select ua.*,
       (CASE WHEN lower(Http_User_Agent) like '%mobi%' then 'Mobile'
             else 'Desktop'
        end) as Device
from Http_User_Agent ua
where lower(Http_User_Agent) like '%mobi%';

However, you cannot use a column alias in a where at the same level where it is defined.  This is part of the ANSI standard and not a "limitation" of SQL Server (or any other database).

A: At the time of execution of the query, the Device alias isn't yet assigned to the resultset. So you need to either do this:
SELECT
  CASE WHEN LOWER(Http_User_Agent) LIKE '%mobi%' THEN 'Mobile'
  ELSE 'Desktop'
  END AS Device
FROM Http_User_Agent
WHERE
  CASE WHEN LOWER(Http_User_Agent) LIKE '%mobi%' THEN 'Mobile'
  ELSE 'Desktop'
  END = 'Mobile'

...i.e. not reference the new alias at all. Or this
SELECT *
FROM
(SELECT
  CASE WHEN LOWER(Http_User_Agent) LIKE '%mobi%' THEN 'Mobile'
  ELSE 'Desktop'
  END AS Device
FROM Http_User_Agent)
WHERE Device = 'Mobile'

...i.e reference it from a surrounding select

A:
It is not allowable to refer to a column alias in a WHERE clause, because the column value might not yet be determined when the WHERE clause is executed.

So you have to write that case statement again in your where clause.


text:
Q: Is it possible to run Vagrant on Windows without relying on Cygwin rsync? I installed Vagrant on Windows 10. But it won't run the VM because it complains that the installed Cygwin rsync is incompatible.
Right now, I have no need to synchronize files with Windows and so I don't think I need rsync.
Is it possible to tell Vagrant to turn this requirement / option off?

A: Yes, you need to use an override in your Vagrantfile:
override.vm.synced_folder ".", "/vagrant", disabled: true


text:
Q: detect if windows is running on hyper-v virtual machine Is there a way to detect if a windows operating system is running on Hyper-V? I am going to implement it in Java (I found out that there is a way for C++ but not for java) so that my application will be able to recognize if it is running on native or virtual(explicitly Hyper-V) system.

A: I think your problem should be in executing a WMI query from java.
Libraries like jWMI could help you.
Also you could try to find an answer on the following post.
After that you could use your code written in C++ to easily execute your windows discovery.
Hope it helps.


text:
Q: Is it possible for 2 windows managed by Windows to have the same window handle value? Is it possible for 2 windows managed by Windows to have the same window handle value?
Consider both cases when these 2 windows are opened by the same process and when these 2 windows are opened by 2 different processes.

A: Quick answer: no, it's not possible if they are inside the same desktop, every window handle issued by the window manager is unique (inside its desktop) throughout all the existence of the window, otherwise it couldn't uniquely identify such window on the system current window station desktop (which is defined by MSDN as "a logical display surface" that "contains user interface objects such as windows, menus, and hooks; it can be used to create and manage windows").

Long answer:
The issue is discussed here, which points to this article. It seems that HWNDs are local to desktops , so you can have two identical HWNDs that point to two different windows, but they are necessarily in two separated desktops, so there's no ambiguity (the WM handle you pass to every user32 function refers implicitly to the current desktop, to go to another one you have to use SetThreadDesktop, and this call fails if your thread owns any desktop-contained object into the current desktop).
On the other hand, when a window is destroyed, its handle can be reused, but IIRC the window manager employs some techniques to avoid immediately reusing a handle.

A: Every window open at a particular time will have a unique handle.
However, they can be reused once a window is closed.


text:
Q: Slow Matlab R2018b TypedArray array access in C++ I am using MATLAB R2018b mex functions to integrate a C++ library with my MATLAB code. As part of that, I need to take data in a MATLAB array and save into a C++ pointer array and a C++ vector of structures. However, mapping the matlab typed array is proving to be very slow (~0.4 seconds for ~800,000 elements).
here is the relevant code
const matlab::data::TypedArray<float> Vertices = std::move(inputs[0]);
float* positions = new float[Vertices.getNumberofElements()];
for (size_t i = 0; i < Vertices.getDimensions()[0]; i ++)
{
    ctr = 9 * i;
    positions[ctr + 0] = Vertices[i][0];
    positions[ctr + 1] = Vertices[i][1];
    positions[ctr + 2] = Vertices[i][2];
}

What is causing this loop to be slow? I tried re-ordering array access for Vertices to try and make the code more cache friendly, but that didn't produce a meaningful speed-up. Right now, the loop is ~0.4ms for 800,000 elements, ideally memory copy should take far less time, right?
When I looked over previous advice, I found that most answers use older mex functions, where the new(?) MATLAB C++ API doesn't have the same functions or structure.
Edit:
I followed Cris' advice and used a loop over iterators, that increased speed by about half, to 0.14 seconds.
The new code I'm using is:
    const matlab::data::TypedArray<float> Vertices = std::move(inputs[0]);
    float* positions = new float[Vertices.getNumberofElements()];
for (auto it = Vertices.begin(); it != Vertices.end(); ++it)
{
    positions[ctr] = *it;
    ++ctr;
}

So it is faster, but still surprisingly slow (0.14 seconds for 800,000 elements). Is there any other way to speed this loop?

A: I got a major speedup by applying Cris advice and using the following code:
const matlab::data::TypedArray<float> Vertices = std::move(inputs[0]);
float* positions = new float[Vertices.getNumberofElements()];
memcpy(positions,&*Vertices.begin,sizeof(float)*Vertices.getNumberofElements());

Runtime went from 0.14 (using standard Visual Studio optimization) to 0.0035, which is acceptably fast for my application.


text:
Q: Xargs doesn't listen to stdin I try to add an svn:keywords property to all existing *.php and *.phtml files. Therefore, I use this command:
find . -regex '.*\.php' -o -regex '.*\.phtml'|xargs svn propset svn:keywords "Id"

This should, according to Mateusz Loskot, add the property to all files. If I run find . -regex '.*\.php' -o -regex '.*\.phtml', all files are found but xargs returns this message: xargs: svn: No such file or directory.
I also tried to export the found list (>> ~/temp) and use xargs -a to read the arguments from a file input, without success. How can I update all my php files?
PS. I use Kubuntu Linux Natty (11.04), which has built in bash 4.2.8 and xargs 4.4.2 (if that might matter)

A: Your command looks ok. It seems that xargs cannot find svn command in PATH. Verify that it is available or use full file path (which svn should display full path to svn).
To prevent spaces in file name issue I would recommend -print0 argument for find and -0 for xargs:
find . -name '\*.php' -o -name '\*.phtml' -print0 | xargs -0 svn propset svn:keywords "Id"

A: You can try the usual tricks here, such as:
find ... | while read i ; do svn propset svn:keywords Id "$i" ; done


text:
Q: Replace atomic numbers in a column with the corresponding atomic symbols in a file Can anybody tell me how can I replace atomic numbers in the first column of a file by the corresponding atomic symbols in bash script? I have many file to be replaced this way.
file:HCOOH
  6             0        -.134702     .401251    -.000249
  8             0       -1.134262    -.264582     .000069
  8             0        1.118680    -.091075     .000056
  1             0        -.107617    1.495465     .000513
  1             0        1.040484   -1.057714    -.000020

Desired Result:
  C             0        -.134702     .401251    -.000249
  O             0       -1.134262    -.264582     .000069
  O             0        1.118680    -.091075     .000056
  H             0        -.107617    1.495465     .000513
  H             0        1.040484   -1.057714    -.000020

My aim is to extract the geometry  of a system from the benchmark databases given in the supporting in formation of the paper "J. Chem. Theory Comput., 2005, 1 (3), pp 415–432 DOI: 10.1021/ct049851d" . As the atoms are given as the atomic numbers in the databases I can not use geometry directly in the NWCHEM code. Therefore I need to replace them with their corresponding symbols. Using the script
    #!/bin/bash
    atoms=(HCOOH H He Li Be B C N O F Ne)
    name="$(awk '{print $1}' HCOOH)"
    rm atom
    for j in ${name};
    do
     echo ${atoms[$j]} >>atom
    done
    awk 'FNR==NR{a[NR]=$1;next}{$1=a[FNR]}1' atom HCOOH | awk '{printf         "%-3s %-1s %10.5f %10.5f %10.5f\n", $1, $2, $3, $4, $5}'

I am getting
 HCOOH      0.00000    0.00000    0.00000
 C   0   -0.13470    0.40125   -0.00025
 O   0   -1.13426   -0.26458    0.00007
 O   0    1.11868   -0.09108    0.00006
 H   0   -0.10762    1.49547    0.00051
 H   0    1.04048   -1.05771   -0.00002

I could not escape zeros coming in the first line if the formatted output is required. I would be happy if someone can help to print the formatted output without printing zeros in the first line.
Thanks.
Finally, got the desired results using the script
    #!/bin/bash
    atoms=(HCOOH H He Li Be B C N O F Ne)
    name="$(awk '{print $1}' HCOOH)"
    rm atom
    for j in ${name};
    do
     echo ${atoms[$j]} >>atom
    done
    awk 'FNR==NR{a[NR]=$1;next}{$1=a[FNR]}1' atom HCOOH | awk 'NR==1{printf "%-3s\n", $1}' >tHCOOH
    awk 'FNR==NR{a[NR]=$1;next}{$1=a[FNR]}1' atom HCOOH | awk 'NR> 1{printf "%-3s %-1s %10.5f %10.5f %10.5f\n", $1, $2, $3, $4, $5}' >>tHCOOH #|
    mv tHCOOH HCOOH

which is
 HCOOH
 C   0   -0.13470    0.40125   -0.00025
 O   0   -1.13426   -0.26458    0.00007
 O   0    1.11868   -0.09108    0.00006
 H   0   -0.10762    1.49547    0.00051
 H   0    1.04048   -1.05771   -0.00002

Let me know if there is a better way for getting the same output.
Thanks.


text:
Q: Tooltip Issue with jQuery I have this code
<?php
if(!empty($auction['Auc']['beginner'])){
?>

<?= $html->image('badge/beginner_icon.png', array('width'=>"30", 'height'=>"30", 'border'=>"0", 'alt'=>"Beginner auction", 'title'=>"Beginner auc"))?>

    Beginner
    For an explanation please click here

<?php
}
?>

Issue is when I have two auctions with same auction type for e.g like beginner in this case, then tooltip is only working for one auction. I want it to display tooltip on all similar auctions..

A: Change your code to use this:
<?php if(!empty($auction['Auc']['beginner'])){?>
   <?= $html->image('badge/beginner_icon.png', array('width'=>"30", 'height'=>"30", 'border'=>"0", 'alt'=>"Beginner auction", 'title'=>"Beginner auc"))?>

       Beginner
       For an explanation please click here

<?php } ?>

ID has to be unique so you need to use different IDs or a class instead.

A: ID of elements should be unique. No two elements should have same ID. You should use CSS class as your jquery selector
$(function() {
    $(".yourCssClassName").tooltip();
});

Assuming all your auction items has the class yourCssClassName


text:
Q: Can't get property values from ${env} in Apache Ant I have the following Ant target to show the value of the JAVA_HOME environment variable:
<target name="show-java-home">
    <echo message="${env.JAVA_HOME}"/>
</target>

However, I get the following result:
show-java-home:
     [echo] ${env.JAVA_HOME}
BUILD SUCCESSFUL
Total time: 292 milliseconds

What am I doing wrong?

A: Try this:
<property environment="env"/>

<target name="show-java-home">
   <echo message="${env.JAVA_HOME}"/>
</target>

more info here: https://ant.apache.org/manual/Tasks/property.html

A: You're doing everything right.
This Ant console output tells you that %JAVA_HOME% simply isn't defined:
show-java-home:
     [echo] ${env.JAVA_HOME}


text:
Q: Reading values from JSON in Node.js in GET request I need to pull the Indication value from the following
{
    "records": [{
        "id": "recBgV3VDiJeMkcwo",
        "fields": {
            "DrugName": "azatadine",
            "nameapi": ["recBgV3VDiJeMkcwo"],
            "Indication": "For the relief of the symptoms of upper respiratory mucosal congestion in perennial and allergic rhinitis, and for the relief of nasal congestion and eustachian t.b. congestion.",
            "lookup": ["azatadine"],
            "drugID": "recBgV3VDiJeMkcwo"
        },
        "createdTime": "2018-11-09T19:38:24.000Z"
    }]
 }

When I try to do
response.records[0].fields.Indication
I get the error
Cannot read property 'fields' of undefined
Here is my code:
function httpGet() {

return new Promise(((resolve, reject) => {

var options = {

host: 'api.airtable.com',

port: 443,

path: '/v0/appYqfJ3Rt2F0sRGn/Database?filterByFormula=(DrugName=%27azatadine%27)',

method: 'GET',

headers: {

Authorization: 'Bearer key123456789'

}

};

const request = https.request(options, (response) => {

response.setEncoding('utf8');

let returnData = '';

response.on('data', (chunk) => {

returnData += chunk;

});

response.on('end', () => {

resolve(returnData);

});

response.on('error', (error) => {

reject(error);

});

});

request.end();

}));

}

const UserReplyIntent_Handler = {

canHandle(handlerInput) {

const request = handlerInput.requestEnvelope.request;

return request.type === 'IntentRequest' && request.intent.name === 'UserReplyIntent' ;

},

async handle(handlerInput) {

const response = await httpGet();

console.log(response);

return handlerInput.responseBuilder

.speak("Okay. Here we go" + response.records[0].fields.Indication)

.reprompt("say again")

.getResponse();

},

};

A: Your JSON isn't really JSON yet at this stage. You need to parse the result you get from your Ajax request to then work with it as native JSON.
The response is stringified when it gets delivered to you, that parse command will in stringify it for you.
You can do this as part of a then chain after your promise (probably best practice) or do it right inside your promise.

A: I was missing json.parse
.then((response) => {
      const data = JSON.parse(response);
 for (let i = 0; i < data.records.length; i++) {
 if (i === 0) {
     outputSpeech = outputSpeech +  'The name of the drug is' + data.records[i].fields.DrugName +  ', '

A: I was missing the json.parse method
.then((response) => {
      const data = JSON.parse(response);
 for (let i = 0; i < data.records.length; i++) {
 if (i === 0) {
     outputSpeech = outputSpeech +  'The name of the drug is' + data.records[i].fields.DrugName +  ', '

A: A standard way to do this with asynchronous responses is to do the following:
.then((response) => response.json())
.then((response) => {
  //response is now a JSON object that you can be worked with
})


text:
Q: Set num of output shard in Write.to(Sink) in dataflow I am having a customized sink extending FileBasedSink to which I write to by calling PCollection.apply(Write.to(MySink)) in dataflow (very simpler to XmlSink.java). However it seems by default simply calling Write.to will always result to 3 output shards? Is there any way that I could define the number of output shard (like TextTO.Write.withNumShards) just in customized sink class definition? or I have to define another customized PTransformer like TextIO.Write?

A: Unfortunately, right now FileBasedSink does not support specifying the number of shards.
In practice, the number of shards you get will be dependent on how the framework chooses to optimize the parts of the pipeline producing the collection you're writing, so there's essentially no control over that.
I've filed a JIRA issue for your request so you can subscribe to the status.


text:
Q: Is it possible to close the print dialog? By using window.print() we can trigger the print dialog to be opened.
Is there any way to close it?
It turns out that (at least on Chrome/Chromium), location.reload() does close it, but it reloads the page.
Is there any other friendlier way/API to close it?

A: What about using setTimeout?
window.print(); //this triggers the print

setTimeout("closePrintView()", 3000); // delay required for IE to realise what's going on

window.onafterprint = closePrintView(); // this is the magic

// this function simply runs something you want it to do
function closePrintView() {
  // do something
}

EDIT: There's also onbeforeprint if it's useful.
EDIT 2: It appears onbeforeprint fires before the dialog appears...
onafterprint is fired just before the dialog appears. So it's not possible to know if the document is printed or whether you've canceled the dialog.

A: Try this:
var window = window.open();
window.print();
window.onfocus = function () {
    window.close();
}

A: You can check window.close. This will close the current window.
var openPrint = window.print();
//Rest of code
 openPrint.close();


text:
Q: Why is appendChild not working? I'm trying to create three elements (parent, and one child) but the third element which is an <a> tag is not appending to modalChild event thought it's creating it correctly.

modal = document.createElement("div");
    modal.className = "parent";
 modalChild = document.createElement("div");
 modalChild.className = "child";
    btnClose = document.createElement("a");
 btnClose.className = "btnClose";
 btnClose.textContent = "X";

 modal.appendChild(modalChild);
 modalChild.appendChild(btnClose);

 document.body.appendChild(modal);
 modal.style.display = "flex";

modalChild is being appended to modal correctly but btnClose is not appending to modalChild. Does anyone see the problem with the code?

A: The code works porperly.You can append to modalChild  in any order

modal = document.createElement("div");
modal.className = "parent";
modalChild = document.createElement("div");
modalChild.className = "child";
btnClose = document.createElement("a");
btnClose.className = "btnClose";
btnClose.textContent = "X";

modalChild.appendChild(btnClose);
modal.appendChild(modalChild);

document.body.appendChild(modal);
modal.style.display = "flex";


text:
Q: Why is ffprobe showing N/A for bitrate? I am transcoding a video from VP9/opus webm to H.264/aac mp4. I'd like to maintain bitrate or reduce bitrate if either the audio bitrate > 128k or the file becomes larger than 5MB.
So I try to query the  bitrate of the source audio stream in my video. However, it gives me N/A for the bitrate. (Also for the video stream by the way.)
$  ffprobe -v error -show_format -show_streams myvid.webm
[STREAM]
index=1
codec_name=opus
codec_long_name=Opus (Opus Interactive Audio Codec)
profile=unknown
codec_type=audio
codec_tag_string=[0][0][0][0]
codec_tag=0x0000
sample_fmt=fltp
sample_rate=48000
channels=2
channel_layout=stereo
bits_per_sample=0
id=N/A
r_frame_rate=0/0
avg_frame_rate=0/0
time_base=1/1000
start_pts=-7
start_time=-0.007000
duration_ts=N/A
duration=N/A
bit_rate=N/A
max_bit_rate=N/A
bits_per_raw_sample=N/A
nb_frames=N/A
nb_read_frames=N/A
nb_read_packets=N/A
DISPOSITION:default=1
DISPOSITION:dub=0
DISPOSITION:original=0
DISPOSITION:comment=0
DISPOSITION:lyrics=0
DISPOSITION:karaoke=0
DISPOSITION:forced=0
DISPOSITION:hearing_impaired=0
DISPOSITION:visual_impaired=0
DISPOSITION:clean_effects=0
DISPOSITION:attached_pic=0
DISPOSITION:timed_thumbnails=0
TAG:language=eng
TAG:DURATION=00:02:48.161000000
[/STREAM]

What gives? Shouldn't the bitrate always be known???


text:
Q: wp_add_inline_style in plugin not working I am trying to use wp_add_inline_style in plugin. I want to add some style when shortcode runs.
add_action('wp_enqueue_scripts', 'cod_enqueue_scripts');
add_shortcode('cod', 'cod_process_shortcode');

function cod_enqueue_scripts() {
    wp_enqueue_style('cod-style', plugins_url('css/style.css', __FILE__));
}

function cod_process_shortcode(){
    $inline_css = "
        .icon-color{
            color:#ad3;
        }";

    wp_add_inline_style('cod-style', $inline_css);
}

This doesn't work, It will not hook to 'cod-style'.
It works if I do this: (first enqueue CSS then call wp_add_inline_style immediately afterwards)
function cod_process_shortcode(){
    wp_enqueue_style('cod-custom', plugins_url('css/blank.css', __FILE__));
    $inline_css = "
        .icon-color{
            color:#ad3;
        }";

    wp_add_inline_style('cod-custom', $inline_css);
}

In the above example, I used an empty CSS file (blank.css) for testing.
I though maybe my original css file is not loaded yet, but even if I enqueue empty css in cod_enqueue_scripts, it will wont do it, like this:
function cod_enqueue_scripts() {
    wp_enqueue_style('cod-style', plugins_url('css/blank.css', __FILE__));
}

function cod_process_shortcode(){
    $inline_css = "
        .icon-color{
            color:#ad3;
        }";

    wp_add_inline_style('cod-style', $inline_css);
}

I don't know what inline CSS I need until shortcode runs, and seems odd that the wp_add_inline_style will not hook to original wp_enqueue_style.

A: Here's a solution based on this post, which allows the inline CSS to be rendered by a shortcode using a dependency without a path (basically a null file).
// Optional base styles
add_action( 'wp_enqueue_scripts', 'cod_enqueue_scripts' );
function cod_enqueue_scripts() {
    wp_enqueue_style('cod-style', plugins_url('css/style.css', __FILE__));
}

// Shortcode handler which also outputs inline styles.
add_shortcode( 'cod', 'cod_process_shortcode');
function cod_process_shortcode() {
    $color = '#ff0000';
    $css = 'body { background-color: ' . $color . '; }';

    wp_register_style( 'cod-inline-style', false );
    wp_enqueue_style( 'cod-inline-style' );
    wp_add_inline_style( 'cod-inline-style', $css );

    return "
Shortcode output...
";
}

Alternatively, Rarst pointed out that the WordPress gallery shortcode outputs dynamic styles. The gallery shortcode does not make use of wp_add_inline_style(), but the end result is essentially the same.
Edit: Here's an alternate version where the inline styles use the dependency of the original styles.
// Base styles
add_action( 'wp_enqueue_scripts', 'cod_enqueue_scripts' );
function cod_enqueue_scripts() {
    wp_enqueue_style('cod-style', plugins_url('css/style.css', __FILE__));
}

// Shortcode handler which also outputs inline styles.
add_shortcode( 'cod', 'cod_process_shortcode');
function cod_process_shortcode() {
    $color = '#bada55';
    $css = 'body { background-color: ' . $color . '; }';

    wp_register_style( 'cod-inline-style', false, array( 'cod-style' )  );
    wp_enqueue_style( 'cod-inline-style' );
    wp_add_inline_style( 'cod-inline-style', $css );

    return "
Shortcode output...
";
}

A: This code is worked for me..
// Optional base styles
add_action( 'wp_enqueue_scripts', 'cod_enqueue_scripts' );
function cod_enqueue_scripts() {
    wp_enqueue_style('cod-style', plugins_url('css/style.css', __FILE__));
}

// Shortcode handler which also outputs inline styles.
add_shortcode( 'cod', 'cod_process_shortcode');
function cod_process_shortcode() {
    // your fornt end html
}

function custom_inline_style(){
    $color = '#ff0000';
    $css = 'body { background-color: ' . $color . '; }';

    wp_add_inline_style( 'cod-style', $css ); // hook to add inline style
}
add_action( 'wp_enqueue_scripts', 'custom_inline_style', 20 ); // if 20

If the priority is not working you can give more than 20.

A:          wp_enqueue_style( 'ninetheme-custom-style', get_template_directory_uri() . '/css/update.css' );
         $css = '.package .btn_acele { background-color: #333; }';
         wp_add_inline_style( 'my-custom-style', $css );
      }

You can use it in WordPress Shortcode, no need add_action :)


text:
Q: Understanding the relationship of displacement and electrical field of nonlinear material using fourier **I posted this question first in math.stackexchange but was told it might be more suitable here.
I have a general formula of
$$D = P_0 + \epsilon_1 E + \epsilon_2 E^2 + \epsilon_3 E^3 + ...$$
with $D$ as the electrical displacement, $E$ the electrical field, $P_0$ for the polarization at zero-field and $\epsilon$ the permittivity for a nonlinear dielectric ->  Source
With $E(t) = E cos(\omega t)$,
$$ D(t) = P_0 + \epsilon_1^*E_0 cos(wt) + \epsilon_2^*E_0^2 cos(2wt) + \epsilon_3^*E_0^3 cos(3wt)+ ...$$
and $D = \epsilon E$,
How do I go from:
$$ D(t) = D_0 + D_1cos(wt) + D_2cos(2wt) + D_3cos(3wt)+ ...$$
to
$$ D_0^* = P_0 + \frac{1}{2}\epsilon_2^*E_0^2 + \frac{3}{8}\epsilon_4^*E_0^4 + ... $$
$$ D_1^* = \epsilon_1^*E_0 + \frac{3}{4}\epsilon_3^*E_0^3 + \frac{10}{16}\epsilon_5^*E_0^5... $$
$$ D_2^* = \frac{1}{2}\epsilon_2^*E_0^2 + \frac{1}{2}\epsilon_4^*E_0^4 + \frac{15}{32}\epsilon_6^*E_0^6... $$
$$ D_3^* = \frac{1}{4}\epsilon_3^*E_0^3 + \frac{5}{16}\epsilon_5^*E_0^5 + \frac{21}{64}\epsilon_7^*E_0^7... $$
I'm pretty sure it has something to do with Fourier Transformation/Series but I'm not sure how to derive them.


text:
Q: How can I use the proof steps in the proof for the conservation of momentum to write equations for a 3-particle system? I am being asked to restate the proof for the conservation of momentum and Newton's third law for a 3-particle system. The textbook's steps (for an N particle system) are as follows:
(1.25) (net force on particle $\alpha$) $=\vec{F}_{\alpha}=\sum_{\beta\neq\alpha}\vec{F}_{\alpha\beta}+\vec{F}_{\alpha}^{ext}$ (where $\vec{F}^{ext}$ represents an external force on $\alpha$)
The net force is also the rate of change of the momentum for particle $\alpha$
(1.26) $\dot{\vec{P_\alpha}}=\sum_{\beta\neq\alpha}\vec{F}_{\alpha\beta}+\vec{F}_{\alpha}^{ext}$
Consider the total momentum: $\vec{P}=\sum_{\alpha}\vec{P_\alpha}$
Differentiating the equations: $\dot{\vec{P}}=\sum_{\alpha}\dot{\vec{P_\alpha}}$
Substituting $\dot{\vec{P_\alpha}}$,
(1.27) $\dot{\vec{P}}=\sum_{\alpha}\sum_{\beta\neq{\alpha}}\vec{F}_{\alpha\beta}+\sum_{\alpha}\vec{F}_\alpha^{ext}$
The double sum contains N(N-1) terms in all. The elements $\vec{F}_\alpha\beta$ can each be paired with $\vec{F}_\beta\alpha$, such that
(1.28) $\sum{}_\alpha\sum_{\beta\neq\alpha}\vec{F}_{\alpha\beta}=\sum_\alpha\sum_{\beta>\alpha}{(\vec{F}_{\alpha\beta}+\vec{F}_{\beta\alpha})}$
The double sum on the right only includes values of $\alpha$ and $\beta$ with $\alpha<\beta$ and has half of many terms as that on the left. Each term is the sum of two forces, and by the third law, that sum is zero. Therefore,
(1.29) $\dot{\vec{P}}=\sum_{\alpha}\vec{F}_\alpha^{ext}\equiv\vec{F}^{ext}$

For the N=3 particle system, I have written what I believe are the equations (1.25) and (1.26)
(1.25) $\vec{F}_{net}=\vec{F}_{1,2}+\vec{F}_{1,3}+\vec{F}_{2,1}+\vec{F}_{2,3}+\vec{F}_{3,1}+\vec{F}_{3,2}+\vec{F}^{ext}_1+\vec{F}^{ext}_2+\vec{F}^{ext}_3$
(1.26) $\dot{\vec{P}}_1=\vec{F}_{1,2}+\vec{F}_{1,3}+\vec{F}^{ext}_1$ ; $\dot{\vec{P}}_2=\vec{F}_{2,1}+\vec{F}_{2,3}+\vec{F}^{ext}_2$ ; $\dot{\vec{P}}_2=\vec{F}_{3,1}+\vec{F}_{3,2}+\vec{F}^{ext}_3$
I am assuming my final answer will lead me to show that $$\dot{\vec{P}}=\vec{F}_1^{ext}+\vec{F}_3^{ext}+\vec{F}_3^{ext}$$
However, I am unsure of how to write the summations explicitly for each of particles in the steps leading to equation (1.29).


text:
Q: Virtual photon description of $B$ and $E$ fields I continue to find it amazing that something as "bulky" and macroscopic as a static magnetic or electric field is actually a manifestation of virtual photons.
So putting on your QFT spectacles, look closely at the space near the pole of a powerful magnet – virtual photons! Now look between the plates of a charged capacitor – virtual photons again!
But if it's all virtual photons, how do we get the difference between a magnetic and electric field?

A: In QED, for transverse photons, the electric field doesn't commute with the photon number operator. Neither does the magnetic field. In fact, the electric and magnetic fields don't even commute with each other. To get a state with a fixed electric field — or at least with a small uncertainty in it in the quantum sense — we need a superposition of states with different numbers of photons. This is called a squeezed state in quantum optics. The smaller the uncertainty in the electric field, the larger the corresponding uncertainty in the magnetic field and vice versa.
Photons come with a transverse polarization. The electric field is parallel to it, while the magnetic field is perpendicular to both the polarization and the wave vector.
What about longitudinal photons then? In the $\xi$-gauge, we have to impose additional constraints (Lorenz gauge and Gauss constraints), making the actual physical state a coherent state with a definite value for the Fourier transform of the longitudinal component of the electric field, which is equated with the Fourier transform of the charge density divided by the wave number. This applies to electrostatics. Longitudinal photons do not contribute to the magnetic field.
What about magnetostatics then? Only transverse photons can contribute to the magnetic field, and the analysis involving photon number operators applies. This time, we have a special case of a squeezed state, namely a coherent state.
We have to note though that the number of photons isn't conserved in time because of absorption and emission by the current source. This causes the coherent phase to kept stationary in time, instead of rotating.
Incidentally, unless a photon escapes into outer space and heads off to infinity without being absorbed by or interacting with any matter, then by the definition of a virtual photon as a photon propagator not contained in any of the external legs of a Feynman diagram, nearly all photons are virtual photons. And if a photon is detected in any way, it definitely has to be a virtual photon.

A: the wave function of a single photon has several components - much like the components of the Dirac field (or Dirac wave function) - and this wave function is pretty much isomorphic to the electromagnetic field, remembering the complexified values of $E$ and $B$ vectors at each point. The probability density that a photon is found at a particular point is proportional to the energy density $(E^2+B^2)/2$ at this point. But again, the interpretation of $B,E$ for a single photon has to be changed.
So whether the field around an object is electric or magnetic or both is encoded in the "polarization" of the virtual photons.
You may imagine that the photon has 6 possible polarizations or so, identified with the components of $E$ and $B$. Well, for a particular direction, it is really just the $E+iB$ combination that acts as the wave function, so there are only three polarizations for a given direction - and one of them (the longitudinal) is forbidden, too. ;-) But the qualitative point that there are many polarizations is correct.
However, as emphasized repeatedly, you shouldn't imagine that a virtual photon is a real particle that can be counted. That's a reason why QGR's answer is pretty much irrelevant for your question because there is no operator counting virtual photons at all - so it makes no sense to ask whether it commutes with other operators. QGR may have thought about real photons but he hasn't answered your question, anyway.
By the way, static fields correspond to a vanishing frequency - because everything with a non-vanishing frequency will go like $\exp(i\omega t)$ or $\cos(\omega t)$. So if you want to describe the fields of electric sources and magnets as a collection of virtual photons, you must realize that the static nature of the field implies that the relevant fields will have the energy equal to zero. But the momentum is nonzero because the field depends on space - because of the sources. Such virtual photons are very far from being on-shell - they're very virtual, indeed. It is not too helpful to talk about virtual photons with particular frequencies and wavenumbers if there are electric sources in the middle of the region you want to describe. The Fourier analysis is only helpful for photons in a pretty much empty space.
But you could calculate the probabilities of various outcomes for a charged particle in an external electric or magnetic field, produced e.g. by many spinning electrons, using Feynman diagrams - where the virtual photons are the internal lines. The Feynman diagrams would be able to calculate the force acting on the probe particle. Some terms in the force wouldn't depend on the velocity - the electric forces - while others would depend on the velocity - the magnetic ones. These different terms would always come from the "same type" of virtual photons but all these photons depend on the sources of the field, so you would of course get different results for electric and magnetic fields.
All this stuff is confusing and really unnecessary. If you worry that quantum electrodynamics won't reproduce basic properties of electromagnetism - such as the difference between electricity and magnetism; or the difference between attractive and repulsive forces - then you shouldn't worry. It can be easily demonstrated that in the classical limit - e.g. for strong enough fields with a low enough frequency - the quantum electrodynamics (and the quantum field) directly reduces to the right classical limit, the classical electrodynamics (and the classical fields). Virtual photons are just a very helpful tool to study all kinds of processes similar to scattering. Their maths can be deduced from quantum fields - not the other way around - and these virtual photons don't happen to be useful to describe your kind of highly classical situations.
Best wishes
Luboš


text:
Q: box-shadow not showing on div element I'm trying to add box-shadow to a <div> element but it just doesn't show up.
I've already tried adding height and width in px to the class and tried using z-index on class and parents, nothing worked for me.
Here's the code. https://codepen.io/mateus-ramos/pen/BaBbyMG
I want to add shadow to ".imagem-container" class.

A: Clip path is cutting off your shadow. A workaround for this is to create a parent div for the element, then put the box-shadow on that. Then use filter to follow the path of your imagem-container (otherwise it will be a square box shadow). This article might help: https://css-tricks.com/using-box-shadows-and-clip-path-together/

A: You have to add a drop-shadow filter in the parent div, so the effect can be shown. In your code add this into the .job class
.job { /*parent div of .imagem-container*/
  display: flex;
  padding: 5%;
  height: 500px;
  filter: drop-shadow(5px 5px 5px rgba(0, 0, 0, 0.5));
}

The problem in your case is that the shadow is applied to the text as well. You need to create a parent div only for your .imagem-container div, the text can be outside of that scope and the effect doesn't apply to all the content.


text:
Q: No system command when using mysql from cli Attempting to change directories, view directory contents, etc., but for some reason I don't have the system command to use the command line once I run mysql.  These are the options I get:
List of all MySQL commands:
Note that all text commands must be first on line and end with ';'
?         (\?) Synonym for `help'.
clear     (\c) Clear the current input statement.
connect   (\r) Reconnect to the server. Optional arguments are db and host.
delimiter (\d) Set statement delimiter.
ego       (\G) Send command to mysql server, display result vertically.
exit      (\q) Exit mysql. Same as quit.
go        (\g) Send command to mysql server.
help      (\h) Display this help.
notee     (\t) Don't write into outfile.
print     (\p) Print current command.
prompt    (\R) Change your mysql prompt.
quit      (\q) Quit mysql.
rehash    (\#) Rebuild completion hash.
source    (\.) Execute an SQL script file. Takes a file name as an argument.
status    (\s) Get status information from the server.
tee       (\T) Set outfile [to_outfile]. Append everything into given outfile.
use       (\u) Use another database. Takes database name as argument.
charset   (\C) Switch to another charset. Might be needed for processing binlog
with multi-byte charsets.
warnings  (\W) Show warnings after every statement.
nowarning (\w) Don't show warnings after every statement.

Any ideas what could cause this?  It seems to be possible using windows (using \!).

A: As stated in the MySQL documentation, the MySQL system command works only in Unix and therefore not in Windows:
http://dev.mysql.com/doc/refman/5.6/en/mysql-commands.html


text:
Q: reseting animator in unity im trying to do some simple animations of a moving ball when i click on it and i want to do it in a "loop" what i mean is when i click the first time the ball will move from point A to point B, after that to point C and then to point A again and if i will press again it will go to point B...
the problem is that after i finish the first rotation (the ball got to point A again) the ball wont go to point B no matter what.
this is the animator with the states and the state parameter the condition for moving from state to state is just an int that goes up by 1 from click to click and is restarted when it gets to 5
enter image description here
and this is the code that changes the state every time i click on it
  public void OnPointerDown(PointerEventData eventData)
{
    if (relesed)
    {
        relesed = false;
        int temp = anim.GetInteger("state");
        temp++;
        anim.SetInteger("state", temp);
        if (anim.GetInteger("state") >= 5)
        {
            anim.SetInteger("state", 0);
            anim.ResetTrigger("state");
        }
        print(anim.GetInteger("state"));
    }

    meshRenderer.material.color = downColor;

}

A: There are a few things that could be causing this, check on the transitions to make sure they are properly checking the integer you're working with. As for the code, it does what you want just fine. Code-wise it could be that the "relese" boolean is being set to false after the first loop.
Just a few notes regarding the code:
You're using anim.ResetTrigger("state") when "state" is not a trigger, it's an integer parameter. There are also some small performance issues for unecessary GetInteger calls, here's how I would improve it:
public void OnPointerDown(PointerEventData eventData)
    {
        if (relesed)
        {
            relesed = false;
            int temp = anim.GetInteger("state");
            temp++;
            if (temp >= 5)
                temp = 0;

            anim.SetInteger("state", temp);

            print(temp);
        }

        meshRenderer.material.color = downColor;
    }


text:
Q: Wordpress site getting DDOS with dynamic query strings in URL I have a WordPress site which is hosted on AWS lightsail (Load balancer with few instances running apache).
Site is getting 1000s of request per minute with URL like site.com/?872837
The number in the URL is dynamic which forces my cache plugin (Hummingbird) to create a new cache page and not use the existing cached page.
Lighsails load balancer doesn't provide any logs so I can't check which IPs are hitting the site.
Can I use .htaccess to remove that query string of this format (I tried searching but couldn't find anything)?


text:
Q: Activating overlay background when hovering over link I am preparing a layout for a blog and need to make a slideshow more or less as follows:

I'm already able to do a lot via CSS, but I have a problem! The images only activate when the mouse hovers over the div, but I need the image to be activated, or better, be colored, when hovering over the image link.
Could someone help me out with this?
Take my code via BOOTPLY
Bootply
I do not know if I do this via CSS or only via JavaScript. I even tried to do more via JavaScript but do not know much about it.

A: You need to use the pseudo-class :hover on the parent of the image and text.  This will change the opacity of the image when you hover over any child of that element.
Change this
.img-box-feature:hover{opacity:1;}

to this
[class*="box-"]:hover .img-box-feature{opacity:1;}

See updated Bootply
Also, I suggest you change the classes from box-um, box-dois, and box-tres to just box.  Then you can use .box:nth-child() or .box:nth-of-type() to target a specific one.

A: If you change this line:
.img-box-feature:hover {
  opacity:1;
}

to this:
.img-box-feature:hover,
.img-box-feature.hover{
  opacity:1;
}

you could use jQuery to toggle to new class:
$('.over-text-feature h1 a').on('mouseenter mouseleave', function(e) {
  $(this).closest('[class^="col-"]').find('.img-box-feature').toggleClass('hover');
})

Bootply

A: try out the webkit filters
e.g. .img-box-feature2:hover{-webkit-filter: invert(100%);}
You could also use contrast (%), brightness (decimal), blur (px), or sepia (%)

A: It remains unclear to me if you want the images to active also when hovering over the text, or only when hovering over the text. I also wonder if you want all images to be active to just one.
In case you want all the images to only become active when hovering the text, you could move the text element to be the first child of .section-slider, and use the CSS sibling selector: ~.
Like this:

Lorem Ipsum é simplesmente uma simulação de texto da indústria tipográfica e de impressos

Lorem Ipsum é simplesmente uma simulação de texto da indústria tipográfica e de impressos

01

01

01

01

/* SLIDER PRINCIPAL */
.section-slider{ background:#000; width: 100%;}

.img-box-feature{
    width: 100%;
    height: 0;
    padding-bottom: 70% ; /* % of width, defines aspect ratio*/
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;
    background:rgba(0,0,0,0.6);
    opacity:0.3;
    transition: all 0.5s ease;
    -webkit-transition: all 0.5s ease;

}
.img-box-feature2{
    width: 100%;
    height: 0;
    padding-bottom: 35% ; /* % of width, defines aspect ratio*/
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;
    background:rgba(0,0,0,0.6);
    opacity:0.3;
    transition: all 0.5s ease;
    -webkit-transition: all 0.5s ease;
}
.over-text-feature{ z-index:100;
    position:absolute;
    color:white;
    display: inline-block;
    vertical-align: middle;
    bottom: 15px;
    width: 95%;
    left:10px;
    border-left: 5px solid #fff;
    padding-left: 10px;
    }
.over-text-feature h1{ font-size: 1.8em;}
.over-text-feature h1 a{color: #00aeef;}
.section-slider .box-um{float: left; margin: 0px !important; padding: 0px !important;}
.section-slider .box-dois{float: right;margin: 0px !important; padding: 0px !important;}
.section-slider .box-tres{float: right; margin: 0px !important; padding: 0px !important;}
.over-text-feature:hover ~ .container .img-box-feature, .over-text-feature:hover ~ .container .img-box-feature2{opacity: 1;}


text:
Q: Как сделать запись атрибута href в куки? (Смена стилей на сайте) Всем привет! Не могу побороть данную проблему из-за нехватки знаний.
Мне необходимо менять цветовые схемы на сайте, что бы после перезагрузки страницы все сохранялось.
Как это работает на сайте, смотрите тут: https://themes.3rdwavemedia.com/demo/devblog/
Вот так выглядит окошко с кнопками в index.html

Choose Colour

При каком либо выборе в менюшке выше, меняется атрибут href вот тут.
    <link id="theme-style" rel="stylesheet" href="{THEME}/css/main.css" />

Управляет всем этим делом JS и библиотека jQuery v3.3.1
    $(document).ready(function() {

    /* ======= DEMO THEME CONFIG ====== */
    $('#config-trigger').click(function(e){

        e.preventDefault();

        //$("#config-panel").toggleClass('config-panel-open');

        if($(this).hasClass('config-panel-open')){
          $("#config-panel").animate({
            right: "-=190" //same as the panel width
           }, 500);
          $(this).removeClass('config-panel-open').addClass('config-panel-hide');
         }
         else {
         $("#config-panel").animate({
           right: "+=190" //same as the panel width
           }, 500);
          $(this).removeClass('config-panel-hide').addClass('config-panel-open');
         }
    });

    $('#config-close').on('click', function(e) {
        e.preventDefault();
        $('#config-trigger').click();
    });

    $('#color-options a').on('click', function(e) {
        var $styleSheet = $(this).attr('data-style');

        $('#theme-style').attr('href', $styleSheet);

        var $listItem = $(this).closest('li');
        $listItem.addClass('active');
        $listItem.siblings().removeClass('active');

        e.preventDefault();

    });

});

Основная проблема, что после обновления страницы, устанавливается стандартный стиль main.css, а нужно сохранить выбранный юзером стиль. Помогите решить эту проблему!


text:
Q: Divided differences at one point According to wikipedia for different numbers $a_0, a_1, a_2,..., a_n$ we can write
$$f[a_0, a_1, a_2,...,a_n] = \sum_{j = 0}^n \frac{f(x_j)}{q'(x_j)}$$
where $q(x) = \prod_{i = 0}^n(x - x_i)$
Also, for the same numbers $(n + 1)$, we can write that:
$$f[a_0, a_0,...,a_0] = \frac{f^{(n)}(a_0)}{n!}$$
However, I'm wondering if we can write this expression in terms of polynomial $q$, as in the case of different nodes $a_0, a_1,...,a_n$. Could you please give a hand with justifying if its possible?


text:
Q: Cells are not formatting as per styling Xlsx-Styles Angular 4 I have to export an excel sheet through my angular app. So I am using js-xlsx and xlsx-style modules. I would like to format the cells as I required but am not able to.
The below is the piece of code using for styling the cell.
cell.s = {font: { bold: true }};

While debugging the sheet has font styling properties but while exporting the excel doesn't render the properties.


text:
Q: Python - MySQL connection error I use Python 3.5.2 and PyMySQL
and after creating  the database of MySQL
import pymysql

conn = pymysql(host='127.0.0.1',unix_socket='/tmp/mysql.sock',user='root',passwd=None,db='mysql')

AttributeError: module 'socket' has no attribute 'AF_UNIX'

p.s. when setting MySQL in my win10,the port 3306 can't work(make me unable to continue)
so I change the port to 306 and then work
Has that any impact on my error?
it shows some error...

A: If you are running on Windows, you cannot use a Unix socket to connect to the database.  When connecting, set the host and port parameters instead of unix_socket.
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='Your password', db='mysql')


text:
Q: App was rejected for use of protected 3rd party material My app has been rejected due to 3rd party material clause:

8.5: Use of protected 3rd party material (trademarks, copyrights, trade secrets, otherwise proprietary content) requires a documented rights check which must be provided upon request.

1, What is documented rights check composed of
2, How do I offer it up to Apple so that my App is approved.

A: There are several avenues you can take to resolve this. The first is to log into the developer center for your iOS developer account and go to the Resolution Center and verify that the reason is correct and see if they have identified specific assets (music, artwork, code that could reasonably be protected by copyright in the US.).
There is an App Review board, but I wouldn't rush to that as it's kind of a final step and you'll want all your ducks in a row if you go that route.
If you really have no clue what parts of your app might be problematic, you can use a support incident and ask Developer Technical Support to point you to the specific items that are problematic and flagged by the reviewer. My guess is you will have a good idea and can substitute a royalty free drawing or song to resubmit the app and confirm whether the items you suspect being flagged for rejection are the actual items.
At that point, you will need to decide if you want to push things and use the assets and somehow justify why copyright material isn't in your app or get approval from the copyright owner and submit that evidence to Apple.
You could also ask the reviewer to send you the list of assets so you can start the rights check documentation. Depending on the issue they see, it could be a simple letter from your lawyer to something much more involved if Apple has had previous legal requests from copyright holders and you have run afoul of that with your recent review denial.
All of the above would be most applicable if the app contains assets that were flagged. If your app during testing consumes or downloads other copyright material, you may need to have a more direct discussion with Apple to understand if you are even going to be allowed to distribute your App through Apple's storefront.
Worst case, you can request clarification of the rejection from https://developer.apple.com/appstore/contact/


text:
Q: TreeView inside ScrollWindow prints warning Spent 2 days to solve this, so I find this very useful.
I am followed by this GTKmm tutorial, added Gtk::TreeView in Gtk::ScrolledWindow but when I am adding more rows it shows messages like this:

(GUI:25948): Gtk-WARNING **: Allocating size to gtkmm__GtkWindow
  0x55ad53e44500 without calling
  gtk_widget_get_preferred_width/height(). How does the code know the
  size to allocate?

How to remove warnings? Its annoying too much.

A: So, you have ExampleWindow class with this childs
Gtk::ScrolledWindow m_ScrolledWindow;
Gtk::TreeView m_TreeView;
Glib::RefPtr<Gtk::ListStore> m_refTreeModel;

Inside your ExampleWindow() constructor replace this:
m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);

with:
m_ScrolledWindow.set_policy(Gtk::POLICY_ALWAYS, Gtk::POLICY_ALWAYS);
m_ScrolledWindow.set_resize_mode(Gtk::ResizeMode::RESIZE_IMMEDIATE);

I've replaced POLICY_AUTOMATIC with POLICY_ALWAYS because of SIGSEGV in /usr/lib/libgtk-3.so.0


text:
Q: Run sp_BlitzCache an agent job to assist performance tuning efforts / baselining query performance? Just getting into using various Brent Ozar tools like sp_BlitzCache and sp_BlitzIndex to identify and correct SQL Server performance issues. Been experimenting with running sp_AskBrent (now BlitzFirst...) and sp_WhoIsActive as agent jobs as a way to baseline query performance.
Do any of you run sp_BlitzCache periodically as an agent job to capture history / provide a baseline and/or evidence for your SQL Server performance tuning efforts? If so:

*

*How specifically has this helped you in your environment?

*Which sp_BlitzCache sort_order do you find most helpful to log? I'm considering separate output tables by cpu, reads, duration, and executions per minute. But wondering if I should be using "avg X" for these sorts.

*Should I stick with the default of @top = 10? Or go for 20, 30, etc?
Here's an example where I'm using total reads and top 20:
EXEC DbaTools.dbo.sp_BlitzCache
 @top='20', @sort_order = 'reads', @output_database_name = 'DbaTools', @output_schema_name = 'dbo', @output_table_name = 'BlitzCache_by_reads'

*How frequently would you run such a job? Weekly? Since the plan cache doesn't get wiped out until a host / service restart, an explicit command to do so (dbcc freeproccache), or in some other perhaps unexpected way (to some) such as changing MAXDOP (our Team learned the latter the hard way).

*This is more in line with with another StackExchange question just I posted about sp_AskBrent and sp_WhoIsActive, but how resource-intensive is it to run these SPs on a periodic basis?
That other StackExchange question is here:
sp_AskBrent not logging queries when saving to table vs. sp_WhoIsActive

A:
How specifically has this helped you in your environment?

My laptop instances are running great these days!
But seriously, if you lack a monitoring tool, this is a good way to analyze your plan cache for all sorts of problems, and opportunities for tuning. We warn you about a lot of stuff that may not be obvious just looking at an execution plan.

Which sp_BlitzCache sort_order do you find most helpful to log? I'm
  considering separate output tables by cpu, reads, duration, and
  executions per minute. But wondering if I should be using "avg X" for
  these sorts.

You may find some overlap in the different sort orders. For instance, CPU and Reads often have a lot of overlap.
As for average vs total, that mostly depends on plan cache stability. If it doesn't change much, averages can be more interesting than totals. Sometimes small, not necessarily tune-able queries rack up a lot of total CPU time because they're run fairly frequently, as well as maintenance tasks. This is something you'll have to figure out for each environment.

Should I stick with the default of @top = 10? Or go for 20, 30, etc?

This is also subjective, but lends itself a bit to another question of yours. The more plans you choose to bring in to analyze, the more resource intensive it is. Analyzing XML in SQL Server is... challenging.
The default is 10 to keep the footprint small, but also give you some meaningful results back. Of course, if you're not finding anything of interest in the top 10, feel free to experiment with different values to see how long it takes to run, and even if it helps you find anything interesting.

How frequently would you run such a job? Weekly? Since the plan cache
  doesn't get wiped out until a host / service restart, an explicit
  command to do so (dbcc freeproccache), or in some other perhaps
  unexpected way (to some) such as changing MAXDOP (our Team learned the
  latter the hard way).

This depends a bit on plan cache stability. If the same stored procedures run over and over again, daily or weekly is fine. If your server gets a lot of ad hoc user queries pushed through, you may want to run it hourly, or at some other interval your server can handle.
You can also use the @IgnoreQueryHashes parameter to keep some of the noise out.

This is more in line with with another StackExchange question just I
  posted about sp_AskBrent and sp_WhoIsActive, but how
  resource-intensive is it to run these SPs on a periodic basis?

We aim to be as resource un-intensive as possible, but the number of plans you choose to analyze, and the size of the plans can cause spikes. Like I said, analyzing XML in SQL Server ain't fun. It's single threaded, and can use a bit of CPU. You can use the @DatabaseName parameter if you're only interested in what one database is doing, which can help focus tuning efforts.
Thanks!


text:
Q: How can i solve "0 " value try to get length value? if i try to add int value into array with string length Whole data is "0" why? and how can solve it?
  for (int j = 0; j < dTable.Columns.Count; j++)
                for (int i = 0; i < dTable.Rows.Count; i++)
                {

                    mycounter[i] = dTable.Rows[i][j].ToString().Length;
                }
it is not related to mycounter because:
  string test = "";
           foreach(DataColumn dc in dTable.Columns)
                for (int i = 0; i < dTable.Rows.Count; i++)
                {
                   // MessageBox.Show(dTable.Rows[i][dc].ToString());
                    test = dTable.Rows[i][dc].ToString().Length.ToString();
                }

A: In  mycounter[]  you will have only values from last column of table.
May be last column contains empty strings?

A: In addition to what @Orsol said, the fact that you're looping through both dimensions seems to indicate that you want a total length for each row, and therefore,
mycounter[i] = dTable.Rows[i][j].ToString().Length;

should be changed to
mycounter[i] += dTable.Rows[i][j].ToString().Length;

It is also possible that the ToString() method is returning empty strings. Perhaps you're looking for a Text property?

A: Unless you are redeclaring mycounter between the for loops, you are overwriting mycounter[i] for each column 0 to Columns.Count-1 until the last column.
Did you want to sum the lengths? Or did you maybe want a 2-dimensional array for mycounter?


text:
Q: Pop up page using AJAX/jQuery I am developing a simple map to display business locations in my area. I have the main page (map.php) which holds the map and I have also created a page (business.php) which displays more information about a particular business such as some images, reviews, etc.
I need to have a link on the infobox (infowindow) which will link to this page dynamically using AJAX/jQuery. I also want to be able to pass values of the business selected (the icon clicked) from the map.php to business.php so that I can display and/or manipulate them. I can easily do that by passing values on the url to the php page. However I do not want to leave the main page, I just want the business page to pop up. How do I go about this? This is my JavaScript code below:
function getLocations (url) {
    downloadUrl(url, function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName("marker");

        for (var i = 0; i < markers.length; i++) {
            var name = markers[i].getAttribute("name");
            var address = markers[i].getAttribute("address");
            var type = markers[i].getAttribute("type");
            var pic = markers[i].getAttribute("image");
            var link = markers[i].getAttribute("link");
            var details = markers[i].getAttribute("details");
            var point = new google.maps.LatLng(
                parseFloat(markers[i].getAttribute("lat")),
                parseFloat(markers[i].getAttribute("lng"))
            );

            var html = "
" + name + "
" + '' + "
" + address + '
 View More Information
';
            var icon = customIcons[type] || {};
            var marker = new MarkerWithLabel({
                position: point,
                draggable: false,
                raiseOnDrag: false,
                map: map,
                labelContent: type,
                labelAnchor: new google.maps.Point(30, 65),
                labelClass: "labels", // the CSS class for the label
            });
            bindInfoWindow(marker, map, infoWindow, html);
        }
    });
}

When the user clicks the 'View More Information' link I want business.php page to pop dynamically.

A: The right answer is: it depends. How do you want to show that information? Do you want to open a new window or not at all?

*

*If you want/need/like to open a new window, just use the target attribute of the  tag. Like this: View More Information. target is the name of the window you want to open (as in here). You can even manipulate that window with javascript if you'd like (position, size, etc.). This is technically a pop-up, so some of your client's browser configurations might not like that.

*On the other hand, if you wish to display business.php on the same page, use a fancybox or lightbox-like solution with an embedded iframe, that will make so that you you can see the original page in the background (dimmed and not accessible) and still see your business page. You can even get away without the iframe by creaftinf your page so that you load the business.php page with ajax and replace the contents of some div/whatever to include that new html.

*You can also create a dynamic iframe to render the business.php page, etc.
There are lots of options and you should carefully examine which one to use based on your requirements and on each solution applicability to your problem (what happens if users prevent new windows from opening, for instance).

A: You'll need to "hijax" those links. The simplest way I can think of is something like this:
// When clicking any link
$('a').live('click', function (e) {
    var clicked = $(this);

    // Make sure a bussiness.php-link was clicked
    if (clicked.attr('href').indexOf('business.php') != -1) {
        // Grab the page with ajax
        $.get(clicked.attr('href'), function (data) {
            alert(data);
        });

        return false;
    }
});

Edit: You'll most likely wanna change the alert() to a lightbox or something fancier.


text:
Q: jQuery Magnify image will not rotate in Chrome only? I am using the jQuery Magnify plugin. The image doesn't rotate in Chrome unless I press Ctrl+F5.
After rotation I tried window.location.reload(true), random query string on JS files, using the following meta tags in the document:
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />

On click rotate button:
$.post("" + document.getElementById('site_url').value + "project_management/rotate_image", {
  src: $image[0].src,
  angle: angle,
  direction: direction
}).done(function(data) {
  window.location.reload(true);
});

The image rotates on the backend but is not shown on the screen after reloading.

A: So Query string does the trick in Manigfy.Js Thanks you very much madalinivascu


text:
Q: Beamer Handouts: 4 on 1 w/ adjusted positions, but page numbering incorrect I need to make Beamer handouts (either 4 on 1 or 8 on 1). Below is my MWE. I think the usual 4 on 1 has too much space between slides, with the slides too close to the margins (printing the handouts sometimes cuts off part of the slides). So I've included in my MWE a lot of code that I pulled from other questions on this site. The page numbering is incorrect. It was correct the first time I typeset it, but when I added more slides, things went crazy. How do I fix the page numbering?
\documentclass[12pt, handout]{beamer}

\usepackage{etex}
\usepackage{amsmath,amssymb,amsfonts,amsthm}
\usepackage{graphics}
\usepackage{color}
\usepackage{framed}
\usepackage{amsthm, array}
\usepackage{yhmath}
\usepackage{cancel}
\usepackage{shadethm}
\usepackage{booktabs}
\usepackage{tikz}
\usepackage{pgfplots}
\usetikzlibrary{calc,through,arrows,shadows,backgrounds,mindmap,calendar}
\RequirePackage{latexsym, verbatim, xspace, setspace}
\RequirePackage{tikz, pgflibraryplotmarks}

%%%%%%%%%%%%%%%%%%%%
% PRESENTATIONS
%
%
% Background color
%\setbeamercolor{normal text}{bg=red!20!yellow!25!}
%
%
% END OF PRESENTATION COMMANDS
%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%
%% HANDOUTS
%
%
\usepackage{pgffor}

\makeatletter
\def\strokeifnotempty{%
\expandafter\ifvoid\csname pgfpages@box@\the\pgf@cpn\endcsname
\let\@next=\relax
\else
\let\@next=\pgfstroke
\fi
\@next%
}
\makeatother

\mode<handout>
{
  \usepackage{pgf}
  \usepackage{pgfpages}

% 4 pages per sheet of paper
\pgfpagesdeclarelayout{4 on 1 new}%[letterpaper, border shrink=12mm, landscape]
{
  \edef\pgfpageoptionheight{\the\paperheight}
  \edef\pgfpageoptionwidth{\the\paperwidth}
  \edef\pgfpageoptionborder{0pt}
}
{
\pgfpagesphysicalpageoptions{
logical pages=4,
physical height=\pgfpageoptionheight,
physical width=\pgfpageoptionwidth}
\pgfpageslogicalpageoptions{1}{border code=\pgfsetlinewidth{1.1pt}
\strokeifnotempty,
border shrink=\pgfpageoptionborder,
resized width=.5\pgfphysicalwidth,
resized height=.5\pgfphysicalheight,
center = \pgfpoint{.25\pgfphysicalwidth + 10mm}{.75\pgfphysicalheight - 10mm}
}
\pgfpageslogicalpageoptions{2}{border code=\pgfsetlinewidth{1.1pt}\strokeifnotempty,
border shrink=\pgfpageoptionborder,
resized width=.5\pgfphysicalwidth,
resized height=.5\pgfphysicalheight,
center = \pgfpoint{.75\pgfphysicalwidth - 10mm}{.75\pgfphysicalheight - 10mm}
}
\pgfpageslogicalpageoptions{3}{border code=\pgfsetlinewidth{1.1pt}\strokeifnotempty,
border shrink=\pgfpageoptionborder,
resized width=.5\pgfphysicalwidth,
resized height=.5\pgfphysicalheight,
center = \pgfpoint{.25\pgfphysicalwidth + 10mm}{.25\pgfphysicalheight + 10mm}
}
\pgfpageslogicalpageoptions{4}{border code=\pgfsetlinewidth{1.1pt}\strokeifnotempty,
border shrink=\pgfpageoptionborder,
resized width=.5\pgfphysicalwidth,
resized height=.5\pgfphysicalheight,
center = \pgfpoint{.75\pgfphysicalwidth - 10mm}{.25\pgfphysicalheight + 10mm}
}
}

\IfFileExists{\jobname.aux}{\pgfpagesuselayout{4 on 1 new}[letterpaper,
border shrink=12mm, landscape] \nofiles}{}
}

% Make a border around frames
\setbeamertemplate{background canvas}{ \tikz \draw[semithick]
    (current page.north west)
    rectangle
    (current page.south east); }

%Page numbering for handouts
\defbeamertemplate{footline}{centered page number}
{%
    \hspace*{\fill}%
    \usebeamercolor[fg]{page number in head/foot}%
    \usebeamerfont{page number in head/foot}%
    {\color{black} \scriptsize \insertpagenumber \,/\,\inserttotalframenumber}%
    \hspace*{\fill}\vskip2pt%
}
\setbeamertemplate{footline}[centered page number]
%
%
% END OF HANDOUT COMMANDS
%%%%%%%%%%%%%%%%%%%%%%%

\frenchspacing

\title{Title}
\subtitle{Subtitle}
\author{Author}
\date{Date}

\begin{document}
%%%%%%%%%%%%%%%%%%%%
% Title Page
\begin{frame}[t]
\titlepage
\end{frame}
%%%%%%%%%%%%%%%%%%%%
\begin{frame}
%
Here's a slide.
\end{frame}
%%%%%%%%%%%%%%%%%%%%
\begin{frame}
%
Here's a slide.
\end{frame}
%%%%%%%%%%%%%%%%%%%%
\end{document}


text:
Q: Django and Matplotlib: signal only works in main thread In views.py of my Django project, at a certain point in the code, I want to display a graph plot on the server to visualise in real-time the user input. So, I created another file plotter.py in the same folder as views.py, with the following content to display a simple graph:
import numpy
import matplotlib.pyplot
def plot():
    N = 50
    x = numpy.random.rand(N)
    y = numpy.random.rand(N)
    colors = numpy.random.rand(N)
    area = numpy.pi * (15 * numpy.random.rand(N))**2
    matplotlib.pyplot.scatter(x, y, s=area, c=colors, alpha=0.5)
    matplotlib.pyplot.show()

Then, in views.py, I import plotter, and then at my desired point in the file, I have plotter.plot(). However, this gives the following error:
Request Method:     POST
Request URL:    http://localhost:8000/teacher/
Django Version:     1.7
Exception Type:     ValueError
Exception Value:

signal only works in main thread

Exception Location:     C:\Anaconda\lib\site-packages\matplotlib\backends\backend_qt5.py in mainloop, line 150
Python Executable:  C:\Anaconda\python.exe
Python Version:     2.7.8

How can I achieve this without causing such an error?

A: run your server as follows
python manage.py runserver --nothreading --noreload