text:
Q: Camel - Making parallel GET requests and aggregating the results via Dynamic Routes using Java DSL I am receiving a request on a Jetty Http Endpoint. The request body contains some urls in the request body. I have to make a GET request to those urls. Then aggregate the results from each of the GET request and return it to the caller.
Request Body:-
{
    "data" : [
        {"name" : "Hello", "url" : "http://server1"}
        {"name" : "Hello2", "url" : "http://server2"}

    ]
}

One way I can think of doing this is like below:-
from("jetty:http://localhost:8888/hello").process(new Processor() {
    public void process(Exchange exchange) throws Exception {
        // 1. Make the GET request in parallel using ThreadPoolExecutor
        // 2. Wait for all calls to finish. Collate the response
        // 3. Write it to exchange.getOut().setBody
    }
})

Can some one let me know if this can be achieved via Java DSL using camel Dynamic Routes, Splitter & Aggregator so that the Processor remains relatively small?
I am using camel 2.16.3.

A: The steps would be:

*

*Split the incoming data into URLs. This might involve sub-steps: for
instance, you might unmarshal the incoming JSON string into some POJO and perhaps this POJO has an array or list where each entry is a URL. Then, you could pass this along as the body. (Of course, you might need other information from the incoming request, so you might vary this.)

*The splitter would split easily enough if the body is a Array or something else that it can handle easily. In the simplest case, the splitter would pass on a single URI in the body of each split message.

*Next -- within the splitter's flow -- you could have a producer like http4, but instead of using the URI on the endpoint, you could ask it to use the URI in the message.

*Finally, you would have an aggregator.

Sounds like the core of your question is about the dynamic URI. This is how a code-snippet might look:
 from(...)... etc.
    .setHeader(Exchange.HTTP_URI, simple("${body}"))
    .setHeader(Exchange.HTTP_METHOD,
              constant(org.apache.camel.component.http4.HttpMethods.GET))
    .to("http4://google.com")

For a small work-demo, see this class.
public class HttpDynamicClient extends RouteBuilder {

    @Override
    public void configure() throws Exception {

        from("direct:testMultiple")
        .split(body())
        .to("direct:httpClient");

        from("direct:httpClient")
        .log("starting httpClient route")
        .setHeader(Exchange.HTTP_URI, simple("${body}"))
        .setHeader(Exchange.HTTP_METHOD, constant(org.apache.camel.component.http4.HttpMethods.GET))
        .to("http4://google.com")
        .process(new BodyToStringConverter())
        .log(LoggingLevel.INFO, "Output was ${body}");
    }

    private static class BodyToStringConverter implements Processor {
        @Override
        public void process(Exchange exchange) throws Exception {
            exchange.getOut().setBody(exchange.getIn().getBody(String.class));
        }
    }

    public static void main(String[] args) throws Exception {
        CamelContext context = new DefaultCamelContext();
        try {
            Logger logger = Logger.getLogger(HttpDynamicClient.class);

            context.addRoutes(new HttpDynamicClient());
            ProducerTemplate template = context.createProducerTemplate();
            context.start();
            Thread.sleep(1000);

            template.sendBody("direct:httpClient", "http://jsonplaceholder.typicode.com/posts/1");
            Thread.sleep(2000);

            template.sendBody("direct:testMultiple", new String [] {"http://jsonplaceholder.typicode.com/posts/1" , "http://jsonplaceholder.typicode.com/posts/1"});

        } finally {
            context.stop();
        }
    }

}

A: The answer of @Darius X. is pretty much what you need. To make the backend requests execute in parallel and to aggregate the response bodies in a string list you need to setup an aggregation strategy and set the parallel processing flag on the split definition.
@Override
public void configure() throws Exception {

    from("direct:testMultiple")
            .split(body(), new FlexibleAggregationStrategy<String>()
                    .pick(Builder.body())
                    .castAs(String.class)
                    .accumulateInCollection(ArrayList.class))
            .parallelProcessing()
            // .executorService(<instance of java.util.concurrent.ExecutorService>) // optional: use custom thread pool for parallel processing
            .to("direct:httpClient");

    from("direct:httpClient")
            .log("starting httpClient route")
            .setHeader(Exchange.HTTP_URI, simple("${body}"))
            .setHeader(Exchange.HTTP_METHOD, constant(org.apache.camel.component.http4.HttpMethods.GET))
            .to("http4://google.com")
            .convertBodyTo(String.class)
            .log(LoggingLevel.INFO, "Output was ${body}");
}

The out message of the exchange returned by direct:testMultiple will contain your result array as body.


text:
Q: Ajax uploading and ASP.NET I'm trying to upload some text content via ajax, that will be parsed later. That is my Javascript code:

 $("#fuFile").change(function () {
            var fileInput = document.getElementById("fuFile");
            var file = fileInput.files[0];
            var formdata = new FormData();
            formdata.append('file', file);

            var xhr = new XMLHttpRequest();
            xhr.open("POST", 'testhandler.ashx', true);
            xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            xhr.setRequestHeader("X-File-Name", file.name);
            xhr.setRequestHeader("Content-Type", "application/octet-stream");
            xhr.send(formdata);

 });

Where fuFile is my file input, and testhandler.ashx is the server handler that gets the uploaded file. (I actually use another handler to parse the file content.)
BUT when I try to do this:

HttpFileCollection fc = context.Request.Files;

It returned no files. But Works in IE for some reason.
But when I try to get the input stream:
    StreamReader stream = new StreamReader(context.Request.InputStream);
    string text = stream.ReadToEnd();

The text variable become (Http Headers) + File Content.
------WebKitFormBoundaryx16Mw7tnG6JeflIB\r\nContent-Disposition: form-data;name=\"file\"; filename=\"teste export.CSV\"\r\nContent-Type: application/vnd.ms-excel(..file content..)

That's OK, but I've used this plugin: http://valums.com/ajax-upload/
And the plugin returned me only the file content, in witch I could get the content via InputStream, I didn't received any HTTP header.
That's PERFECT, but I want to make a Upload script without using plugins. Just upload and parse, returning some results. Simple and fast
So, My question is: How to get the file content, uploaded by Ajax XHR, getting ONLY the file content, in any browser?

A: It's work for me and I think it can help you
My js function :
$("#fuFile").click(function () {
    var fileInput = document.getElementById("fuFile");
    var file = fileInput.files[0];
    var fd = new FormData();
    fd.append("files", file);
    var xhr = new XMLHttpRequest();

    xhr.open("POST", 'http://localhost:63186/UploadFile.ashx');

    xhr.send(fd);

});

My handler :
  string filePath = "~/Files/";

        //write your handler implementation here.
        if (context.Request.Files.Count <= 0)
        {
            context.Response.Write("No file uploaded");
        }
        else
        {
            for (int i = 0; i < context.Request.Files.Count; ++i)
            {
                HttpPostedFile file = context.Request.Files[i];
                 var fileInfo = new FileInfo(file.FileName);
                file.SaveAs(context.Server.MapPath(filePath + fileInfo.Name));
                context.Response.Write("File uploaded");
            }
        }

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I instantiate an array of objects from an Observable in Angular I have this in my .ts file
myobj: Observable<MyObj[]>;

which I can loop through in my HTML file to see all myObj[] coming from my API
is it possible to turn this Observable into an Array of MyObj?

A: You can use *ngFor directive with asyncPipe in your HTML template.
Your case:
<ng-container *ngFor="let obj of myobj | async">
  {{obj}}
</ng-container>


text:
Q: how to define commands within custom environment I am working on a custom .cls for typesetting my CV. I am trying to create a custom environment to provide formatting for job/education history. I would like to specify it as follows:
\begin{cvsection}
  \cvdate{xx-xx-xxxx}
  \cvcompany{Some company & Co.}
  \cvposition{Toilet cleaner}
  \cvcomment{I love cleanin' dem toilets!}
\end{cvsection}

So I've defined my environment and tried to use \newcommand... within the environment definition. LaTeX doesn't like that so what is the best way to approach this?

A: One purpose of organizing an environment in that way is to allow flexibility in the input.
You don't need to define the commands inside the environment; a frequently used strategy is the following:
\newcommand{\cvdate}[1]{\renewcommand{\givencvdate}{#1}}
\newcommand{\cvcompany}[1]{\renewcommand{\givencvcompany}{#1}}
\newcommand{\cvposition}[1]{\renewcommand{\givencvposition}{#1}}
\newcommand{\cvcomment}[1]{\renewcommand{\givencvcomment}{#1}}
\newcommand{\givencvdate}{REQUIRED!}
\newcommand{\givencvcompany}{REQUIRED!}
\newcommand{\givencvposition}{REQUIRED!}
\newcommand{\givencvcomment}{} % this is optional

\newenvironment{cvsection}
 {\begin{flushleft}}
 {\textbf{\givencvdate}\\
  \givencvcompany\\
  \givencvposition
  \ifx\empty\givencvcomment\else\\[.5ex] \textit{\givencvcomment}\fi
  \end{flushleft}}

In this way the order one specifies the data in the environment is irrelevant. Let's see a couple of examples
\begin{cvsection}
  \cvdate{xx-xx-xxxx}
  \cvcompany{Some company \& Co.}
  \cvposition{Toilet cleaner}
  \cvcomment{I love cleanin' dem toilets!}
\end{cvsection}

\begin{cvsection}
  \cvposition{Toilet cleaner}
  \cvdate{xx-xx-xxxx}
  \cvcompany{Another company \& Co.}
\end{cvsection}

Of course you have to adjust the definition of cvsection to suit your needs.


text:
Q: PKI-Certification Authority What are the best technology for the implementation of CA with respect to programming language ,database ,openssl etc

A: The question is quite broad. I find the administrative part is more complex than the technological part when it comes to PKIs.
There's not so much to do when setting up a basic CA: keep the private key safe (as always), receive certificate requests, verify the identity of the requester somehow, issue the certificate and store it somewhere (you can implement revocation mechanisms on top of this). I'm simplifying the picture slightly, but that's roughly the whole process, and you can implement that in a number of languages with existing libraries without much difficulty. Using BouncyCastle in Java works, but I'm sure other tools work too, for example OpenSSL with Perl. Not all languages expose the whole OpenSSL API (if they use it under the hood), and it can be handy to have a library that can read and write ASN.1 structures (especially if you want specific extensions). For storage, it may be useful to combine this with a directory structure (for example, some LDAP based system), but this may depend on what you already have in terms of user-management system.
The other aspect to take into account how simple it has to be for the users to request a certificate. This can be painful for users who have to request/use a certificate but don't have time to learn what it's all about. In-browser key-generation can be handy, instead of making them generate a CSR (more or less by hand). For in-browser generation, it's a combination of using <keygen> (the form element introduced by Netscape for this - works on Firefox and Opera for example), ActiveX (for MSIE) or the Mozilla Javascript extensions. Instead of ActiveX, you could also have a standalone "wizard" that's a full application (it will have more permissions to do some certificate related operations, as otherwise, what's available through JScript/ActiveX from within MSIE is limited and depends on various security settings.)
The other thing to take into account is the system whereby you verify the user's identity upon application. If it's relatively small, there's not much to do, but if it's a wider structure, you may need local representatives and various services that allow them to communicate those assertions by to the people who're going to issue the certificates.
Most of what you need here will depend on the level of assurances you require.
You might be interested in OpenCA.


text:
Q: Hyperledger Fabric v0.6, how to add more peer on the network without vagrant and docker? I have installed Fabric v0.6 on my VM ubuntu 16.04 and it works fine for peer, membersrvc, API, chaincode. I'm doing everything the same with this VM as with another VM on the same server. Let's call them VM1 and  VM2. I don't use vagrant or docker.
My project is connecting 4 peers together. I got some advice from different users. Some said that without using vagrant or pulling the image from docker, it will not work. Some said that it works, but my project does not with any VR environment. It's real implementation.
They said that I need to modify some lines in Core.Yaml and membersrvc.yaml to let the peers discover each other and send acknowledgment message. Some said that I have to do the above step and  port mapping in different servers to make it work.
When I try to edit both files, Sometime I don't understand about it at all. And some tips has no operation and step.
Thx for helping us to solve the problem.

A: Hyperledger Fabric has come a long way since the v0.6 release. If you are still working with v0.6 it is highly recommended that you upgrade to the most current release. There are a number of on-going efforts to develop supported approaches to deploying Hyperledger Fabric to multiple nodes, and for v1.0 and beyond, our deployments are all Docker based and can support kubernetes and swarm.


text:
Q: What is best practice when linking to several similar sources in a rails view? I'm working on a microservices framework in rails, and have come across a View in which we want to link out to several different applications that will reference the user being displayed. The user is identified through a user-urn.
Some notes about the applications we're linking to --

*

*Every different application has a unique url

*Not every application references the user through the same route -- i.e. meaning we can have /users/user-urn, or /users?urn=user-urn

*We'd like to be able to configure the external applications url for testing purposes.

My first instinct was to add a link helper, that would take the arguments of a user (given from the view), generate the link_to strategy with the url stored as an ENV. It looked like this --
def app_1_link(user)
    url = "#{ENV['APP_1_URL']}/users/#{user.urn}"
    link_to "Application 1", url, :target => "_blank"
 end
This made the helper too large, seeing that we needed many different helpers to accomplish the same goal.
My questions is -- is it bad practice to just add all of these links directly into the view with ENV vars?
e.g. (<p><%= link_to "App 1", "#{ENV['APP_1_URL']}/users/#{@user.urn}", :target => "_blank" %> </p>
Or should I build out some additional class/module logic to properly handle building the links?

A: I would make a db table to hold the information for the different applications, and a corresponding model.  Once you start having big lists of stuff in your config files, stored as constants, it's usually a sign that you should move it over into the database.
Then, you can have a model method in your ExternalApp model (or whatever you call it) to generate the necessary url.


text:
Q: Locating the iBooks folder in iCloud Drive (on Windows) I need to get the iBooks that are saved in iCloud Drive, using Windows, in a folder path and / or command line solution.
This is a spin-off from Locating the iBooks folder in iCloud Drive which only has answers for Apple macOS command line (macOS bash), while I need this for Windows.

A: Summing up the answer in advance: the folder simply might not exist on Windows.
And the workaround in advance:
If I cannot locate the folder, the only solution is via extraction from the iTunes backup, see:
https://stackoverflow.com/questions/62434692/iphone-move-in-one-go-all-pdfs-generated-from-safari-page-prints-which-i-fr/62701384#62701384

I found a description that explains the equivalent Windows and Mac folders at https://deciphertools.com/blog/how-to-backup-ibooks-pdfs/.

Where are My iBooks PDFs Stored on my Computer?

On Windows, the iBooks PDF files copied to your iTunes by doing
Transfer Purchases are stored in your computer user's account folder,
alongside your iTunes music. Here's how to find your iBooks PDFs on
your Windows computer: Go into your user account's Music folder. (On
Windows 10, this would show up under This PC -> Music.) Open the
folders iTunes -> iTunes Media -> Books. You should see your PDFs in
this folder.

On Mac, the iBooks PDFs copied by doing Transfer Purchases are tucked
away in data for the iBooks Mac App. Here's how to find your iBooks
PDFs on your Mac: Open Finder, and select the "Go" menu at the top of
the screen. Hold the Option key (or Shift + Option on latest Sierra
builds), and select the "Library" menu option from the Go menu. (On
OSX Lion and above, Library will only appear with the Option key
held.) From Library, navigate to Containers ->
com.apple.BKAgentService -> Data -> Documents -> iBooks -> Books. You
should see your PDFs in this folder.

Then there comes an explanation of how to use iBooks for iCloud, but only on Mac:

First, we need to make sure you've got iBooks turned on for your
iCloud drive documents on your Mac.

*

*From the Apple menu at the top of the screen, select System Preferences.

*Select iCloud in System Preferences.

*Next to iCloud Drive, press the "Options..." button.

*Ensure the iBooks checkbox is checked.

The checkbox "iBooks" does not exist in my iCloud > iCloud Drive settings. This could mean that it is simply not possible to sync iBooks with iCloud on Windows, as @MatthewBarclay commented above. This is also plausible, because my iBooks are backed up, and Apple does only one thing of the both, either sync or backup. And then, to answer the question, there simply is no such folder.
I have also tried opening it in terminal, as it could be hidden like the answer stated at Locating the iBooks folder in iCloud Drive, and I could not find it:
C:\Users\USER\Music\iTunes\iTunes Media>dir /a
does not have it, showing both hidden and unhidden items with /a (for /a see https://www.computerhope.com/issues/ch001039.htm).
Perhaps my sync settings are corrupt or wrong. Because I marked iBooks to be included in iCloud, but they are in my iTunes backup instead (proven), and they can only be in the backup OR in the iCloud (not in both, thus, they seem to be ONLY in the backup), if I am not mistaken. Settings > scroll down to Books > iCloud Drive is switched on, that cannot be the issue, following https://www.topmobiletech.com/how-to-sync-ibooks-to-all-your-ios-devices/.
I will not test this anymore, please test yourself and set a different answer which I will accept in case you find more.
If I cannot locate the folder, the only solution is via extraction from the iTunes backup, see:
https://stackoverflow.com/questions/62434692/iphone-move-in-one-go-all-pdfs-generated-from-safari-page-prints-which-i-fr/62701384#62701384

A: On Windows, the iBooks PDF files copied to your iTunes by doing Transfer Purchases are stored in your computer user's account folder, alongside your iTunes music.
Here's how to find your iBooks PDFs on your Windows computer: Go into your user account's Music folder. (On Windows 10, this would show up under This PC > Music.) Open the folders iTunes > iTunes Media > Books. You should see your PDFs in this folder.


text:
Q: can't delete all the elements in list when using remove() on python users=['admin','tony','roger','lily']
if users:
    for user in users:
        users.remove(user)
print(users)

I don't know why when I print users it still have element to print?


text:
Q: When does the Shampoodle open? I've heard that the Shampoodle opens after you spend 10,000 bells at Kicks or the Able Sisters. Does it start building the day after Kicks, or another random day?

A: From the Animal Crossing Wiki :

It must first be unlocked by spending at least 10,000 Bells between the Able Sisters store or Kicks. Kicks must also be open for at least 7 days before construction begins. It takes 4 days for Shampoodle to be built.


text:
Q: Android deployed App unable to instantiate application I have this strange error I do not know how to resolve.
I test my App deployed straight to my phone and it's working ok. But now testing downloading from Play Store the app crash as startup and the error is this one:

java.lang.RuntimeException: Unable to instantiate application
  com.bookit.android.BookItApp: java.lang.ClassNotFoundException:
  com.bookit.android.BookItApp

I have this class:
package com.bookit.android;

public class BookItApp extends Application {...}

My manifest I think it's ok defining the App class:

< application
          android:name="BookItApp"

Or Maybe should I define:

android:name = "com.bookit.android.BookItApp"

UPDATE:
this is my proguard-project.txt
I don't know if it's ok.
-keep class * extends java.util.ListResourceBundle {
protected Object[][] getContents();
}

-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
public static final *** NULL;
}

-keepnames @com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
@com.google.android.gms.common.annotation.KeepName *;
}

-keepnames class * implements android.os.Parcelable {
public static final ** CREATOR;

A: Exactly like you said, you should define it like this
<application
           android:name="com.bookit.android.BookItApp"
           ...
           ...
           >

A: The error says that "java.lang.ClassNotFoundException: com.bookit.android.BookItApp", so the definition is fine
You can unzip the apk to find  "com.bookit.android.BookItApp", if it's missing ,maybe caused by packging.
PS:Does it occurrs always?


text:
Q: [Vue warn]: Invalid prop: type check failed for prop "value". Expected Array, got Number with value 1 I have an input with the type number, I want to make it so that in the input they cannot print a number greater than ten, everything worked fine for me until I replaced the value with an array (before value: 1 after value: [1, 1])
After I changed to an array, I try to manually get the first number of the array as the value for my input, but I get an error and do not understand how to solve it
App.vue

    <customInput v-model="value[0]" :max-value="10" />

HelloWorld.vue

    <input :value="value[0]" type="number" @input="onInput" max="10" />

Again, everything worked for me until I replaced the 'value' with an array, you can also look at my code in codesandbox

A: When you are using

     <customInput v-model="value[0]" :max-value="10" />
</div

In App.vue you are passing a single value instead of an Array to HelloWorld.vue
So, either you change the type of value in the component from Array to Number, or change to:

     <customInput v-model="value" :max-value="10" />
</div

Also, in HelloWorld.vue the input type is "number" so even if you pass the array to the component you will have the warning.
So, do you need an array passed to the children component?
P.S. In the codesandbox you have this line missing the base: const newValue = parseInt(event.target.value); it should be: const newValue = parseInt(event.target.value, 10);


text:
Q: How to mark a reference as unindexed in Spring data cloud datastore We have @Unindexed annotation to mark a field as unindexed. But it doesn't work with a reference type field.
Source:- https://cloud.spring.io/spring-cloud-static/Greenwich.RC1/multi/multi__spring_data_cloud_datastore.html
@Entity(name = "kind_one")
class Test {
   @Unindexed
   private String someFieldOne; //works - property is unindexed

   @Unindexed
   private List<TestTwo> someFieldTwo; //doesn't work - property is still indexed
}

@Entity(name = "kind_two")
class TestTwo{
   @Unindexed
   private String someFieldThree;
}

When storing the Test object in datastore, "someFieldOne" is marked as unindexed, but "someFieldTwo" is marked as indexed.
Any lead will be appreciated.
Thanks!

A: For Lists the entire list must not be excluded from being indexed instead its values must be individually excluded from being indexed as mentioned in the comments here. Otherwise it will throw an exception.
I believe this is the reason why someFieldTwo is getting indexed in your case as it is a List barring the fact that it should throw an exception as per the comment.
So I would suggest you exclude the list elements individually as mentioned in this example instead of annotating the whole list with @unindexed.


text:
Q: input into javascript function I can't figure out how to have a javascript function which accepts a parameter correctly.
I can get the function working perfectly if I don't use a input parameter because I can do this:
var x = MyFunction;

But the moment I have to do this
 var x = MyFunction(e);

Then it breaks.
I tried to work around this by setting the input parameter afterwards, but I can't get anything to work. How can I do this?
http://jsfiddle.net/TxMmG/
var MyFunction = function() {

    var otherResult = function() {
        alert("Hi");
    },

        input, objToAlert = function() {
            return input;
        };

    return {
        objToAlert: objToAlert,
        input: input,
        otherResult: otherResult
    }

}();

var e1 = "test";

//var y = MyFunction(e); //this does not work if i add a parameter to function - moment i put parenthesis i get problems
var x = MyFunction;
x.input = e1; //also cant set the input here
x.objToAlert();
x.otherResult();

A: You put a () after the function definition, so the function is called and MyFunction is actually the object returned by the function, not the function itself.
Do like this:
var MyFunction = function() {
    // ...
};  // No () here

A: The problem is that your function returns an object. Therefore you're assigning an object to a var y. You can not treat object as a function.


text:
Q: using user defined Gjs classes in looking glass when defining Gjs classes within the scope of an extension, Because they can be assigned to a variable for later usage, there is a handle (namely the variable they are assigned to) to use them throughout the code.
var myClass = new Lang.Class({Name:'thisClass',...});
var instance = new myClass();

but attempting to use these classes that are defined within extensions, within the scope of looking glass, is not possible since there is no global variable assigned to them as a handle that I know of.
they are definitely globally defined since declaring a Gjs class of the same name triggers an error in looking glass.
//the following executed is within the scope of looking glass while an exctension including a class with the same name is running
var myClassLG = new Lang.Class({Name:'thisClass',...});
// returns <exception Error: Type of Gjs_thisClass is already registered.>

var myClassLG = new Lang.Class({Name:'thisClassWithDifferentNameButSameContent',...});
// this works
var instance = new myClassLG();

so is there a way to use these classes within the scope of looking glass without having to re-declare them with a different name?


text:
Q: Does every statistic have a sampling distribution, not just the sample mean? I am curious because most basic undergraduate statistics reference just start out Inferential Statistics by mentioning sampling distributions and the sampling distribution of the mean. My question is that does every statistic have one? Even the sample proportion, sample variance and standard deviation?
Edit: What would they be like?

A: Yes, as every statistic is a function of you sample (which are random variables) they will have a distribution. It might not be as easy to deduce the distribution as with the sample mean.

A: Yes, every statistic has a sampling distribution (though some may be degenerate).

What would they be like?

The sampling distribution of a statistic - just as with the mean - will in general depend on the population distribution you start with (and the sample size, naturally).
As an example, in a random sample from a normal distribution, the sample variance is a multiple of a chi-squared random variable and so the sample s.d. is a multiple of a chi random variable.
Below is a histogram of the sample standard deviations from 10000 samples of size 10 from a normal distribution, and the true sampling distribution (scaled-chi, red curve):

(click for larger version)
If you don't start with a normal population, the distribution of the sample s.d. is something else. E.g. here's the sample sd for 10000 samples of size 10 from a uniform distribution:

As we see, this one is mildly left skew rather than mildly right skew (I didn't calculate its theoretical distribution).
Note also that a sample proportion is a form of mean (label the in-category observations with a 1 and the out-of-category observations with a 0 and the sample mean is the sample proportion you started with). If the probability of being in group is constant and the observations are independent, it will have a discrete sampling distribution; a scaled binomial.
Many statistics are asymptotically normal under fairly mild conditions, but many are not (e.g. consider sample maxima for one).
Sampling distributions of various statistics come up in a number of situations. As an example, sampling distributions are important in hypothesis testing.


text:
Q: An exercise on isomorphic groups of order 24 I am a beginning learner of group theory.
Which of the following are isomorphic:$$\mathbb{Z_{24}}, D_{4}\times \mathbb{Z_{3}},A_{4}\times \mathbb{Z_{2}},\mathbb{Z_{2}}\times D_{6}, \mathbb{Z_{12}}\times \mathbb{Z_{2}},D_{12}, S_{4}$$
I know $\mathbb{Z_{24}}$ is cyclic and none of $\mathbb{Z_{12}}\times \mathbb{Z_{2}},D_{12}, S_{4}$ are cyclic since none has an element of order 24. I also know $D_{12}$ and $S_{4}$ are not isomorphic because $S_{4}$ has no element of order 12. Finally, I know $A_{4}$ and $D_{6}$ are also not isomorphic because $D_{6}$, unlike $A_{4}$, contains an element of order 6.
Other than this I don't know how to proceed. Any hints are appreciated. Please allow me to do the work.

A: $\mathbb{Z_{24}}$ is the only cyclic one - all other groups are non-abelian except $\mathbb{Z_{12}}\times \mathbb{Z_{2}}$, which you noted is not cyclic.
Among the remaining ones, $\mathbb{Z_{12}}\times \mathbb{Z_{2}}$ is the only abelian one, so this is out too.
If you have already seen the center of a group, you may proceed as follows.
Among the remaining ones, $S_{4}$ is the only centerless one ($Z(S_{4}) = 1$).
Now you should know that $D_{2 k}$ has a center of order $2$. Then $D_{4}\times \mathbb{Z_{3}}$ is the only one with a center of order $6$, and $\mathbb{Z_{2}}\times D_{6}$ is the only one with a center of order $4$.
We are left with $A_{4}\times \mathbb{Z_{2}}$ and $D_{12}$. But the latter has an element of order $12$, while the former does not. In fact, if $a \in A_{4}\times \mathbb{Z_{2}}$ has order $12$, then $a^{2} \in A_{4}$ has order $6$, and you know this is not the case.


text:
Q: VIDIOC_STREAMON error 28, No space left on device ,after i tried the common solution on the web I have a depth camera(XTION2).
i can successfully get the image stream by the following code:
roslaunch openni2_launch openni2.launch
rosrun image_view image_view image:=/camera/depth/image_raw

but when i tried output my rgb image stream by the following code
roslaunch openni2_launch openni2.launch
rosrun image_view image_view image:=/camera/rgb/image_raw

I got an error message:
VIDIOC_STREAMON error 28, No space left on device

I tried some common solutions to solve this problem like:
sudo rmmod uvcvideo
sudo modprobe uvcvideo quirks=640

or
sudo rmmod uvcvideo
sudo modprobe uvcvideo quirks=128

but it still doesn't work.
my ubuntu version is "16.04"
Here's the output of "lsusb"
Bus 002 Device 032: ID 0b05:182c ASUSTek Computer, Inc.
Bus 002 Device 031: ID 0b05:182d ASUSTek Computer, Inc.
Bus 002 Device 030: ID 0bda:0401 Realtek Semiconductor Corp.
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 005: ID 0cf3:e007 Atheros Communications, Inc.
Bus 001 Device 004: ID 0bda:0129 Realtek Semiconductor Corp. RTS5129 Card Reader Controller
Bus 001 Device 003: ID 0bda:5769 Realtek Semiconductor Corp.
Bus 001 Device 011: ID 046d:c52f Logitech, Inc. Unifying Receiver
Bus 001 Device 016: ID 0bda:5401 Realtek Semiconductor Corp. RTL 8153 USB 3.0 hub with gigabit ethernet
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Here's the output of "lsusb -t" when i plug in my xtion2 camera
/:  Bus 02.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/6p, 5000M
    |__ Port 1: Dev 30, If 0, Class=Hub, Driver=hub/4p, 5000M
        |__ Port 1: Dev 31, If 0, Class=Video, Driver=uvcvideo, 5000M
        |__ Port 1: Dev 31, If 1, Class=Video, Driver=uvcvideo, 5000M
        |__ Port 1: Dev 31, If 2, Class=Audio, Driver=snd-usb-audio, 5000M
        |__ Port 1: Dev 31, If 3, Class=Audio, Driver=snd-usb-audio, 5000M
        |__ Port 2: Dev 32, If 0, Class=Video, Driver=uvcvideo, 5000M
        |__ Port 2: Dev 32, If 1, Class=Video, Driver=uvcvideo, 5000M
/:  Bus 01.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/12p, 480M
    |__ Port 1: Dev 16, If 0, Class=Hub, Driver=hub/4p, 480M
    |__ Port 3: Dev 11, If 0, Class=Human Interface Device, Driver=usbhid, 12M
    |__ Port 3: Dev 11, If 1, Class=Human Interface Device, Driver=usbhid, 12M
    |__ Port 5: Dev 3, If 0, Class=Video, Driver=uvcvideo, 480M
    |__ Port 5: Dev 3, If 1, Class=Video, Driver=uvcvideo, 480M
    |__ Port 6: Dev 4, If 0, Class=Vendor Specific Class, Driver=rtsx_usb, 480M
    |__ Port 7: Dev 5, If 0, Class=Wireless, Driver=btusb, 12M
    |__ Port 7: Dev 5, If 1, Class=Wireless, Driver=btusb, 12M

Can anyone help me fix this issue?please help me,thanks very much!

A: i fix this issue occasionally.
after run the following code
sudo rmmod uvcvideo
sudo modprobe uvcvideo quirks=640

I pluged my xtion2 device into my computer through the port of usb2.0 from usb 3 port, and it suddenly worked. I don't konw why.


text:
Q: Can't access to mail attachments in mail app via apple script Let's assume that in the following code
tell application "Mail"
    tell first account
        tell first mailbox
            set myMessage to first message
            set myAttachment to mail attachments of myMessage
        end tell
    end tell
end tell

the first message of the first mailbox of the first account actually has attachments. Let's further assume that the account in question is a GMail account (maybe that proves relevant) and that I am trying this on El Capitan.
On the "set myAttachments" line I always get the error "error in apple event routine, -10000" (losely translated from German). I have read in old threads that there was indeed a bug in the access to attachments. But I also saw a new thread that was talking specifics about how to best handle them (no mentioning of having no access at all).
What am I missing? Does it work? Maybe in general but not with GMail? Do I have to do something specific?
Thanks!
Sandro

A: The exact syntax for this is "mail attachement of myMessage" (without "s").
The script bellow is working perfectly on my side for selected emails:
tell application "Mail"
activate
set ListMessage to selection
repeat with aMessage in ListMessage
    set AList to every mail attachment of aMessage
    repeat with aFile in AList
        if (downloaded of aFile) then
            -- do something with aFile
        end if
    end repeat -- next file
end repeat -- next message
end tell

Are you sure the the message with attachement is in your first account/first mailbox?


text:
Q: Java - Why do we use the "this" keyword in constructors? I've tried to look around but it's hard searching for "this." But I just can't seem to grasp the difference between these two
public class x{
int y = 0;
int z = 0;

x(int y, int z){
    y = y;
    z = z
    }
}

and
public class x{
int y = 0;
int z = 0;

x(int y, int z){
    this.y = y;
    this.z = z;
   }
}

A: When you write
y = y;
z = z;

You're just assigning the local variables to themselves, and not touching the instance variables at all.  Since y refers to a local variable, you have to write this.y to refer to the instance variable that you want to assign.
You can help to catch mistakes like this by making your variables final if they aren't meant to be modified.  For example:
x(final int y, final int z) {
    this.y = y;
    this.z = z;
}

If you take away the this. prefixes, you'll get a compile error because the local variables y and z can't be changed.

A: In Java, the this keyword represents the current instantiation of the class. So when you create an object:
x obj = new x();

x has two "instance" (not local) variables y and z.
If your class also has methods that contain local variables of the same name, then how can the Java Runtime environment (the computer) know which y and z you are referring to? For example:
x(int y, int z){
    y = y; //Both z are just the local variables
           //of this method and don't change the class.
    z = z; //Both z are just the local variables and dont affect class object
}

But if you do the following, then you change the objects y value but not its z value:
x(int y, int z){
    this.y = 50; //call this function sets the objects y value to 50
    z = z; //But nothing happens to the objects z value because the
           //Java Runtime enviornment sees the z and finds its nearest
           //scope which is the method its defined in and thus the local
           //variable gets set to itself and then deleted after the method
           //is called and the object's z value is not changed.
}


text:
Q: How do I get the debugger to recognize the sourcemaps in webstorm 10 using the react starter kit I created a sample react starter kit project in webstorm using webstorm's pre-defined project template and am trying to set breakpoints in debug mode.
I first built the project using npm run build then set the debug configuration to run build/server.js.
However it won't recognize any of the breakpoints in the original source files and seems to be ignoring the sourcemaps.  How can I get it to recognize the sourcemaps and allow me to both set breakpoints in the source files as well as step into the source files.
There is this issue in the react starter kit repo: https://github.com/kriasoft/react-starter-kit/issues/121 but I couldn't see what the resolution was, and unlike the commenter, I couldn't even get it to step into the source files... it just stayed on the generated js files instead.

A: Well...
WebStorm 10 has no support for sourcemaps generated by Webpack. They are partially supported in WebStorm 11 for client-side applications (see http://blog.jetbrains.com/webstorm/2015/09/debugging-webpack-applications-in-webstorm/), but not supported for Node.js.
so, you can't debug server.js in WebStorm 11, but you can debug client side. To do this, try the following:
change appConfig in src/config.js as follows:
const appConfig = merge({}, config, {
  entry: [
    ...(WATCH ? ['webpack-hot-middleware/client'] : []),
    './src/app.js',
  ],
  output: {
    path: path.join(__dirname, '../build/public'),
    filename: 'app.js',
  },
devtool: 'source-map',
module: {
    loaders: [
      WATCH ? {
        ...JS_LOADER,
        query: {
          // Wraps all React components into arbitrary transforms
          // https://github.com/gaearon/babel-plugin-react-transform
          plugins: ['react-transform'],
          extra: {
            'react-transform': {
              transforms: [
                {
                  transform: 'react-transform-hmr',
                  imports: ['react'],
                  locals: ['module'],
                }, {
                  transform: 'react-transform-catch-errors',
                  imports: ['react', 'redbox-react'],
                },
              ],
            },
          },
        },
      } : JS_LOADER,
      ...config.module.loaders,
      {
        test: /\.css$/,
        loader: 'style-loader/useable!css-loader!postcss-loader',
      },
    ],
  },
});

set up the javascript debug run configuration:
URL: http://localhost:5000
Remote URLs: map project root folder to 'webpack:///path/to/react-starter-kit', like 'webpack:///C:/WebstormProjects/react-starter-kit'
map build/public to http://localhost:5000
This doesn't work perfectly, but works in general - breakpoints in src/routes.js, src/app.js are hit


text:
Q: Get virtual machine created time on Azure using Python API My requirement is to get all VMs in a subscription with launch(created) time. I didn't find the VM created time in the dashboard where as in the Activity log found a timestamp. I would like to fetch all VMs which were created by one subscription id along with created time.
(For this account details 2FA is enabled so -  UserPassCredentials won't work )
List of all VMs in a subscription id:
import os
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.compute import ComputeManagementClient
subscription_id = os.environ['AZURE_SUBSCRIPTION_ID']
credentials = ServicePrincipalCredentials(client_id=os.environ['AZURE_CLIENT_ID'], secret=os.environ['AZURE_CLIENT_SECRET'], tenant=os.environ['AZURE_TENANT_ID'])
compute_client = ComputeManagementClient(credentials, subscription_id)
for vm in compute_client.virtual_machines.list_all():
    print("\tVM: {}".format(vm.name))

Fetch created time from Activity log:
import os
import datetime
from pprint import pprint
from azure.monitor import MonitorClient
from azure.common.credentials import ServicePrincipalCredentials

today = datetime.datetime.now().date()
filter = " and ".join([ "eventTimestamp le '{}T00:00:00Z'".format(today), "resourceGroupName eq 'test-group'" ])
subscription_id = 'xxxxx'
credentials = ServicePrincipalCredentials(client_id=os.environ['AZURE_CLIENT_ID'], secret=os.environ['AZURE_CLIENT_SECRET'], tenant=os.environ['AZURE_TENANT_ID'])
client = MonitorClient(credentials, subscription_id)
select = ",".join([ "Administrative", "Write VirtualMachines" ])
activity_logs = client.activity_logs.list( filter=filter, select=select )

for i in activity_logs:
    pprint(i.__dict__)

I'm able to get the all VMs(1st sample program), However while trying to fetch the Activity log get some error(2nd sample program).
Error:
    Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/msrest/paging.py", line 109, in __next__
    self.advance_page()
  File "/Library/Python/2.7/site-packages/msrest/paging.py", line 95, in advance_page
    self._response = self._get_next(self.next_link)
  File "/Library/Python/2.7/site-packages/azure/monitor/operations/activity_logs_operations.py", line 117, in internal_paging
    raise models.ErrorResponseException(self._deserialize, response)
azure.monitor.models.error_response.ErrorResponseException: Operation returned an invalid status code 'Bad Request'

Can somebody help me to find the issue please? any help really appreciated.

A: I tried to fetch my active log of resource group today by using the code you provided and I reproduce your issue.
My code:
import os
import datetime
from pprint import pprint
from azure.monitor import MonitorClient
from azure.common.credentials import ServicePrincipalCredentials

subscription_id = '***'
client_id='***'
secret='***'
tenant='***'

today = datetime.datetime.now().date()
filter = " and ".join([ "eventTimestamp le '{}T00:00:00Z'".format(today), "resourceGroupName eq 'jay'" ])

credentials = ServicePrincipalCredentials(client_id=client_id, secret=secret, tenant=tenant)

client = MonitorClient(credentials, subscription_id)
select = ",".join([ "eventName", "operationName" ])

print select
print filter
activity_logs = client.activity_logs.list( filter=filter, select=select )

for log in activity_logs:
    # assert isinstance(log, azure.monitor.models.EventData)
    print(" ".join([
        log.event_name.localized_value,
        log.operation_name.localized_value
    ]))

Running result:
eventName,operationName
eventTimestamp le '2017-10-17T00:00:00Z' and resourceGroupName eq 'jay'
Traceback (most recent call last):
  File "E:/PythonWorkSpace/ActiveLog/FetchActiveLog.py", line 24, in <module>
    for log in activity_logs:
  File "E:\Python27\lib\site-packages\msrest\paging.py", line 109, in __next__
    self.advance_page()
  File "E:\Python27\lib\site-packages\msrest\paging.py", line 95, in advance_page
    self._response = self._get_next(self.next_link)
  File "E:\Python27\lib\site-packages\azure\monitor\operations\activity_logs_operations.py", line 117, in internal_paging
    raise models.ErrorResponseException(self._deserialize, response)
azure.monitor.models.error_response.ErrorResponseException: Operation returned an invalid status code 'Bad Request'

After rearching the Azure Monitor Python SDK, I found the difference.
filter = " and ".join([ "eventTimestamp ge '{}T00:00:00Z'".format(today), "resourceGroupName eq 'jay'" ])

Here is ge ,not le.
I modify the keyword then the code works well for me.
eventName,operationName
eventTimestamp ge '2017-10-17T00:00:00Z' and resourceGroupName eq 'jay'
End request Microsoft.Compute/virtualMachines/delete
End request Microsoft.Compute/virtualMachines/delete
End request Microsoft.Compute/virtualMachines/delete
Begin request Microsoft.Compute/virtualMachines/delete
End request Microsoft.Compute/virtualMachines/deallocate/action
End request Microsoft.Compute/virtualMachines/deallocate/action
Begin request Microsoft.Compute/virtualMachines/deallocate/action
End request Microsoft.Compute/virtualMachines/write
End request Microsoft.Compute/disks/write
End request Microsoft.Compute/virtualMachines/write
End request Microsoft.Network/networkSecurityGroups/write
End request Microsoft.Network/networkInterfaces/write
End request Microsoft.Network/publicIPAddresses/write

Hope it helps you.

A: Based on the doc, it seems your date should be escaped. Moreover, seems they take a datetime (and not a date):
https://learn.microsoft.com/en-us/rest/api/monitor/activitylogs
filter = " and ".join([
        "eventTimestamp le '{}T00:00:00Z'".format(today),
        "resourceGroupName eq 'test-group'"
])

A: Call az cli from python
use below command
az vm list

This will list json data with fields and you can filter
date = vm['timeCreated']

//"timeCreated": "2022-06-24T14:13:00.326985+00:00",


text:
Q: Javascript callback on a file uploader Here is an example of how to create a FileUpload button in javascript (from w3schools, but it's pretty generic).
function myFunction() {
    var x = document.createElement("INPUT");
    x.setAttribute("type", "file");
    document.body.appendChild(x);
}

To get at the file(s) itself we must use the files[] property of the button, but I believe a callback must be used.  While I understand the concept of callbacks in principle, I'm not sure how to apply it to this situation.  Only one file will be uploaded in my case, but feel free to give the general answer.
Basically, when I try to grab the files[0] it generates an error when the file picker launches without waiting to complete.  That's why I think a callback is needed.
Thanks.
UPDATE:
Here is some code that doesn't work.  It's just two files added to the above.  There are no error messages, the file picker comes up, and "File contents: undefined" is logged when the picker comes up.
var x = document.createElement("INPUT");
x.setAttribute("type", "file");
document.body.appendChild(x);
x.click();
console.log("File contents: " + x.files[0]);

My only real goal here is to get it so the last line works instead of showing undefined.  I.e. I have the actual file.

A: The code you are using creates an input tag which does not have multiple attribute set. In your case you would not get an array but just a single file object.
To enable multiple selections you need to set multiple attribute.
You could try this
function myFunction() {
  var x = document.createElement("INPUT");
  x.setAttribute("type", "file");
  x.setAttribute("multiple", "multiple");
  document.body.appendChild(x);
}

To read the selected file
There are basic ways to read the user selected file
1. Post the form inwhich case you will get the file in POST params
2. Get a reference to INPUT tag and then access the selected file
To upload a file you should generally go with the second option and you can do that as follows.
var inputTag = document.querySelectorAll('input'); // querySelectorAll returns an array so you will need to access the tag with proper index
var selectedFile = inputTag[0].files;// you will find the selected file in **files** property of the inputTag.

To read the selected file contents you need to use FileReader. For a complete example on how to use it here is a great tutorial.
Hope this helps.


text:
Q: Use CSS to move a button in html page I have the following button in html code:
<button type="button" id="acp-toggle-toolbar" class=" toolbar-left" style="top: 25px;"></button>

            <button id="acp-close-toolbar">
                Close the accessibility toolbar

            </button>

I need to move the button down.
I tried the following with no luck.
.toolbar-left img:style {
    top: 105px;
   }

My website is https://apostolosloukas.org/ and it's the accessibility button on the upper left.

A: You have inline-css that says: top: 25px, this is overriding your class code. In order to fix this, remove the inline css.
You can also add !important, in your class code.

A: You can use !important to override inline styles:
.toolbar-left {
  top: 105px !important;
}

This is widely considered bad practice and should only ever be used in situations where no other way of solving the problem is available.
On top of that, the current top: 25px affects the surrounding button, not the img.
The other issue is that there is no pseudo selector :style in CSS. Just get rid of it.
This is the result of my suggestion:


text:
Q: $f$-factors and fractional $f$-factors and odd cycles For a graph $G=(V,E)$ and a nonnegative integer valued function $f$ defined on $V$, an $f$-factor of $G$ is a spanning subgraph $F\subseteq G$ such that $d_F(v)=f(v)$ for all $v\in V$. A fractional $f$-factor is a function $h:E\to [0,1]$ such that for any vertex $v\in V$, $\sum_{\{e|e=uv\}}h(e)=f(v)$.
Let $G=(V,E)$ be a graph such that every pair of vertex disjoint odd cycles in $G$ are connected by an edge and let $f:V\to \mathbb{N}_0$ be a function such that $\sum_{v\in V}f(v)\equiv0\mod 2$. Prove that $G$ has an $f$-factor if and only if $G$ has a fractional $f$-factor.
I have almost nothing. I've started in the one direction: suppose that $G$ has a fractional $f$ factor $h$. Then for any vertex $v$, $\sum_{\{e|e=uv\}}h(e)\leq d_G(v)$, so there are at least enough edges.
But that's all I have and I am so stumped. I have no idea how to utilize the assumption that vertex disjoint odd cycles are connected.
Can anyone help with this?

Edit
As a commenter pointed out, the one direction is simple. Given an $f$-factor $F$ we can simply form a fractional $f$-factor $$h(uv)=\begin{cases} 1 & uv\in E(F) \\ 0 & \text{otherwise} \end{cases}$$
But the other direction is still a mystery.


text:
Q: Pycharm can't connect to mysql: Access denied I am working on ubuntu 18.04. My pycharm version is:
PyCharm 2022.1 (Community Edition)
Build #PC-221.5080.212, built on April 12, 2022
Runtime version: 11.0.14.1+1-b2043.25 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.
Linux 4.15.0-175-generic
GC: G1 Young Generation, G1 Old Generation
Memory: 1972M
Cores: 12
Current Desktop: ubuntu:GNOME
When I am trying to connect  with mysql using the following program:
import pymysql

conn = pymysql.connect(host='localhost',
                       user='root',
                       password='',
                       database='db',
                       charset='utf8mb4',
                       cursorclass=pymysql.cursors.DictCursor)
cursor = db.cursor()

I am getting the following errors:
> File "/home/user/PycharmProjects/pythonProjectDB/main2.py", line 9,
> in <module>
>     cursorclass=pymysql.cursors.DictCursor)   File "/home/user/PycharmProjects/pythonProjectRev/venv/lib/python3.6/site-packages/pymysql/connections.py",
> line 353, in __init__
>     self.connect()   File "/home/user/PycharmProjects/pythonProjectRev/venv/lib/python3.6/site-packages/pymysql/connections.py",
> line 633, in connect
>     self._request_authentication()   File "/home/user/PycharmProjects/pythonProjectRev/venv/lib/python3.6/site-packages/pymysql/connections.py",
> line 907, in _request_authentication
>     auth_packet = self._read_packet()   File "/home/user/PycharmProjects/pythonProjectRev/venv/lib/python3.6/site-packages/pymysql/connections.py",
> line 725, in _read_packet
>     packet.raise_for_error()   File "/home/user/PycharmProjects/pythonProjectRev/venv/lib/python3.6/site-packages/pymysql/protocol.py",
> line 221, in raise_for_error
>     err.raise_mysql_exception(self._data)   File "/home/user/PycharmProjects/pythonProjectRev/venv/lib/python3.6/site-packages/pymysql/err.py",
> line 143, in raise_mysql_exception
>     raise errorclass(errno, errval) pymysql.err.OperationalError: (1698, "Access denied for user 'root'@'localhost'")

My mysql version is:
mysql> select version();
+-------------------------+
| version()               |
+-------------------------+
| 5.7.37-0ubuntu0.18.04.1 |
+-------------------------+
1 row in set (0.00 sec)

Created databases are:
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| db                 |
| menagerie          |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

Somebody please guide me.
Zulfi.

A: lThe traceback (read bottom-up) error "raise errorclass(errno, errval) pymysql.err.OperationalError: (1698, "Access denied for user 'root'@'localhost'")" says that local user root was denied access to the database server.
Were you running your queries as root or with sudo? Why. Don't be confused between the system manager account root and the MySql "root" user.
See https://serverpilot.io/docs/how-to-access-mysql-with-the-mysql-root-user/and read man mysql mysqld.


text:
Q: Restore interactive commands after accidentally overpaging pipe input to less? Consider a script like this:
$ cat example.sh
#! /usr/bin/env bash

for i in {1..90}
do
    printf '%s\n' "$i"
done
sleep 10
printf '91\n'
sleep 10
printf 'done\n'

and suppose the output is piped to less, like so:
$ bash example.sh | less

If I scroll down as far as line 90,
I can scroll back up again, search,
and use any other interactive commands that less provides.
However, as soon as I try to go past line 90 with e.g. j or Ctrl-N,
less stops responding to interactive commands
until another line of input is available.
And if I try to scroll a full pageful past line 90 with e.g. spacebar,
less stops responding to interactive commands
until a full page of input is available
or it receives EOF.
This can be undesirable if I want to look at previous output
and don't realize I have just gone over the available lines
and must wait for more lines to appear,
which could require an arbitrary amount of time.
If I use Ctrl-C to send SIGINT,
I can immediately get interactivity again,
but then less will stop listening for more input from the pipe.
The script is just an easily reproducible example,
but it could be replaced by any long-running command
that slowly generates lines of output, such as finding broken symbolic links:
$ find $HOME -xtype l | less

or world-readable permissions in my home directory:
$ find $HOME -perm 777 | less

or any number of other slow, resource-intensive commands that send lines to stdout.
Is there any way I can tell less to stop waiting for more input
and regain interactive commands
without waiting for the required lines of input
to be generated from the pipe?

A: In
bash example.sh | less

The whole pipeline is put in foreground (the foreground process group has both the process running bash and all the processes it spawns itself,  and less), so when you press Ctrl + C, all of bash, sleep and less receive the SIGINT.
sleep will die upon receiving it, so will bash¹. less intercepts that SIGINT where it's handled as cancel current action.
But if bash hadn't died, you would have been able to resume reading inside less.
So what you can do is prevent bash from dying of SIGINT:
(trap '' INT; bash example.sh) | less

Then you'll be able to use Ctrl + C to interrupt less without affecting bash and the processes launched by that script.
To stop the script, you can use Ctrl + \ which sends a SIGQUIT (beware it may cause a core dump if you haven't set the core dump size limit to 0), or Ctrl + Z to suspend the job (SIGTSTP) followed by kill % to kill it (with SIGTERM).

¹ here, as bash realised sleep died of a SIGINT; it would have been different if sleep had handled that SIGINT and exited normally, that's a special SIGINT handling done by bash and a a few other shells.

A: If I understand your question correctly, your desired behavior is to interrupt sleep and return to the interactive vim-like mode with : .
The answer lies in how the sleep functionality is handled, as sleep is not a regular shell command in itself, but a pretty special command that creates a dummy job that executes for a specific time, and accordingly this has to be taken into account with regards to interrupt handling. However, your behavior can be easily achieved by modifying your script as such.
#!/bin/bash

trap 'kill $(jobs -p)' INT

for i in {1..90}
do
    printf '%s\n' "$i"
done

sleep infinity &
wait

printf '91\n'

sleep 10 &
printf 'done\n'

I modified your original script a little so it sleeps for infinity for testing.
When you reach and then attempt to move past line 90, the sleep engages and runs forever. In order to exit it just hit CTRL+C , which thanks to the signal trap will not only interrupt our sleep job but give you back the desired : and its functionality (you may need to press a key after executing CTRL+C). Additionally, once you again try to move past line 90, line 91 will be printed immediately, as the script execution has moved past the first sleep job.

A: The least bad solution is to use setsid(1):
setsid bash example.sh | less

or
setsid find $HOME -xtype l | less

or
setsid find $HOME -perm 777 | less

"Least bad" both because setsid(1) as a command is a non-standard Linux-ism, so you will need to install it from your nearest package manager if it is not already available (it has the fact it's portable going for it), and because the command in question will escape job control as well, so if it gets really stuck you will have no choice but to locate it in ps x and use the kill command manually with the located PID.
There are alternatives, but they have their own portability or ergonomic headaches. cf: https://unix.stackexchange.com/a/736048/54340


text:
Q: Getting a 500 Internal Server Error when rewriting 2 specific URLs I keep getting a 500 internal server error when trying to rewrite these one specific URLs/files (item.php & purchase.php), the rest works.
I have tried many ways to fix this but nothing seemed to work, which is weird because all other URLs do work, but these 2 just seem to not want to work for some reason.
.htaccess file
Options -Indexes
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

ErrorDocument 500 "500"
ErrorDocument 404 "404"
ErrorDocument 403 "403"

RewriteRule ^users/([^/]*)$ /user/profile.php?username=$1
RewriteRule ^users/([^/]*)/inventory$ /user/GetUserInventory.php?username=$1

RewriteRule ^market/item/([^/]*)$ /market/item.php?id=$1
RewriteRule ^market/item/([^/]*)/purchase$ /market/purchase.php?id=$1

RewriteRule ^community/([^/]*)$ /communities/view.php?id=$1
RewriteRule ^community/([^/]*)/join$ /communities/join.php?id=$1
RewriteRule ^community/([^/]*)/manage$ /communities/manage.php?id=$1

RewriteRule ^game/([^/]*)$ /games/view.php?id=$1

item.php
<?php
    include_once('../private/header.php');
    $item = $handler->query("SELECT * FROM items WHERE id=" . $_GET['id']);
    $gB = $item->fetch(PDO::FETCH_OBJ);

    echo '

    image.'.png" class="responsive-img">

'.$gB->name.'
    '.$gB->type.'

'.$gB->description.'

    ';

    if ($gB->onsale == 1){
        echo 'id.'/purchase" class="modal-trigger waves-effect waves-light btn green">Purchase';
    } else {
        echo 'Offsale';
    }

    echo '

    Creator
    creator.'" style="padding-top:12px;font-size:16px;display:inline-block;">'.$gB->creator.'
    ';

    if($gB->collectable == 'true'){
        if($gB->amount == 0)
            echo '
            Sold Out
            ';
        }else{
            echo '
            '.$gB->amount.' Remaining
            ';
    }

    echo '

'.$gB->created.'

Time Created

'.$gB->created.'

Last Updated

???

Owners

    ';

    include_once('../private/footer.php');

purchase.php
<?php
    include_once('../private/config.php');

    if ($user){
        $money=$myu->CurrencyCoins;
        $id=$_GET['id'];
        $item = $handler->query("SELECT * FROM items WHERE id=" . $id);
        $gB = $item->fetch(PDO::FETCH_OBJ);
        $amount=$gB->amount;

        if ($gB->onsale == 1){
            if ($money >= $gB->price){
                if ($gB->collectable != "true"){
                    if ($amount != 0){
                        $new = ($money - $gB->price);
                        $handler->query("UPDATE `users` SET `CurrencyCoins`='".$new."' WHERE `id`='".$myu->id."'");
                        $handler->query("INSERT INTO inventory (item,user) VALUES (".$id.",".$myu->id.")");
                    }
            } else {
                if ($amount >= 1){
                    $amount1=($amount - 1);
                    $new = ($money - $gB->price);
                    $handler->query("UPDATE `users` SET `CurrencyCoins`='".$new."' WHERE `id`='".$myu->id."'");
                    $handler->query("UPDATE `items` SET `amount`='".$amount1."' WHERE `id`='".$gB->id."'");
                    $handler->query("INSERT INTO inventory (item,user) VALUES (".$id.",".$myu->id.")");
                } else {
                    echo '
Item is sold out!
';
                }
                }
            }
        } else {
        echo '
Item not on sale!
';
        }
    }

    echo '<meta http-equiv="refresh" content="1; url='.$serverUrl.'/account/character">';

A:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

These directives should be at the end of your .htaccess file, after the other rewrites. They are also incorrect - although by placing them at the end of the file it will avoid the immediate issue, but could still cause problems with other URLs.
In its current state, when you request example.com/market/item/1 (where it would seem, /market is a physical directory, and /item.php is a file in that directory) then...
In brief... it results in an endless rewrite loop:
/market/item/1.php
/market/item/1.php.php
/market/item/1.php.php.php
/market/item/1.php.php.php.php
etc.

Which breaks (after 10 iterations) with a 500 response being sent to the browser.
A very similar process happens when requesting /market/item/1/purchase:
/market/item/1/purchase.php
/market/item/1/purchase.php.php
/market/item/1/purchase.php.php.php
/market/item/1/purchase.php.php.php.php
etc.

In detail...

*

*REQUEST_FILENAME is /market/item (ignoring the directory-prefix) and PATH_INFO is /1 (important for later). /market/item is not a directory (1st condition), but /market/item.php is a file (2nd condition) - so both conditions are successfully met.

*The RewriteRule directive then rewrites /market/item/1 to /market/item/1.php (clearly incorrect and not the intention). Since there is no L flag on this rule, processing continues... for the sake of the remaining rules, the PATH_INFO (from the initial request, /1) is appended to the resulting URL to become /market/item/1.php/1 (the DPI flag - discard path info - was created to prevent this specific behaviour).

*/market/item/1.php/1 does not match any further rules in the current pass, so the rewrite engine starts over at the top with /market/item/1.php.

*REQUEST_FILENAME is again /market/item and PATH_INFO is now /1.php. /market/item is not a directory (1st condition), but /market/item.php is a file (2nd condition) - so both conditions are successfully met a second time.

*The RewriteRule directive then rewrites /market/item/1.php to /market/item/1.php.php. Since there is no L flag on this rule, processing continues... for the sake of the remaining rules, the PATH_INFO (from the request, /1.php this time) is appended to the resulting URL to become /market/item/1.php.php/1.php.

*/market/item/1.php.php/1.php does not match any further rules in the current pass, so the rewrite engine starts over at the top with /market/item/1.php.php.

*GOTO #4 (with updated URL-path) etc. etc. etc. rewrite loop, 500 error.
And a very similar process happens when requesting /market/item/1/purchase. The REQUEST_FILENAME is the same /market/item (so it again checks that /market/item.php exists, not purchase.php), except that the PATH_INFO is /1/purchase (not /1). And the initial URL-path that the .php extension is appended to is naturaly /market/item/1/purchase (not /market/item/1).
Fix
If you've followed that "confusing muddle", you'll see that the condition that checks for the existence of the "path/to/file" + ".php" is not necessarily the same as the rule that actually rewrites the request to "URL-path" + ".php". ("path/to/file" is not the same as the "URL-path"). To fix this, it should be written as:
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule (.*) $1.php [L]

No real need for the directory check here, since if it was a directory, the file check that follows must fail (unless you have directory names that end in .php). The %{DOCUMENT_ROOT}/$1.php check is now effectively "the same" as $1.php (the file being rewritten to).
The literal dot does not need to be backslash escaped in the RewriteCond TestString - this is an "ordinary" string, not a regex.
Don't forget the L flag(s). And this rule block should now go at the end of the .htaccess file.
Summary
Options -Indexes
RewriteEngine on

ErrorDocument 500 "500"
ErrorDocument 404 "404"
ErrorDocument 403 "403"

RewriteRule ^users/([^/]*)$ /user/profile.php?username=$1 [L]
RewriteRule ^users/([^/]*)/inventory$ /user/GetUserInventory.php?username=$1 [L]

RewriteRule ^market/item/([^/]*)$ /market/item.php?id=$1 [L]
RewriteRule ^market/item/([^/]*)/purchase$ /market/purchase.php?id=$1 [L]

RewriteRule ^community/([^/]*)$ /communities/view.php?id=$1 [L]
RewriteRule ^community/([^/]*)/join$ /communities/join.php?id=$1 [L]
RewriteRule ^community/([^/]*)/manage$ /communities/manage.php?id=$1 [L]

RewriteRule ^game/([^/]*)$ /games/view.php?id=$1 [L]

# Append .php on remaining requests
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule (.*) $1.php [L]


text:
Q: How to use a jquery inside a boundfield? I'm using the below jQuery to add a "read more" option to a text so it only shows the first 200 characters and allows user to click on read more to view the remaining part of the text
<title>Add Read More Link (from DevCurry.com)</title>

To use the function, I have to use the following

     The Div Text Comes Here

My problem is that I want to use the jQuery inside a gridview boundfield. I have one column that contains a long description and need to apply the jQuery in it.
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
            AutoGenerateColumns="False" EmptyDataText="No Records" EnableSortingAndPagingCallbacks="True"
            Width="1017px" ShowFooter="False" DataSourceID="SqlDataSource1"
            EnableModelValidation="True" PageSize="10" GridLines="None" CssClass="mGrid"
            PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt"  >

        <Columns>
            <asp:BoundField DataField="CreationDate" HeaderText="Date" SortExpression="CreationDate"  dataformatstring="{0:MM/dd/yyyy}" />
            <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
            <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
            <asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />
            <asp:BoundField DataField="Department" HeaderText="Department" SortExpression="Department" />

        </Columns>

    </asp:GridView>

Unfortunately, I can't insert a  inside a boundfield. do you have any other way to apply the Jquery to the boundfield?

A: You could replace
<asp:BoundField DataField="Description" HeaderText="Description"
   SortExpression="Description" />

by
<asp:TemplateField HeaderText="Description" SortExpression="Description">
    <ItemTemplate>

<%# Eval("Description") %>

    </ItemTemplate>
</asp:TemplateField>

A: You can set a css-class and use that class in jQuery.
And you need to use TemplateField for displaying data.


text:
Q: How can I transfer files from Android to Ubuntu (and vice versa)? I've a phone (Huawei Mate 20 Lite) which runs Android (version 10) and I would like to transfer some songs, movies, documents, etc to my phone but I don't know the best way to do this.
I've done some research online but I've only found old ways that are no longer valid.
I'm currently using KDEconnect but this isn't (for me) the best way to transfer my stuff, as I have to establish the connection each time I want to transfer something, and it's a bit slow while transferring.
I wonder if it's possible to transfer files to an Android phone from Ubuntu desktop through USB connection.
I've also installed mtp-tools, but when I switch my phone to MTP and try to run the mtp-detect command, it doesn't detect anything.
What do you advise me?
(I'm on Ubuntu 20.04.1 LTS).
Thanks!

A: I think, wired is always better than wireless.
Just plug in your phone to the PC via USB cable. And then on the phone you will get a prompt saying Allow access to phone data?, or something similar to this (depending on the brand and model). Click allow or something similar to this (depending on the brand and model).
In file manager, your phone will be visible in the side tab. Alternately, it will also be visible in the favorites bar. Just click any of those and you are good to go.
I have attached a screenshot showing both the locations.

A: Try https://snapdrop.net/
Instructions to use snapdrop:

*

*Open https://www.snapdrop.net both in your PC and your smartphone. (Make sure that both the devices are connected to the same network.)

*The smartphone and the PC will be given a name by the website.
In my case, my PC is named as Coral Ferret and my smartphone is named as Gold Spoonbill.

*If I want to share a file from my PC to smartphone, I must click on Gold Spoonbill option in my PC. Then choose the files which needs to be shared.

*Then on your phone, you will get an option to download the file.

*Download the file. And that's it!
The steps will be similar even if you transfer files from smartphone to PC.

This might not be the best method (since best is subjective), but it's one of the easiest methods.

A: The most reliable way to transfer files between the phone and a PC is to use a MicroSD card, especially if you keep all of your files on the MicroSD card anyway.


text:
Q: Applications of Tits' alternative in number theory I have recently studying Tits' alternative. The theorem statement goes like the following:
Tits' alternative: Let $G$ be any finitely generated linear group over a field. Then one of the following is true,
$(1)$ $G$ contains a solvable normal subgroup of finite index,
$(2)$ $G$ contains a non-abelian free subgroup (of rank at least $2$).
I am in search of applications of this wonderful theorem in number theory. Any help, resources or reference will be appreciated. Thanks in advance.
The same question was asked by me in Mathoverflow. But due to lack of proper response, I posted it here.

A: I am not sure how broadly you interpret Number Theory (NT), but the following papers have NT as their primary Math Subject classification and quote Tits' Alternative:
Lubotzky, Alexander; Venkataramana, Tyakal Nanjundiah, The congruence topology, Grothendieck duality and thin groups, Algebra Number Theory 13 (2019), no. 6, 1281–1298, ZBL07103974.
Gao, Ziyang; Habegger, Philipp, Heights in families of abelian varieties and the geometric Bogomolov conjecture, Ann. Math. (2) 189, No. 2, 527-604 (2019). ZBL1432.11060.
Björklund, Michael, Small product sets in compact groups, Fundam. Math. 238, No. 1, 1-27 (2017). ZBL1427.11101.
Bourgain, Jean; Varjú, Péter P., Expansion in $SL_d(\mathbb Z/q\mathbb Z)$, $q$  arbitrary., Invent. Math. 188, No. 1, 151-173 (2012). ZBL1247.20052.
Vu, Van H.; Wood, Melanie Matchett; Wood, Philip Matchett, Mapping incidences, J. Lond. Math. Soc., II. Ser. 84, No. 2, 433-445 (2011). ZBL1234.05049.
Breuillard, Emmanuel, A height gap theorem for finite subsets of $GL_d(\overline{\mathbb{Q}})$ and nonamenable subgroups, Ann. Math. (2) 174, No. 2, 1057-1110 (2011). ZBL1243.11071.
Bourgain, Jean; Gamburd, Alex; Sarnak, Peter, Affine linear sieve, expanders, and sum-product, Invent. Math. 179, No. 3, 559-644 (2010). ZBL1239.11103.
Chang, Mei-Chu, Convolution of discrete measures on linear groups, J. Funct. Anal. 247, No. 2, 417-437 (2007). ZBL1130.22003.
Hajir, Farshid, On the growth of (p)-class groups in (p)-class field towers, J. Algebra 188, No. 1, 256-271 (1997). ZBL0879.11069.


text:
Q: The set of lines through a fixed point in $\mathbb{P}^3$ I am struggling to solve this question. I have to find the set of lines through a fixed point in $\mathbb{P}^3$ using $Gr(2,4)$. How can I show that this set is inside $Gr(2,4)$ and a subset in $\mathbb{P}^5$ defined by three independent linear equations using Plücker coordinates?
Since I have only learned about basic algebraic geometry, I have tried to solve this by finding a corresponding variety lying on $\mathbb{A}^3$. However, I have no idea how to go further from here. Also, I'd like to approach this question only using Plücker coordinates.


text:
Q: PXE automation installation Ubuntu 20.04 desktop I'm currently doing PXE automation installation Ubuntu 20.04 desktop. I'm following this guide https://www.laroberto.com/ubuntu-pxe-boot-with-autoinstall. but the guide is for Ubuntu live server image. I've successfully installed it, but when I tried to do it with Ubuntu 20.04 desktop this error occurred.

Here my configs.
    #cloud-config
autoinstall:
  version: 1
  apt:
    primary:
    - arches: [default]
      uri: http://mirrors.aliyun.com/ubuntu
  # The passwords are all 000000
  user-data:
    timezone: Asia/Shanghai
    disable_root: false
    chpasswd:
      list: |
        root:$6$UenIfx4J$MXuFvAbjNjwotUl6CtEtwC.1SnlPqMkBd7oHg02XZ1iNk97eMglUrRO1hQUVvOZEf3M/aEhgyrQ/gTDx4fizz/
  identity:
    hostname: ubuntu-desktop
    password: $6$exDY1mhS4KUYCE/2$zmn9ToZwTKLhCw.b4/b.ZRTIZM30JZ4QrOQ2aOXJ8yk96xpcCof0kxKwuX1kqLG/ygbJ1f8wxED22bTL4F46P0
    username: ubuntu
  keyboard: {layout: us, variant: ''}
  locale: en_US.UTF-8
  ssh:
    install-server: false

  storage:
    grub:
      reorder_uefi: False
    config:
    - {ptable: gpt, path: /dev/sda, wipe: superblock-recursive, preserve: false, name: '',
      grub_device: false, type: disk, id: disk-sda}
    - {device: disk-sda, size: 436870912, wipe: superblock, flag: boot, number: 1,
      preserve: false, grub_device: true, type: partition, id: partition-0}
    - {fstype: fat32, volume: partition-0, preserve: false, type: format, id: format-0}
    - {device: disk-sda, size: -1, wipe: superblock, flag: '', number: 2,
      preserve: false, type: partition, id: partition-1}
    - {fstype: ext4, volume: partition-1, preserve: false, type: format, id: format-1}
    - {device: format-1, path: /, type: mount, id: mount-1}
    - {device: format-0, path: /boot/efi, type: mount, id: mount-0}

  packages:
  - linux-generic-hwe-20.04-edge
  late-commands:
  - curtin in-target --target=/target -- wget -P /root/ http://10.0.0.4/tftp/bash/init.sh
  - curtin in-target --target=/target -- wget -P /root/ http://10.0.0.4/tftp/bash/network.sh
  - curtin in-target --target=/target -- bash /root/init.sh

default.
DEFAULT vesamenu.c32
MENU TITLE SPECTRUM PXE BOOT
TIMEOUT 300
ONTIMEOUT ubuntu-focal-autoinstall
PROMPT 0
NOESCAPE 1

LABEL ubuntu-focal-autoinstall
        MENU label Install Ubuntu Live Server - autoinstall
        KERNEL vmlinuz
        INITRD initrd
        APPEND root=/dev/ram0 ramdisk_size=150000 ip=dhcp url=http://192.168.75.163/tftp/ubuntu-20.04-live-server-amd64.iso autoinstall ds=nocloud-net;s=http://192.168.75.163/tftp/cloud-init-bios/ cloud-config-url=http://192.168.75.163/tftp/cloud-init-bios/meta-data

LABEL ubuntu-focal-install
        MENU label Install Ubuntu Live Server
        KERNEL vmlinuz
        INITRD initrd
        APPEND root=/dev/ram0 ramdisk_size=150000 ip=dhcp url=http://192.168.75.163/tftp/ubuntu-20.04-live-server-amd64.iso

LABEL ubuntu-desktop-autoinstall
        MENU label Install Ubuntu Desktop-Autoinstall
        KERNEL /u20.04D/vmlinuz
        INITRD /u20.04D/initrd
        APPEND root=/dev/ram0 ramdisk_size=150000 ip=dhcp url=http://192.168.75.163/tftp/ubuntu-20.04-desktop-amd64.iso autoinstall ds=nocloud-net;s=http://192.168.75.163/tftp/u20.04D/ cloud-config-url=/dev/null

LABEL ubuntu-focal-install
        MENU label Install Ubuntu Desktop
        KERNEL /u20.04D/vmlinuz
        INITRD /u20.04D/initrd
        APPEND root=/dev/ram0 ramdisk_size=150000 ip=dhcp url=http://192.168.75.163/tftp/ubuntu-20.04-desktop-amd64.iso


text:
Q: Why Maxwell Distribution of Velocities curve is Bell Shaped? Is there any intuitive and/or quantum mechanical reason behind it? Why Maxwell Distribution of Velocities curve is Bell Shaped?
Apart from mathematics,

*

*Is there any intuitive reason behind it?

*Is there any quantum mechanical reason behind it?

*Is there any explanation with which we can imagine the necessity of distribution to be Bell Shaped?


text:
Q: Creating a new table with data from tables of varying size Hi I have two tables one has a large number of orders with a column for date. The second table has one column labeled month and another with hours making for 12 rows in total. I want to make a new column by dividing the count of orders per month by the hours of that month from the second table.
In excel i'd simply countif orders that are in January from the first table and divide by the hours in January from the second.
I'm having trouble figuring out the best way to make this new table with calculated values from the existing tables.
Thanks for your time.
Below is  a picture of table 2. The first table is a standard dataframe with thousands of rows.

A: Two options.
You can use the "Append Query" and create a new table that is combining all of your data.
You can also use CALCULATE(SUM(table[field]), filter(table, table[field] = table[monthfield]) /SUM(table[field])
If you could give an example of what you have, I could definitely show you how to accomplish this.

Here is a link to the solution file. One by merging data, and one by using CALCULATE(SUM(),FILTER())
https://drive.google.com/file/d/1yxpv62Dnv8LSNW_mxibPfL0aCMrepoCU/view?usp=sharing


text:
Q: ggplot2: Leave one of the margins as default library(ggplot2)

#default
ggplot(iris,aes(Sepal.Length,Sepal.Width))+
  geom_point()

#modify margins
ggplot(iris,aes(Sepal.Length,Sepal.Width))+
  geom_point()+
  theme(plot.margin=grid::unit(c(1,1,1,1),"cm"))

Now I am trying to control some margins while others are left as default.
#doesn't work
ggplot(iris,aes(Sepal.Length,Sepal.Width))+
  geom_point()+
  theme(plot.margin=grid::unit(c(1,1,1,NULL),"cm"))

Using NA or NULL doesn't seem to work.

A: try this:
add_margin = function(...)  grid::convertUnit(theme_get()[["plot.margin"]] + margin(...), "cm")

 ggplot(iris,aes(Sepal.Length,Sepal.Width))+
   geom_point()+ theme(plot.margin = add_margin(l=2, unit="cm"))


text:
Q: GPG encryption in an ASP.NET C# Web application - No Public Key I have set-up Gpg4win on Windows Server 2008 R2 and the website is running .Net 4.5.
I'm using the Starksoft OpenPGP dll.
I've added the required public key to Gpg4win via remote desktop, however when testing in the browser I get the following in the browser:
gpg: EMAIL@EMAIL.COM: skipped: No public key gpg: [stdin]: encryption failed: No public key

I've tested locally on my machine and directly in GPA and Kleopatra on the server and the encryption is working correctly. This leads me to believe that the issue is with the public key being set-up via remote desktop and not being accessible to the application pool or similar.
I've tried copying the pubring.gpg, secring.gpg and trustdb.gpg in to a protected subfolder of the website as suggested somewhere (I forget where now) but this has not worked.
Any ideas how to set-up the public keys to be accessible to the IIS user?

A: Research
Continued research lead me to this SO question: Gpg encryption over web browser which then lead me down the lines of running it via cmd - Running Command line from an ASPX page, and returning output to page
Solution

*

*Export the required keys somewhere (in this case c:\public.key

*Create a page with the following code and execute it
System.Diagnostics.Process si = new System.Diagnostics.Process();
si.StartInfo.WorkingDirectory = "c:\\";
si.StartInfo.UseShellExecute = false;
si.StartInfo.FileName = "cmd.exe";
si.StartInfo.Arguments = "gpg --import c:\\public.key";
si.StartInfo.CreateNoWindow = false;
si.StartInfo.RedirectStandardInput = true;
si.StartInfo.RedirectStandardOutput = true;
si.StartInfo.RedirectStandardError = true;
si.Start();
string output = si.StandardOutput.ReadToEnd();
si.Close();

*The key now works :)

A: GnuPG looks for keyrings in user's home directory, and IIS is run by other user, most likely this is the reason. You can specify the exact path to public and secret keyrings via --keyring and --secret-keyring command line switches.


text:
Q: How to build a soundcloud like player? With the help of waveformjs.org I am able to draw waveform for a mp3 file. I can also use
wav2json to get json data for audio file hosted on my own server and I don't have to depend on soundcloud for that. So far so good. Now, the next challenges for me are

*

*To fill the color in waveform as the audio playing progresses.

*On clicking anywhere on waveform audio should start playing from that point.

Has anyone done similar? I tried to look into soundcloud js SDK but no success. Any pointers in this directions will be appreciated, thanks.

A: As to changing the color my earlier answer here may help:
Soundcloud modify the waveform color
As to moving the position when you click on the waveform you can do something like this:
Assuming you have a x position already from the click event adjusted relative to the canvas.
/// get a representation of x relative to what the waveform represents:
var pos = (x - waveFormX) / waveformWidth;

/// To convert this to time, simply multiply this factor with duration which
/// is in seconds:
audio.currentTime = audio.duration * pos;

Hope this helps!
Update
The requestAnimationFrame is optimized not only for performance but also power consumption as more and more users are on mobile devices. For this reason the browsers may or may not pause or reduce frame rate of rAF when in a different tab or when browser tab is invisible. This can cause a position based approach to render the waveform delayed or not at all when tab is switched.
I would recommend to always use a time based approach so neither FPS or other behavior will interrupt the drawing of the waveform.
You can force the waveform to be updated at the actual current time as luckily we can attach this to the currentTime property of the audio element.
In the rAF loop simply update the position like this using a "reversed" formula of the above:
pos = audio.currentTime / audio.duration * waveformWidth + waveformX

When the tab becomes visible again this approach will make sure the waveform continues based on the actual time position of the audio.


text:
Q: jQuery Ajax return multiple data I am using jQuery AJAX to return a string from PHP which consists of some JavaScript, PHP and HTML.
I can successfully do this with the following code:
header("Content-Type: text/html");
echo $content;

$.ajax({
    type: 'POST',
    url: url,
    data: data,
}).done(function(result) {

}).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(jqXHR, textStatus, errorThrown);
});

The problem I have now is that I want to return some other simple values along this string as well.
But if I use json_encode to send an array of these values, it will break my string and won't be successful.
How could I send one value as string (without json_encode) and some other values with json_encode? (so I don't json_encode my string)
EDIT1:
Here is formatting issue 1:
return 'autoOpenPopup: '.!empty($options["autoOpenPopup"]) ? $this->int_to_bool($options["autoOpenPopup"]) : $this->int_to_bool(false) . PHP_EOL .';

2:
return '.!isset($options["popupInit"]) ?

                $playerId.' = jQuery("#'.$wrapperId.'").hap(settings);

            ':'

                if(hasLocalStorage){

                    if(!localStorage.getItem("hap_popup_fixed")){
                        '.$playerId.' = jQuery("#'.$wrapperId.'").hap(settings);
                    }
                }else{
                    '.$playerId.' = jQuery("#'.$wrapperId.'").hap(settings);
                }

A: The best way is to json_encode your data and string together;
$data = array('some', 'array', 'elements');

$string = 'my string';

$data2 = array('more', 'data');

Then you combine all of them in one array:
$result  = array();
$result['data1'] = $data;
$result['string'] = $string;
$result['data2'] = $data2;

Finally json_encode the array:
echo json_encode($result);

Then you read the result in JS:
$.ajax({
    type: 'POST',
    url: url,
    data: data,
}).done(function(result) {
  var jsonResult = $.parseJSON
  var data1 = result.data;
  var data2 = jsonResult.data2;
  var str = jsonResult.string;

}).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(jqXHR, textStatus, errorThrown);
});

A: header('Content-type: application/json');
echo json_encode($data, true);

and in your $.ajax({...dataType:'json'});


text:
Q: Change tab colour based on cell value, runtime error On each tab of my workbook, cell I1 calculates Print if the tab should be printed (meets criteria)
I am trying to code each tab to look at I1 and change tab colour if I1 = "Print". All of the codes that I am trying end up resulting in a Runtime error 1004.
Can anyone see what is wrong with my code?
EDIT 1: The error is thrown up at
                .Color = RGB(255, 255, 102)
EDIT 2: I have switched to Calculate from Change. Thanks for that.
EDIT 3: I have two module codes in the same book which password protect/unprotect all tabs. Could this be interfering?
Sub protect_all_sheets()
top:
pass = InputBox("password?")
repass = InputBox("Verify Password")
If Not (pass = repass) Then
MsgBox "you made a boo boo"
GoTo top
End If
 For i = 1 To Worksheets.Count
 If Worksheets(i).ProtectContents = True Then GoTo oops
 Next
 For Each s In ActiveWorkbook.Worksheets
 s.Protect Password:=pass
 Next
 Exit Sub
 oops: MsgBox "I think you have some sheets that are already protected. Please unprotect all sheets then running this Macro."
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    MyVal = Range("I1").Text

    With ActiveSheet.Tab
        Select Case MyVal
            Case "Print"
                .Color = RGB(255, 255, 102)
            Case Else
                .ColorIndex = xlColorIndexNone
        End Select
    End With
End Sub

A: Worksheet_Change isn't triggered by calculations: you need Worksheet_Calculate
Private Sub Worksheet_Calculate()
    Me.tab.color = IIf(Me.Range("I1").value="Print",vbRed,vbWhite)
End Sub


text:
Q: SQL/SQLite retrieve list of devices belonging to users when users and devices are stored in same table with associations stored in another table Another case of being given a poorly designed, quite old database and told to extract useful information from it. I do speak a very little bit of SQL but this exceeds my knowledge. I quite frankly hit a wall.
So I've been given an SQLite DB which contains several tables. Of interest are the tables nodes and associations.
Table nodes contains all elements such as users, devices (which are PCs) but a whole lot more such as desk phone apparatus, office numbers, operating systems, basically everything and anything. Here a sample:
id       title          entity_type
-----------------------------------
1        user1          User
2        user2          User
3        pc1            Device
4        user3          User
5        pc2            Device
6        pc3            Device
7        pc4            Device
8        os1            OS
9        phon1          Phone
10       os2            OS
11       phon2          Phone
11       phon3          Phone

Table associations maps a device to a user, but also contains a LOT more garbage mappings, such as operating systems to PCs, phones to offices, etc.
id       parent         child
-----------------------------
1        3              1
2        5              2
3        6              4
4        7              4
5        3              8
6        5              8
7        6              10

So associations maps pc1 with user1, pc2 with user2, pc3 and pc4 with user3 but also os1 to pc1 and pc2, os2 to pc3 etc.
Thankfully users only have PCs, no other items are mapped to users.
I was asked to compile a list which shows all PCs and which user they are assigned to. Basically I need to get:
user1     pc1
user2     pc2
user3     pc3
user3     pc4

My idea was along the lines of:
SELECT nodes.id,title,parent
  FROM nodes
  INNER JOIN associations ON nodes.id = associations.child
  WHERE entity_type = "User"
  ORDER BY id;

So far, this gives me a list of all users and the parents (e.g. the PCs ID in nodes) which belong to them. I have no clue though how I could replace the parent, which right now is just a number refering to the ID in nodes, with the title of this item.
Any help?

A: You will need to use multiple joins to the same table - something like:
select user.title as user, pc.title as pc
from nodes as user
join associations as a on a.child=user.id
join nodes as pc on a.parent=pc.id
where user.entity_type = 'User'

Regarding the "parent+1 for notebooks" logic mentioned in the comments: If I understand correctly, when a PC's title is "mobile", it's a notebook, and the node with the next id is the real title.
select user.title as user, ifnull(nb.title, pc.title) as computer
from nodes as user
join associations as a on a.child=user.id
join nodes as pc on a.parent=pc.id
left join nodes as nb on pc.title='mobile' and nb.id = pc.id + 1
where user.entity_type = 'User'

Using a left join means that nb fields will all be null in the case that the pc title is not 'mobile', and populated when it is. The ifnull in the select should ensure the correct title is used for each row.

A: Here's a query that will extract all user to node relations.  It doesn't assume that users are only ever the child node:
select u.title, n.entity_type, n.title
  from nodes u
  join associations a
    on u.id in (a.parent, a.child)
  join nodes n
    on n.id <> u.id
   and n.id in (a.parent, a.child)
 where u.entity_type = 'User'


text:
Q: Uncaught TypeError: Cannot read property 'name' of undefined even it exist UPDATE TO SIMPLIFY THE QUESTION:
Problem accessing property by string index but works using keys
for(var i in this.props.data[this.props.activeMenu]){
    console.log(i, this.props.data[this.props.activeMenu][i]);
}

Outputs:
url /api/timekeeping
name Timekeeping
submenus Object {dtr: Object, schedules: Object}
id timekeeping

But I have error when calling console.log(i, this.props.data[this.props.activeMenu]['name']). name is a valid key since it was displayed when I checked the keys.

A:
Blockquote ut when I tried to access console.log(this.props.data['timekeeping']['name']), I got this error Uncaught TypeError: Cannot read property 'name' of undefined

I think you should use: console.log(this.props.data['timekeeping'].name).
Try it.


text:
Q: AutoCAD: Drag and Drop *.dwg files from my ListBox hosted in Palettset I'm hosting my .Net ListView control using PalettSet in AutoCAD 2012. The Tag property of ListView items holds the path to *.dwg files. I want to drag from ListView, while picking the dwg file using Item.Tag property and drop it on AutoCAD drawing area and I'm expecting the result would be the drawing would be inserted there just like we normally drag a *.dwg file and drop it on drawing area
I've read about Drag and Drop Blocks using Jig Class and I tried some sample code but using built-in Circle class.
Do I have to first read Blocks from dwg file and then attached to mouse and do the drag and drop operation?
I'm actually confused...
Can someone please guide me? Would really appreciate your replies...
Thanks a bunch....
Farrukh

A: Finally I solved this, but after some long research and code testing. I wrote code (by reading multiple blogs) which would insert the Block from *.dwg file into current AutoCAD document, but then I realize that many Blocks contains Attributes and some might need to be handled while adding dwg.
So finally, I decided to call INSERT command of AutoCAD, instead writing my own code. Here is the code for other fellows.
Please note that here I'm making it an example while hard-coding dwg file name and path, while in my real application, DWG file path would be read from ListBox.Tag property.
[CommandMethod("InsertDWG")]
static public void SendCmd()
{
    string DWGFile = @"D:\sym\1047.DWG";
    string InsertCmd = @"_.-INSERT " + DWGFile + '\r' + '\n';
    Document doc = Application.DocumentManager.MdiActiveDocument;
    doc.SendStringToExecute(InsertCmd, true, false, false);
}

Note: You should keep  '\r' + '\n' (Will act as Enter or Carriage Return) with SendStringToExecute() method, or AutoCAD would get the command string, but will wait for user input.
Hope this would be beneficial for someone.
Best regards
Farrukh


text:
Q: Quantum coherence and decoherence In Quantum Mechanics coherent states are defined as eigenstates to some annihilation operator. Afaik this notion is due to Roy Glauber.
Now, I just read that if you have a spin-state for example, then the coherence of the spin-state is measured by the off-diagonal elements of the density matrix. This meant that there is no coherence if the off-diagonal entries are zero, because then I have just spin-up or spin-down.
Are these two notions related to each other, cause I currently don't see it.
If anything is unclear, please let me know.

A: Coherent state is one thing and decoherence is something else.
The coherent state has the form
$ (\text I) \ |\alpha \rangle = e^{-\alpha ^2/2} \sum _n \frac {\alpha ^n}{\sqrt {n!}} |n \rangle.$
where $|n \rangle$ is a Fock state of n identical particles. This state is a coherent superposition of Fock states, and its density matrix has diagonal and non-diagonal elements.
Decoherence means that the density matrix is diagonal, i.e. you have a mixture, not a pure state in the form of quantum superposition.


text:
Q: MBProgressHUD view not hiding In one stack I am displaying the MBProgressHUD and if by using the other stack when some calculation called I want MBProgressHUD to remove from the view but it is not been removed from the hud ..check what mistake I am doing..
first stack called LoginViewController.m
- (void)viewWillAppear:(BOOL)animated {
     [super viewWillAppear:animated];

     [MBProgressHUD showHUDAddedTo:self.view animated:YES];
}

-(void)myTask {
    // Do something usefull in here instead of sleeping ...

    [MBProgressHUD hideHUDForView:self.view animated:YES];

    [self.hud hide:YES];
    self.hud=nil;
    [self.hud removeFromSuperview];

    //[self.hud showWhileExecuting:@selector(myTask1) onTarget:self withObject:nil animated:YES];
 }

now theViewController get calls but view will be same Previous  and
after some calculation and I want that in  ViewController I want to remove theHUD  from the view by calling the method in the LoginViewController..check code
 - (void)didReceiveResponseFromServer:(NSString *)responseData
 {
     login=[[LoginViewController alloc]init];

     [self.login myTask];
 }

A: Set UP MBProgressHUD
- (void) setupHUD
{
    //setup progress hud
    self.HUD = [[MBProgressHUD alloc] initWithFrame:self.window.bounds];
    [self.SpurView addSubview:self.HUD]; // add it as here.
    self.HUD.dimBackground = YES;
    self.HUD.minSize = CGSizeMake(150.f, 150.f);
    self.HUD.delegate = self;
    self.HUD.labelText = @"Loading...";
}

Then use for hide [self.HUD hide:YES];  as describe in your code .

A: like me ,
I tyr [MBProgressHUD hideHUDForView:bAnimatedView animated:YES]
but it will no work at times when I quick push in and back out .
So I add something to check the view of MBProgressHUD.
 MBProgressHUD *HUD = [MBProgressHUD HUDForView:bAnimatedView];
 if (HUD!= nil) {
     [HUD removeFromSuperview];
     HUD=nil;
 }


text:
Q: Cheerio: Loop through children and call html() I have the following HTML which has been passed into Cheerio:

heading1

text

The output of $.root().html() is this:

heading1

text

I need to loop through the children of body and call .html() on each non-h1 child, and do something else with each h1 child.
It's important that I loop through the elements in order, I can't select all non-h1 children of body and .html() them all at once.
I've tried this:
var children = $("body").first().children();
for(var i = 0; i < children.length; i++){
    console.log(children[i].html()); // children[i].html() is not a function
}

but I can't call .html() after selecting a child from the array. .html() is also not a function when using children.each.
.html() is a function if instead of getting the element from the array using [i] I use .first(), but obviously this only works for the first element.

A: This is probably what you're looking for,
var children = $("body").first().children(":not(h1)"); // Select all non-h1 children
for(var i = 0; i < children.length; i++){
    console.log($(children[i]).html()); // Get jquery object from dom element
}

A: you can use this solution
var children = $("body").first().children(/* add your expression as string whether you want the header or not*/);

for(var i = 0; i < children.length; i++){
    console.log($(children[i]).html());
}