text:
Q: Display string with more than 3000 chars in label view Xcode My app need to display string value in label the string value is get from web server its length exceeds upto 3000 char
My code is
    [super viewDidLayoutSubviews];
    [self.scrollview layoutIfNeeded];
    self.scrollview.contentSize = self.contentview.bounds.size;
    [self.scrollview1 layoutIfNeeded];
    self.scrollview1.contentSize = self.label_sample.bounds.size;
    [self.scrolllabel layoutIfNeeded];
    self.scrolllabel.contentSize = self.textlabelscroll.bounds.size;
    [self.scrolllabel addSubview:textlabelscroll];
}

-(void)viewDidLoad

{

 [textlabelscroll setText:(got from webserver)];

 [textlabelscroll sizeToFit];

}

the label displays empty but the scroll is enabled am unable to view the string if the string length is more than 934 characters.

A: My Suggestion it maybe correct or not... try text view or why you need label and add this
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
return NO;}

or
[textView setEditable:NO];

To disable editing textview
Why you want only label???


text:
Q: How to separate logs of uWSGI? I want to separate the logs of uwsgi like access logs, request logs, error logs in individual files. At the moment these all are in same file and not well formatted.

A: There are configuration directives to specify different loggers for requests and all other messages: logger and req-logger. Example:
# uwsgi.ini
req-logger = file:/var/log/uwsgi/uwsgi-req.log
logger = file:/var/log/uwsgi/uwsgi.log

If you want nondefault formatting, filtering or a peculiar output location, you could write your own logging plugin. Here's a link the relevant page: http://uwsgi-docs.readthedocs.org/en/latest/Logging.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change double integral to polar coordinates I have an integral $$ \int_{1}^{2} \int_{0}^{2 - y} f\left(x, y\right) \mathrm{d}x \: \mathrm{d}y$$ and I need to change into polar coordinates. The area looks like this:

Since there's no easy way of saying which bounds $r$ will have, we need to use a substitution into one of the following inequalities:
$$ 1 \leq y \leq 2, $$
$$ 0 \leq x \leq 2 - y. $$
By substituting into $x$ inequality I get:
$$ x \geq 0 \implies r \cdot \cos \varphi \geq 0 \implies r \geq 0 $$
$$ x \leq 2 - y \implies r \cdot \cos \varphi \leq 2 - r \cdot \sin \varphi \implies r \leq \frac{2}{\sin \varphi + \cos \varphi},$$
so the integral would look like this $$ \int_{\frac{\pi}{4}}^{\frac{\pi}{2}} \int_{0}^{\frac{2}{\sin \varphi + \cos \varphi}} f \left( r \cos \varphi, r \sin \varphi \right) \mathrm{d}r \: \mathrm{d}\varphi $$
But when doing the same for the $y$ inequality, the integral would be different:
$$ \int_{\frac{\pi}{4}}^{\frac{\pi}{2}} \int_{\frac{1}{\sin \varphi}}^{\frac{2}{\sin \varphi}}
f \left( r \cos \varphi, r \sin \varphi \right) \mathrm{d}r \: \mathrm{d}\varphi $$
Which one is right and how to choose where to subtitute?


text:
Q: iphone development Please guide me to write a code for iphone where i want to display the path of the browsed image along with the displaying that image?

A: NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.kitco.com/images/live/silverw.gif"]];
if([imageData length] == 0){
    /*NSString *imagePath = [[NSString alloc] initWithFormat:@"%@/%@",[[NSBundle mainBundle] resourcePath],@"no_image.png"];
     UIImage *image = [[UIImage alloc] initWithContentsOfFile:imagePath];
     [item setObject:image forKey:@"itemImage"];
     [imagePath release];
     [image release];*/
}
else {
    UIImage *image = [[UIImage alloc] initWithData:imageData];

    mChartImageView.frame = CGRectMake(0,0, 600, 300);
    myScrollView.contentSize = mChartImageView.frame.size;
    [myScrollView setMinimumZoomScale:-1.0];
    [myScrollView setMaximumZoomScale:4.0];
    [myScrollView setScrollEnabled:YES];
    [myScrollView setContentSize:CGSizeMake(mChartImageView.frame.size.width, mChartImageView.frame.size.height)];
    mChartImageView.image = image;
    [image release];
}
[pool release];


text:
Q: Figuring out partial fractions using Taylor series
Suppose the factor $(x-a)$ in the denominator to be repeated $r$ times, so that,
$$ \phi(x) = (x-a)^r \Phi(x)$$
Let $$ x-a = y$$
Then,
$$ \frac{f(x)}{\phi(x)} = \frac{ f(a+y)}{y^r \Phi(a+y)}$$
or expanding each function by any means in ascending powers of 'y'
$$ \frac{ f(a+y)}{y^r \Phi(a+y)}= \frac{A_o + A_1 y + A_2 y^2...}{y^r ( B_o + B_1 y +b_2 y^2...)}$$
Divide out thus:-
$$ B_o + B_1 y + .. A_O + A_1 y + C_o + C_1 y + C_2 y^2... $$
and let division continue until $y^r$ is a factor of the remainder. Let the remainder be $ y^r \chi (y)$
Hence the fraction =$$ \frac{C_o}{y^r} + \frac{C_1}{y^r-1} ... + \frac{C_{r-1} }{y} + \frac{ \chi (y) }{ \phi(a+y)} =\frac{C_o}{(x-a)^r} + \frac{C_1}{(x-a)^{r-1}} ... + \frac{C_{r-1} }{(x-a)} + \frac{ \chi ((x-a)) }{ \phi(a+y)} $$
-Differential Calculus for Beginners, Joseph Edwards

Ok, so I'm quite confused as to what he meant in the 'Divide out thus' step. What exactly is this new series he writes in the next line? Further after seeing this, I thought could we split reciprocal of functions with a 'nicely' convergent series using this technique?


text:
Q: Permutation of Elements of a Countable Infinite Set Such That No Element Repeats a Position Let $ A = \{a_1,a_2, \ldots\}$, $B = \{b_1, b_2, \ldots\}$ and $C = \{c_1, c_2, \dots\}$ be three countable infinite sets. Let's say for each element $a_i \in A$ we want to pair an element $b_j \in B$ with an element $c_k \in C$ where $i$, $j$, and $k$ can be equal. Let's say we want to impose a restriction on this and that is if the pair $(b_j, c_k)$ has been paired before, we can't pair them again. Also every element of $B$ and $C$ has to be paired.
My understanding so far has been that we need $|\mathbb{N}|$ number of bijections from $\mathbb{N} \rightarrow \mathbb{N}$. Essentially what I thought about doing is to have a fixed permutation of $(b_1, b_2, b_3, \ldots )$ and just permute $(c_1, c_2, c_3, \ldots )$ countably infinite times such that no $c_i$ ever appears in the same spot. I was thinking of somehow using the unique prime factorization theorem to ensure each element $c_i$ appears in a unique spot each time, but I can't figure out the bijection.

A: Your question amounts to finding an injection $g : \mathbb{N} \to \{f : \mathbb{N} \to \mathbb{N} | f$ is a bijection$\}$. It suffices to instead find an injection $g : \mathbb{N} \to \{f : \mathbb{Z} \to \mathbb{Z} | f$ is a bijection$\}$ since $\mathbb{Z}$ and $\mathbb{N}$ are in a canonical bijection. This is quite simple: for each $n \in \mathbb{N}$, define $g_n(k) = n + k$.


text:
Q: Detection of long images fails I trained a few images and label the live image with the trained data. But when the live image is little far away from the camera my algorithm couldn't detect those images. Is there any way to even detect far images ?
Things I tried :
(*) Trained more images (i.e) increased dataset
(*) Used Image filter - Like medium filter, Gaussian filter
But those things too failed in detecting far images.
The detector couldn't detect images that are 5-6th far from the camera.


text:
Q: What nuance does this have? Might it not be a mistake?
I don't understand this combination, might plus not, this way.

A: might expresses the possibility. Here, the speaker/author wants to express the possibility of whether it is a mistake.
Make this question an answer and it'll look fine to you -

It might not be a mistake.

It's just formed into a question.
However, I'd rather say in this order- Might not it be a mistake?

A: The question "Might it not be?" is derived from the sentence "It might not be", by the process of Subject-Aux inversion.
The subject is "it", and the auxiliary verb is "might".  These two elements exchange places, and a question is formed.
"It might not be" expresses uncertainty about whether something may or may not be. The speaker is fairly certain that something is a certain way, but there is some doubt.

I think I can fix the engine, but it might not be easy. [I'm quite confident about fixing it, but I foresee certain possible difficulties.]

The question "might it not be?" expresses the speaker's suspicion that something is true, or exists in a certain way. It is usually a rhetorical question, which has the effect of proposing the suspicion in a humble way.

Might it not be that you're doing it wrong? [Is it possible you are doing it wrong?] -> [I suspect you're doing it wrong, but I want to say that in a nicer way.]


text:
Q: Java Spring Webflux on Kubernetes: always [or-http-epoll-1], [or-http-epoll-2], [or-http-epoll-3], [or-http-epoll-4] despite configured resource Small question regarding a Java 11 Spring Webflux 2.6.6+ web app, containerized and deployed using Kubernetes please.
From the web app application logs, I am seeing things such as:
INFO [service,1bcce5941c742568,22c0ab2133c63a77] 11 --- [or-http-epoll-2] a.b.c.SomeClass  : Some message from the reactive pipeline.
INFO [service,67cb40974712b3f4,15285d01bce9dfd5] 11 --- [or-http-epoll-4] a.b.c.SomeClass  : Some message from the reactive pipeline.
INFO [service,5011dc5e09de30b7,f58687695bda20f2] 11 --- [or-http-epoll-3] a.b.c.SomeClass  : Some message from the reactive pipeline.
INFO [service,8046bdde07b13261,5c30a56a4a603f4d] 11 --- [or-http-epoll-1] a.b.c.SomeClass  : Some message from the reactive pipeline.

And always, I can only see [or-http-epoll-1] [or-http-epoll-2] [or-http-epoll-3] [or-http-epoll-4] which I think stands for: [reactor-http-epoll-N]
The problem is, no matter how much CPU I allocate from Kubernetes, it is always those 4, no less, no more.
I tried:
  resources:
            requests:
              cpu: 1
              memory: 1G
            limits:
              cpu: 2
              memory: 2G

  resources:
            requests:
              cpu: 4
              memory: 4G
            limits:
              cpu: 6
              memory: 6G

  resources:
            requests:
              cpu: 10
              memory: 10G
            limits:
              cpu: 10
              memory: 10G

But again, always only those 4.
I am having a hard time understanding what is the problem here, and why am I stuck with only/always 4 "or-http-epoll-".
Thank you

A: By default WebFlux uses Netty as an underlining web server. Here is how Netty determine number of threads in the pool Netty - LoopResources
/**
* Default worker thread count, fallback to available processor
* (but with a minimum value of 4)
*/
int DEFAULT_IO_WORKER_COUNT = Integer.parseInt(System.getProperty(
    ReactorNetty.IO_WORKER_COUNT,
    "" + Math.max(Runtime.getRuntime().availableProcessors(), 4)));

The next question, what is the current Runtime.getRuntime().availableProcessors()?
It depends on Java version. Until Java version 10, application on Docker sees CPU on the machine and not inside the container.
You could create a simple Java application to validate
class TestCpu {
    public static void main(String[] args) {
       int processors = Runtime.getRuntime().availableProcessors();
       System.out.println("CPU cores: " + processors);
  }
}


text:
Q: Integrate existing MVC view into Umbraco I have created an Umbraco site using the latest version (6.1.6) as an MVC site. Now I have an existing website which retrieves a list of users. I would like to integrate these pages into Umbraco under a custom section. In previous versions of Umbraco (4.7), I used to create user controls in .NET to perform my non-Umbraco db tasks and then link them up in Umbraco by dropping the DLL and the user control in.
How do I do this with the MVC site? I did a bit of reading up on SurfaceController and RenderMVCController but am confused as I really don't want to use any Umbraco related controllers. I would just like to integrate the existing views/controllers into the Umbraco site like I used to do with .NET user controls
Any ideas how this can be achieved?

A: You can still use webforms controls like you did before. Umbraco lets you mix Web Forms and MVC, however it's based on the page. As far as I'm aware, you can't mix MVC and Web Forms functionality into a single page, but you can have both Web Forms and MVC pages in your application.
If you are able to get by with it, you can create a new page using a Master Page template (non-MVC) and use your usercontrol macros there.


text:
Q: How to fetch data in a background process in Ubuntu I am finding a Ubuntu OS command, which lets the program to read the data from keyboard even if the program is in background. I tried to search it a lot but got no success. If any Ubuntu/Linux programmer knows the OS command which lets the program to do so, Please share it with me.
I am a beginner of Ubuntu programming.

A: You can use the Linux input subsystem to read events from mice and keyboards. It will only work if your application has the necessary privileges. Basically, you have to run the application as root for this to work.
If you cannot run as root, you should not be attempting to monitor the keyboard anyway.
You can create an X11 application to monitor keyboard events in the current session. It only works for the current user, and in the current graphical environment, and may not be able to observe privileged dialogs, for example password inputs. For details, look at the application shortcut launcher for your desktop environment; all Linux DEs I've ever heard of have one.
I think the old Linux Journal articles, The Linux USB Input Subsystem and Using the Input Subsystem, are still one of the best introductions to the Linux input subsystem. Most Linux distributions nowadays also support uinput, a similar device that allows injecting input events back to the kernel subsystem, designed to allow user-space input device drivers. Their interfaces are described in /usr/include/linux/input.h and /usr/include/linux/uinput.h. I recommend you start at the above articles, and then look at some input and uinput examples.

A: If you are comfortable using a program, have a look at Logkeys project
. It directly takes input from /dev/input/event*.


text:
Q: Error in R-function when input is string I have made a function that tests which numbers in a range that are multiple of 6 and/or 3, or none of them.
Multi <- function(x,y) {
 z = x:y
 for (i in z) {
  if (i%%1!=0 | i<0) {
   print("Error!")
   break
 } else if (i%%3==0 & i%%6==0) {
   print(paste(i, "is multiple of both 3 and 6"))
 } else if (i%%3==0) {
   print(paste(i, "is multiple of 3"))
 } else {
   print(paste(i, "is not multiple"))
  }
 }
}

The loop works as I want it to, but within the first if-statement, I would also like it to print "Error!" if a character/string is provided. The message I get when trying Multi("Hello",10) is:
Error in x:y : NA/NaN argument
In addition: Warning message:
In Multi("Hello", 10) : NAs introduced by coercion
I have tried the suppressWarnings() function, but I couldn't make it work.
Any suggestions?

A: Try this:
Multi <- function(x,y) {
  if (!is.numeric(x) | !is.numeric(y)) {
    print("Error!")
  } else {
    z = x:y
    for (i in z) {
      if (i%%1!=0 | i<0) {
        print("Error!")
        break
      } else if (i%%3==0 & i%%6==0) {
        print(paste(i, "is multiple of both 3 and 6"))
      } else if (i%%3==0) {
        print(paste(i, "is multiple of 3"))
      } else {
        print(paste(i, "is not multiple"))
      }
    }
  }
}
Multi(1,10)
Multi('Hello', 10) # now it will print Error without a NaN: 'Hello':10 was causing this NaN

You can reduce the code a little bit also
sapply(1:10, function(i) ifelse(i%%3==0,
                                ifelse(i%%6==0,
                                       paste(i, "is multiple of both 3 and 6"),
                                       paste(i, "is multiple of 3")),
                                paste(i, "is not multiple")))


text:
Q: Generic solution needed for decoding Cyrillic string encoded in UTF-8 in C# I am getting ÐиÑилл ÐаÑанник from a C++ component and I need to decode it. The string is always UTF-8 encoded. After much RnD, I figured following way to decode it.
String text = Encoding.UTF8
                      .GetString(Encoding.GetEncoding("iso-8859-1")
                      .GetBytes("ÐиÑилл ÐаÑанник"));

But isn't this hardcoding "iso-8859-1", as in what if characters other than cyrillic come up. So I want to have a generic method for decoding a UTF-8 string.
Thanks in advance.

A: When you type text, the computer sees only bytes. In this case, when you type Cyrillic characters into your C++ program, the computer converts each character to its corresponding UTF-8 encoded character.
string typedByUser = "Привет мир!";
byte[] input = Encoding.UTF8.GetBytes(typedByUser);

Then your C++ program comes along, looks at the bytes and thinks it is ISO-8859-1 encoded.
string cppString = Encoding.GetEncoding("iso-8859-1").GetString(input);
// ÐÑÐ¸Ð²ÐµÑ Ð¼Ð¸Ñ!

Not much you can do about that. Then you get the wrongly encoded string and have to assume it is incorrectly ISO-8859-1 encoded UTF-8. This assumption proves to be correct, but you cannot determine this in any way.
byte[] decoded = Encoding.GetEncoding("iso-8859-1").GetBytes(cppString);
string text = Encoding.UTF8.GetString(decoded);
// Привет мир!

Note that ISO-8859-1 is the ISO West-European encoding, and has nothing to do with the fact that the original input was Cyrillic. For example, if the input was Japanese UTF-8 encoded, your C++ program would still interpret it as ISO-8859-1:
string typedByUser = "こんにちは、世界!";
byte[] input = Encoding.UTF8.GetBytes(typedByUser);
string cppString = Encoding.GetEncoding("iso-8859-1").GetString(input);
// ããã«ã¡ã¯ãä¸çï¼
byte[] decoded = Encoding.GetEncoding("iso-8859-1").GetBytes(cppString);
string text = Encoding.UTF8.GetString(decoded);
// こんにちは、世界!

The C++ program will always interpret the input as ISO-8859-1, regardless of whether it is Cyrillic, Japanese or plain English. So that assumption is always correct.
However, you have an additional assumption that the original input is UTF-8 encoded. I'm not sure whether that is always correct. It may depend on the program, the input mechanism it uses and the default encoding used by the Operating System. For example, the C++ program made the assumption that the original input is ISO-8859-1 encoded, which was wrong.

By the way, character encodings have always been problematic. A great example is a letter from a French student to his Russian friend where the Cyrillic address was incorrectly written as ISO-8859-1 on the envelope, and decoded by the postal employees.

A: A source of characters should only be transfered in one encoding, that means it's either iso-8859-1 or something else, but not both at the same time
(that means you might be wrong about the reverse engineered cyrillic in the first place)
Could you post the expected UTF-8 output of your input?


text:
Q: geometry - adjust textwidth to new margins \documentclass[11pt]{article}
\usepackage[a4paper, portrait, margin=1in]{geometry}
\usepackage{adjustbox}
\usepackage{tabularx}
\usepackage{booktabs,csvsimple}
\usepackage{pdflscape}

[...]

\begin{landscape}
\thispagestyle{empty}
    \begin{table}[ht]
        \begin{adjustbox}{max width=\textwidth}
            \csvautobooktabular[]{csvs/large_table.csv}
        \end{adjustbox}
        \caption{\small{Blah blah blah}}
        \label{tab:test}
    \end{table}
\end{landscape}

The above code will give me something like this:

which, I guess, is acceptable when reading the file on a digital device because you can zoom in.
But just to be sure, I would like to extend the space available to the table:

How do I do that? I tried using the geometry package
\documentclass[11pt]{article}
\usepackage[a4paper, portrait, margin=1in]{geometry}
\usepackage{adjustbox}
\usepackage{tabularx}
\usepackage{booktabs,csvsimple}
\usepackage{pdflscape}

[...]

\begin{landscape}
\thispagestyle{empty}
\newgeometry{margin=1cm}
    \begin{table}[ht]
        \begin{adjustbox}{max width=\textwidth}
            \csvautobooktabular[]{csvs/large_table.csv}
        \end{adjustbox}
        \caption{\small{Blah blah blah}}
        \label{tab:test}
    \end{table}
\end{landscape}

Which had the very interesting (and very useless) effect that the margins were reduced but apparently, the textwidth was not changed to reflect this.

So I tried
\newgeometry{margin=1cm,textwidth=\paperwidth-2cm}

Which achieved perfectly nothing.
UPDATE
Using
\begin{adjustbox}{max width = \dimexpr\paperheight-1cm, center} ... \end{adjustbox}

as proposed by Werner in the comments results in

which would be fine inasfar as width is concerned. Any way to violate the top (left, if you hold it in portrait) margin?


text:
Q: How combined my templatetags and base filter |linebreaksbr I have a problem with right sidebar in that site:
http://antonigin.pythonanywhere.com/
I need to create linebreaks in text. I can add that in post, that's not a problem. But sidebar using my tag.
@register.simple_tag
def notetitle(value):
    note = Note.objects.get(pk=value)
    return note.title

@register.simple_tag
def notetext(value):
    note = Note.objects.get(pk=value)
    return note.text

I create that template:
{% load note_def %}
    {% block note %}

{% notetitle 2 %}

{% notetext 2 %}

    {% endblock %}

I need a filter |linebreaksbr. And i dont know, how to insert this.
Of course, i can send value with my note in every view and insert {% content block %} in every templates, but if i will want change sidebar, that's take a lot of time.

A: Simple solution: use a single tag that returns the note, ie:
template tag:
@register.simple_tag
def get_note(value):
    note = Note.objects.get(pk=value)
    return note

template:
{% load note_def %}
    {% block note %}
        {% get_note 2 as note %}

{{ note.title }}

{{ note.text|linebreaksbr }}

    {% endblock %}

As an added benefit you now only need half the db queries ;)
NB : for django < 1.9 you'll have to use an assignment_tag instead, cf the doc for your exact version.


text:
Q: What is the equivalent in .Net of the :print: character class from PHP or Java? I have some validators that in Java and PHP that are using this :print: character class in their regexes to validate input lengths. Any human readable input is valid as long as it doesn't exceed a limit.
In the .Net part we are using the word (\w) characters class. This lead to a bug where lots of characters weren't matched by the .Net regex (ie. #, currencies, so on).
The question is: is \s\S a valid equivalent for :print:? If not what are the other options I have?


text:
Q: How to append a value at the end of src attribute in html string I have this html in string, I want to modify the src tags such a way that I want to keep the values but append a string at the end of the attribute
HTML before modification
<html>
  <head>
    <title>LDRA Testbed Results</title>
  </head>
  <script>
    var AddTxt = true;
    var TBpublish = true;
  </script>
  <frameset cols="206,*" marginwidth="0" marginheight="0"
FRAMEBORDER="no" BORDERCOLOR="#DEDEEF">
     <frame src="./App_xyz_P_tbresults/App_xyz_P.lfm.htm" name="lFrame" NORESIZE>
     <frame src="htm_idx/frontpage.htm" name="rFrame" FRAMEBORDER="no">
  </frameset>
</html>

HTML after modification
<html>
   <head>
     <title>LDRA Testbed Results</title>
   </head>
   <script>
      var AddTxt = true;
      var TBpublish = true;
   </script>
   <frameset cols="206,*" marginwidth="0" marginheight="0" FRAMEBORDER="no" BORDERCOLOR="#DEDEEF">
      <frame src="./App_xyz_P_tbresults/App_xyz_P.lfm.htm:A:1" name="lFrame" NORESIZE>
      <frame src="htm_idx/frontpage.htm:A:1" name="rFrame" FRAMEBORDER="no">
    </frameset>
</html>

How can I do that in Node.js
Current code
This is how I'm currently parsing the html code using the parser
var html = chunk.toString();
    var temp = html;

    html = parse(html);
    var modifiedHTML = [];
    var elementsTag = [
      "<a ",
      "<area ",
      "<base ",
      "<body ",
      "<frame ",
      "<iframe ",
      "<img ",
      "<input ",
      "<link ",
      "<script ",
      "<audio ",
      "<embed ",
      "<source ",
      "<track ",
      "<video "
    ];

    var elements = [
      "a",
      "area",
      "base",
      "body",
      "frame",
      "iframe",
      "img",
      "input",
      "link",
      "script",
      "audio",
      "embed",
      "source",
      "track",
      "video"
    ];

    for (var i = 0; i < elementsTag.length; i++) {
      var count = (temp.match(new RegExp(elementsTag[i], "g")) || []).length;

      for (var j = 0; j < count; j++) {
        var elementAttr = html.querySelector(elements[i]);

        if (elementAttr != null) {
          // console.log(elementAttr);
          if (Object.keys(elementAttr.attributes).length > 0) {
            Object.keys(elementAttr.attributes).forEach(attribute => {
              if (attribute == "src" || attribute == "href") {
                var attributeVal = elementAttr.attributes[attribute];
                // console.log(attributeVal[j]);
                attributeVal = attributeVal + `:${project_name}:${type}`;
                elementAttr.setAttribute(attribute, attributeVal);
              }
            });
          }
          modifiedHTML.push(elementAttr.outerHTML);
        }
      }
    }

    console.log(modifiedHTML);

Output:
[
[0]   '<frame src="./App_xyz_P_tbresults/App_xyz_P.lfm.htm:TEST:static_analysis_report1:TEST:static_analysis_report1" name="lFrame" NORESIZE></frame>',
[0]   '<frame src="./App_xyz_P_tbresults/App_xyz_P.lfm.htm:TEST:static_analysis_report1:TEST:static_analysis_report1:TEST:static_analysis_report1" name="lFrame" NORESIZE></frame>'
[0] ]

A: It is not a trivial task to parse HTML in JavaScript. I didn't check your attempt but you should really use an existing HTML parser instead of doing your own.
You can use for example jsdom to achieve what you want:
const jsdom = require("jsdom");
const { JSDOM } = jsdom;

let html = `<html>
  <head>
    <title>LDRA Testbed Results</title>
  </head>
  <script>
    var AddTxt = true;
    var TBpublish = true;
  </script>
  <frameset cols="206,*" marginwidth="0" marginheight="0"
FRAMEBORDER="no" BORDERCOLOR="#DEDEEF">
     <frame src="./App_xyz_P_tbresults/App_xyz_P.lfm.htm" name="lFrame" NORESIZE>
     <frame src="htm_idx/frontpage.htm" name="rFrame" FRAMEBORDER="no">
  </frameset>
</html>`;

const dom = new JSDOM(html);

let frameset_children = dom.window.document.body.children;
for (let i = 0; i < frameset_children.length; i++) {
  let frame = frameset_children[i];
  frame.src = frame.src + ':A:1';
}

console.log(dom.serialize())


text:
Q: Avro schema evolution: extending an existing array Standard Avro schema evolution examples show adding a new field with a default value to a record. But what if your old schema had an array and you want to add a new field to that array?
For example, given an array of records:
{
  "type": "array",
  "items": {
    "name": "Loss",
    "type": "record",
    "fields": [
      {
        "name": "lossTotalAmount",
        "type": [ "null", "string" ],
        "default": null
      },
      {
        "name": "lossType",
        "type": [ "null", "string" ],
        "default": null
      },
      {
        "name": "lossId",
        "type": [ "null", "string" ],
        "default": null
      },
      {
        "name": "vehicleLossCode",
        "type": [ "null", "string" ],
        "default": null
      }
    ]
  }
}

Adding a new field claimNumber:
{
  "type": "array",
  "items": {
    "name": "Loss",
    "type": "record",
    "fields": [
      {
        "name": "lossTotalAmount",
        "type": [ "null", "string" ],
        "default": null
      },
      {
        "name": "lossType",
        "type": [ "null", "string" ],
        "default": null
      },
      {
        "name": "lossId",
        "type": [ "null", "string" ],
        "default": null
      },
      {
        "name": "vehicleLossCode",
        "type": [ "null", "string" ],
        "default": null
      },
      {
        "name": "claimNumber",
        "type": [ "null", "string" ],
        "default": null
      }
    ]
  }
}

Using the regular technique doesn't seem to work as I start running into deserialization exceptions. Is there a different way to extend existing arrays in Avro or is it impossible?


text:
Q: Google SignIn complete vs manual app switch When using [GIDSignIn sharedInstance].allowsSignInWithWebView = NO how can I tell the difference between the user completing the Google SignIn process or manually switching back to my app?

A: If user completed google sign in (successfully or not) GIDSignInDelegate method - (void)signIn:didSignInForUser:withError: will be called. If its not called, then probably user just returned manually...   Also, you can check in your app delegate: google sign in will return to your app by using the url scheme, as a result this methos will be called: application:openUrl:sourceApplication:annotation


text:
Q: The first letter missing on input field I'm using these two almost identical functions to catch a keypress event in an input field, and clear the label inside it. But for some reason the first letter I type won't appear in the password field, while it appears in the username field. What could be the cause of this?
$("#username").keypress(function()
{
  if($(this).hasClass("label"))
  {
    $(this).removeClass("label");
    $(this).val("");
  }
});

$("#password").keypress(function()
{
  if($(this).hasClass("label"))
  {
    $(this).removeClass("label");
    $(this).prop("type", "password");
    $(this).val("");
  }
});

See example here: https://jsfiddle.net/c0qdj1u3/

A: The following line is causing the bug:
    $(this).prop("type", "password");

If you start off as the type being password, it works fine. Instead of setting the value, use a placeholder. See below:
<input type="text" placeholder="Username" class="label" id="username"><br>
<input type="password" placeholder="Password" class="label" id="password">

$("#username").keypress(function()
{
    if($(this).hasClass("label"))
  {
    $(this).removeClass("label");
    $(this).val("");
  }
});

$("#password").keypress(function()
{
    if($(this).hasClass("label"))
  {
    $(this).removeClass("label");
    $(this).val("");
  }
});

If you MUST have some value in the text box prior to any typing, try using the jQuery-Placeholder plugin. https://github.com/mathiasbynens/jquery-placeholder


text:
Q: Why does attempting to start a task cause an EntryPointNotFoundException? In my application, I have a utility class which is supposed to execute a series of tasks in parallel, and provide reporting on the success and timing of the various tasks.
Every time I run it, I get an EntryPointNotFoundException.
The simplest test case I could come up with which creates the behavior is beyond trivial.  Just
 Task.Run(() => { Console.WriteLine("This is sanity test"); });

using no return value, and no custom classes anywhere throws an EntryPointNotFoundException.

This is with Visual Studio 2015, the process is 64 bit (which for the overall application it MUST be, running on Windows 7 64-bit).  It is a .NET 4.5 console application.
What causes this and how can it be fixed?


text:
Q: Generate Individual serial number for a specific pattern in android I need to get a new serial in my android app. I need a serial number with a specific pattern every time when a user click a button.
The serial number pattern is:
[date]_1 ... ... ... [date]_n
for example, today is 21-09-2021. so first serial number for today will be 210921_1, the next one for today will be 210921_2. And for tomorrow the first serial number will be 220921_1, the next one will be 220921_2. Like this it will continue.
How can I do it?
please forgive if I make any mistake.

A: The first step with solving a problem such as this is to break it down into the separate logic elements.

*

*Extract Date Today.

*Check 'number' of previous dates stored.

*Convert data to DDMMYY format.

*Append _

*Append 'number' + 1

*Increment 'number' counter.

Those are the steps. You therefore need a variable to start with that will contain the current value of the number of serials stored that day, this will start at 0.
Next you now need to understand how to get the 'date' and how to format it. Look at the APIs for Calendar and SimpleDateFormat.
That's about it.
I could post code but, there's a lot of examples for those and, really, with that logic, you should now be able to do this yourself.
Good luck!


text:
Q: How much water is destroyed in photosynthesis, relative to the world's supply? Water is involved in the photosynthesis. How much water are we talking about compared with the total amount on water on Earth? Is it enough to have an effect on the average age of water molecules?

A: According to http://ga.water.usgs.gov/edu/earthhowmuch.html the total volume of water on the earth is $1.386\times 10^9$km$^3$, which is about $1.4 \times 10^{21}$kg (I'm rounding because I don't know the average temperature and therefore density of the water).
According to http://en.wikipedia.org/wiki/Biomass_(ecology)#Global_rate_of_production the annual photoautotrophic production of biomass is 104.9 billion tonnes C/yr. Assuming this is all carbohydrate one carbon atom is associated with roughly one water molecule (monosaccharides are C6H12O6) so the weight of water associated with that weight of carbon is $1.6 \times 10^{14}$kg.
So if you assumed all water gets cycled through the biosphere you'd conclude that the average life of a water molecule is 8.75 million years.
I must admit this is shorter than I expected.


text:
Q: Error: Cannot Spawn C:\Path To\TortoiseGit\Bin: No such file or directory Trying to do a fetch from origin:
git remote update

Get the error
Error: Cannot Spawn C:\Path To\TortoiseGit\Bin: No such file or directory
fatal: unable to fork
Error: Could not fetch origin

Why is this happening? Also is there a fix?

A: I faced this problem when I was required to remove and install the TortoiseGit and Git. Previously both was installed on C:\ but later I installed those on F:. So after re-installing when I tried to pull repositories it was giving me the following error while using from context menu
error: cannot spawn C:\Program Files\TortoiseGit\bin\TortoisePlink.exe: No such file or directory
After little bit investigation I went to Settings->Network and update the SSH Client path from C:... to F:... and then it was resolved.

A: For me, for TortoiseGit>Settings>Network>SSH , I had to set it to just ssh.exe instead of the full path to ssh.

A: For me the answer was removing the double quotes of "c:\Program Files (x86)\PuTTY\plink.exe" from the environment variable GIT_SSH.

A: This blog would seem to be the exact same problem that you have:
http://www.techneiq.com/2012/08/error-cannot-spawn-cprogram.html
And this issue on msysgit also points to the same error:
https://code.google.com/p/msysgit/issues/detail?id=313
Find out what your GIT_SSH environmental variable is pointing to and if that path has a space in it. Maybe reinstalling TortoiseGit would solve it. (Otherwise I can really recommend GitExtensions instead)

A: Set environment variable GIT_SSH to
%ProgramFiles(x86)%\PuTTY\plink.exe

or
%ProgramFiles%\PuTTY\plink.exe

A: You can just find the  copy the directory into the place which the error message has point out.


text:
Q: complicated list column to column string matching and deriving another column Dataframes:
df1:
ind_lst
[agriculture_dairy, analytics]
[architecture_planning, advertising_pr_events, analytics]

df2:
ind    score
advertising_pr_events   3.672947168
agriculture_dairy   3.368266582
airlines_aviation_aerospace 3.60798955
analytics   3.67752552
architecture_planning   3.853236675

I have 2 data frames as shown above.
Column ind of df2 is of type string & has industry names. df2.score has a unique score for each industry.
Column ind_lst of df1 is a list of industry names formed by different combinations of unique elements of df2.ind
I want to create a column in df1 avg_score such that the final output is as below:
avg_score in row1 of df1 is avg of the scores from df2 corresponding to agriculture_dairy, analytics
avg_score in row2 of df1 is avg of scores from df2 corresponding to architecture_planning, advertising_pr_events, analytics.
df1
ind_lst    avg_score
[agriculture_dairy, analytics]    3.522896051
[architecture_planning, advertising_pr_events, analytics]    3.734569787666667

How to implement this in python?
I tried this:
avg=[]
avgs=[]
for i in df1.ind_lst:
    for j in i:
        a= df2[df2['ind'] == j].index
        avg.append(df2.loc[a]['score'])
    avgs.append(mean(avg))

df1['avg_score']= avgs

the code doesn't work well. I get an empty list as output.
NOTE: I have sampled the data frames & shared only a subset of the problem statement. the real dataframes df1 has 90k entries & df2 has 860 rows.

A: Option 1: Create a map of ind and score from df2. Use list comprehension to map the score to the industry and calculate mean.
mapper = df2.set_index('ind')['score'].to_dict()
df1['avg_score'] = df1['ind_lst'].apply(lambda x: np.mean([mapper[i] for i in x]))

    ind_lst                                             avg_score
0   [agriculture_dairy, analytics]                      3.522896
1   [architecture_planning, advertising_pr_events,...   3.734570

Option 2: Use DataFrame.explode to unnest the list, groupby index and apply mean
df1['avg_score'] = df1['ind_lst'].explode().map(mapper).groupby(level = 0).mean()

A: Instead of using a mapper and list comprehension like Vaishali does, you can just use the list as an index for df2, like this.
df1["average_score"] = df1["ind_lst"].apply(lambda lst: df2.loc[lst, "score"].mean())


text:
Q: TabView header style I am using TabVIew and I've got two questions:
1.How can I remove the border-bottom of the TabView header?
2. How can I add separator between the items in the TabView header ?

Thanks,
Chen

A: You can't remove neither the bottom color nor add a separator within the tabs. You can control the color of your bottom border for the selected tab. Here are the exposed properties in NativeScript
<TabView
    androidSelectedTabHighlightColor="orange"
    selectedTabTextColor="red"
    tabBackgroundColor="lightgreen"
    tabTextColor="blue">

For anything above that you should access the native element and see if there are native possibilities for further styling the element.


text:
Q: disable escaping single quotes within string from bash read builtin command i want to process files from a text file containing single quoted file names, like
'new'$'\n''line'
'tab'$'\t''ulator'

copy & paste for manually processing this files works fine:
test -f 'tab'$'\t''ulator'

now, reading from file with bash read builtin command
while IFS="" read -r myfile; do
  line=$myfile
  ...
done < text.txt

give strings containing escaped single quotes, like
'\''new'\''$'\''\n'\'''\''line'\'''
'\''tab'\''$'\''\t'\'''\''ulator'\'''

however, processing this file names in bash script does not work.
test -f "$myfile"
test -f ${myfile}

how to disable /undo escaping single quotes and process raw file name within bash?

A: Using eval
Many people quite reasonably regard eval as a mis-spelling of evil.
So, I would regard this solution as last-choice to be used only if all else fails.
Let's take this sample file:
$ cat badformat
'new'$'\n''line'
'tab'$'\t''ulator'

We can read and interpret these file names as in the following example:
while read -r f; do
    eval "f=$f"; [ -f "$f" ] || echo "file not found"
done <badformat

Using NUL-separated lists of file names
The only character that cannot be in a Unix file name is NUL (hex 00).  Consequently, many Unix tools are designed to be able to handle NUL-separated lists.
Thus, when creating the file, replace:
stat -c %N * >badformat

with:
printf '%s\0' * >safeformat

This latter file can be read into shell scripts via a while-read loop.  For example:
while IFS= read -r -d $'\0' f; do
    [ -f "$f" ] || echo "file not found"
done <safeformat

In addition to shell while-read loops, note that grep, find, sort, xargs, as well as GNU sed and GNU awk, all have the native ability to handle NUL-separated lists.  Thus, the NUL-separated list approach is both safe and well-supported.

A: found the solution with string manipulating
${filename//$'\047'\\$'\047'$'\047'/$'\047'}

as you mentioned above, using eval is very dangerous for filenames like 'rm -rf'. regarding stat -c %N (which only escapes single quotes, linefeeds and tabs) there is another solution
while IFS="" read -r myfile; do

  filename="$myfile"

  filename="${filename#?}"
  filename="${filename%?}"
  filename="${filename//"'$'\t''"/$'\011'}"
  filename="${filename//"'$'\n''"/$'\012'}"
  filename="${filename//$'\047'\\$'\047'$'\047'/$'\047'}"

  test -f "$filename" && echo "$myfile exists"

done < text.txt


text:
Q: Error when creating a network namespace inside a docker container. error: mount --make-shared /run/netns failed: Permission denied I'm getting an error when creating a network namespace inside a docker container saying permission denied.
command
ip netns add red

error
mount --make-shared /run/netns failed: Permission denied

I am running an image ubuntu:20.10 and tried by adding specific capabilities to the container and it did not help.
docker run -it --rm --name=ubuntu --cap-add CAP_SYS_ADMIN --cap-add NET_ADMIN ubuntu:20.10
apt-get update && apt-get install -y net-tools && apt-get install -y iproute2

Even after adding all capabilities issue remain same.
docker run -it --rm --name=ubuntu --cap-add ALL ubuntu:20.10

A: --cap-add & --privileged are not same.
Ref: https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities
Issue is sorted by running the container with privilege. Capabilities seems not required for adding network namespace.
docker run -d --name=<name> --network=none --privileged <image>:<tag>

A: The other answer suggests adding --privileged, but note that adding --privileged effectively removes all security features. If you are uncomfortable with this, you might prefer an approach that gives the container access only to what it needs.
The root cause is that Docker's default apparmor profile contains the rule deny mount which prevents mount from working inside Docker containers, which is what is causing the error message mount --make-shared /run/netns failed: Permission denied.
You can confirm this by adding --security-opt apparmor=unconfined to your command, which disables apparmor, and notice that the mount command succeeds.
docker run -it --rm --name=ubuntu \
  --cap-add CAP_SYS_ADMIN --cap-add NET_ADMIN \
  --security-opt apparmor=unconfined \
  ubuntu
apt-get update && apt-get install -y net-tools iproute2
ip netns add red # succeeds

If you don't want to fully opt out of apparmor, you can create a custom apparmor profile, then load it with apparmor_parser -r -W path/to/your/profile and then load it with --security-opt apparmor=your-profile-name. You can create a custom apparmor profile by copying Docker's template and then tweaking it to suit your needs.
At the time of writing, Docker does not have an easy way to show the apparmor profile it is currently using, but you can look at the source template and then expand the template manually (by following the template logic).
See https://docs.docker.com/engine/security/apparmor/


text:
Q: How to freeze/hold the program util the user clicks? I'm having a little problem programming in Java.
I have a while loop that works until the game is over, when it runs I need to get a move from the player, I need the program to hold until the player click on the JFrame and makes his move, I need a method like Scanner from the keyboard, but for the mouse.
Any idea how to do it?
while(!gameOver())
        {
            if(!rw.board.possibleMoves(rw.board.turn).isEmpty())
            {
                // needs to wait until the player makes a move
                Move m =  rw.players[rw.board.turn].move;
                rw.board.makeMove(m);
                rw.updateNewGame();
            }
            // switch the turns after the move
            rw.players[rw.board.turn].move = null;
            rw.board.turn = (rw.board.turn == PLAYER1 ? PLAYER2 : PLAYER1);
        }
    }

A: GUI applications are event driven. This means you don't create such a while loop. You let the program go into its own event loop, and you make the moves and switch the turns as a response to the user's click event.
That is, you create a click event listener, and in its actionPerformed() method, you check:
if (!gameOver())
{
    if(!rw.board.possibleMoves(rw.board.turn).isEmpty())
    {
        // needs to wait until the player makes a move
        Move m =  rw.players[rw.board.turn].move;
        rw.board.makeMove(m);
        rw.updateNewGame();
    }
    // switch the turns after the move
    rw.players[rw.board.turn].move = null;
    rw.board.turn = (rw.board.turn == PLAYER1 ? PLAYER2 : PLAYER1);
}

Make sure that the methods called here change the state of the button or remove it when pressing it no longer makes sense (no possible moves or game over etc.).

A: Well this might be a good reason to implement it asynchronously.
Assuming you are one threaded, this will not be much of a problem:
You'll add a while(m == null);, waiting for the Move to be an object.


text:
Q: fusioncharts multi series bar chart does not render with dynamic categories and datasets I'm using fusioncharts for the first time, and I'm having trouble rendering a multi series bar chart using dynamic categories and datasets. Below is my code:
FusionCharts.ready(function () {

getSentiCount(symbolInput);

var chartCategories1 = "[{'category': [";

for (var a = 0; a < sentiData.length; a++) {
    if(sentiData[sentiData.length - 1].totalcount == sentiData[a].totalcount) {
        chartCategories1 += "{'label':'" + bdateForm(sentiData[a].bdate) + "'}";
    } else {
        chartCategories1 += "{'label':'" + bdateForm(sentiData[a].bdate) + "'},";
    }
}

chartCategories1 += "]}]";

var chartData1 = "[{'seriesname': 'Negative','data':[";

for (var e = 0; e < sentiData.length; e++) {
    if(sentiData[e].bdate == sentiData[sentiData.length - 1].bdate) {
        if(sentiData[e].avgsentimentvalue == "1") {
            chartData1 += "{'value':'" + sentiData[e].totalcount + "'}";
        } else {
            chartData1 += "{'value':'" + 0 + "'}";
        }
    } else {
        if(sentiData[e].avgsentimentvalue == "1") {
            chartData1 += "{'value':'" + sentiData[e].totalcount + "'},";
        } else {
            chartData1 += "{'value':'" + 0 + "'},";
        }
    }
}

chartData1 += "]},{'seriesname': 'Positive','data':[";

for (var e = 0; e < sentiData.length; e++) {
    if(sentiData[e].bdate == sentiData[sentiData.length - 1].bdate) {
        if(sentiData[e].avgsentimentvalue == "3") {
            chartData1 += "{'value':'" + sentiData[e].totalcount + "'}";
        } else {
            chartData1 += "{'value':'" + 0 + "'}";
        }
    } else {
        if(sentiData[e].avgsentimentvalue == "3") {
            chartData1 += "{'value':'" + sentiData[e].totalcount + "'},";
        } else {
            chartData1 += "{'value':'" + 0 + "'},";
        }
    }
}

chartData1 += "]},{'seriesname': 'Neutral','data':[";

for (var e = 0; e < sentiData.length; e++) {
    if(sentiData[e].bdate == sentiData[sentiData.length - 1].bdate) {
        if(sentiData[e].avgsentimentvalue == "2") {
            chartData1 += "{'value':'" + sentiData[e].totalcount + "'}";
        } else {
            chartData1 += "{'value':'" + 0 + "'}";
        }
    } else {
        if(sentiData[e].avgsentimentvalue == "2") {
            chartData1 += "{'value':'" + sentiData[e].totalcount + "'},";
        } else {
            chartData1 += "{'value':'" + 0 + "'},";
        }
    }
}

chartData1 += "]},{'seriesname': 'Unknown','data':[";

for (var e = 0; e < sentiData.length; e++) {
    if(sentiData[e].bdate == sentiData[sentiData.length - 1].bdate) {
        if(sentiData[e].avgsentimentvalue == "") {
            chartData1 += "{'value':'" + sentiData[e].totalcount + "'}";
        } else {
            chartData1 += "{'value':'" + 0 + "'}";
        }
    } else {
        if(sentiData[e].avgsentimentvalue == "") {
            chartData1 += "{'value':'" + sentiData[e].totalcount + "'},";
        } else {
            chartData1 += "{'value':'" + 0 + "'},";
        }
    }
}

chartData1 += "]}]";

 var chartProperties1 = {
          "caption": "Sentiment",
          "bgColor": "#ffffff",
            "bgColor": "#ffffff",
            "showBorder": "0",
            "borderAlpha": "20",
            "canvasBorderAlpha": "0",
            "baseFontSize": "14",
            "usePlotGradientColor": "0",
            "plotBorderAlpha": "10",
            "showXAxisLine": "1",
            "showYAxisLine": "0",
            "showYAxisValues": "0",
            "xAxisLineColor": "#999999",
            "divlineColor": "#999999",
            "showAlternateHGridColor": "0",
          "paletteColors": "#2cb32b,#ff2602,#2786f7,#f9f70e",
          "manageResize": "1",
          "autoScale": "1"
        }

 function renderchart() {
        var contentSummaryChart1 = new FusionCharts({
            type: 'mscolumn2d',
            renderAt: "sentimentChart",
            width: "100%",
            height: "180",
            autoscale: "1",
            dataFormat: "json",
            dataSource: {
                "chart": chartProperties1,
                "categories": chartCategories1,
                "dataset": chartData1
            }

        });

         contentSummaryChart1.render();

    }

 renderchart();

});

sentiData is a variable I'm getting via an Ajax call (sentiData is actually the output of the getSentiCount(symbolInput) function. I've logged them into the console, and they are definitely not null. I've also checked both of them very carefully, and they are definitely in the correct format.
Here is the output of chartCategories1 - [{'category': [{'label':'08-31-2017'},{'label':'08-30-2017'},{'label':'08-28-2017'},{'label':'08-23-2017'},{'label':'08-22-2017'},{'label':'08-21-2017'},{'label':'08-16-2017'},{'label':'08-09-2017'},{'label':'08-08-2017'},{'label':'08-07-2017'},{'label':'08-03-2017'},{'label':'08-02-2017'}]}]
Here is the output of chartData1 - [{'seriesname': 'Negative','data':[{'value':'0'},{'value':'0'},{'value':'0'},{'value':'0'},{'value':'0'},{'value':'0'},{'value':'0'},{'value':'1'},{'value':'0'},{'value':'0'},{'value':'0'},{'value':'0'}]},{'seriesname': 'Positive','data':[{'value':'0'},{'value':'0'},{'value':'0'},{'value':'0'},{'value':'0'},{'value':'0'},{'value':'0'},{'value':'0'},{'value':'0'},{'value':'0'},{'value':'1'},{'value':'0'}]},{'seriesname': 'Neutral','data':[{'value':'0'},{'value':'0'},{'value':'0'},{'value':'0'},{'value':'0'},{'value':'0'},{'value':'2'},{'value':'0'},{'value':'0'},{'value':'1'},{'value':'0'},{'value':'4'}]},{'seriesname': 'Unknown','data':[{'value':'2'},{'value':'1'},{'value':'1'},{'value':'2'},{'value':'1'},{'value':'1'},{'value':'0'},{'value':'0'},{'value':'1'},{'value':'0'},{'value':'0'},{'value':'0'}]}]
Here is how the code would look like if the data was readily available and I didn't need an Ajax call to get it (in getSentiCount(symbolInput)):
FusionCharts.ready(function() {
var contentSummaryChart1 = new FusionCharts({
type: 'msbar2d',
renderAt: 'chart-container',
width: '100%',
height: '180',
dataFormat: 'json',
dataSource: {
  "chart": {
    "caption": "Sentiment",
    "bgColor": "#ffffff",
    "bgColor": "#ffffff",
    "showBorder": "0",
    "borderAlpha": "20",
    "canvasBorderAlpha": "0",
    "baseFontSize": "14",
    "usePlotGradientColor": "0",
    "plotBorderAlpha": "10",
    "showXAxisLine": "1",
    "showYAxisLine": "0",
    "showYAxisValues": "0",
    "xAxisLineColor": "#999999",
    "divlineColor": "#999999",
    "showAlternateHGridColor": "0",
    "paletteColors": "#2cb32b,#ff2602,#2786f7,#f9f70e",

  },
  "categories": [{

    'category': [{
      'label': '08-31-2017'
    }, {
      'label': '08-30-2017'
    }, {
      'label': '08-28-2017'
    }, {
      'label': '08-23-2017'
    }, {
      'label': '08-22-2017'
    }, {
      'label': '08-21-2017'
    }, {
      'label': '08-16-2017'
    }, {
      'label': '08-09-2017'
    }, {
      'label': '08-08-2017'
    }, {
      'label': '08-07-2017'
    }, {
      'label': '08-03-2017'
    }, {
      'label': '08-02-2017'
    }]

  }],
  "dataset": [{
    'seriesname': 'Negative',
    'data': [{
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '1'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }]
  }, {
    'seriesname': 'Positive',
    'data': [{
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '1'
    }, {
      'value': '0'
    }]
  }, {
    'seriesname': 'Neutral',
    'data': [{
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '2'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '1'
    }, {
      'value': '0'
    }, {
      'value': '4'
    }]
  }, {
    'seriesname': 'Unknown',
    'data': [{
      'value': '2'
    }, {
      'value': '1'
    }, {
      'value': '1'
    }, {
      'value': '2'
    }, {
      'value': '1'
    }, {
      'value': '1'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '1'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }, {
      'value': '0'
    }]
  }]
}
}).render();
});

I tried using the feedData method (both on window load and on clicking on a div), but that didn't work either.
Is there a way to render this chart using the variables chartCategories1 and chartData1? I can't use the static values format because I have different labels and values for each asset, so every window will be getting different values and displaying a different chart.

A: I figured out what I was doing wrong. User adiga was right, I wasn't creating the JSON object the right way. Below is what I ended up doing:
var dataJSON = {

                "chart": {
                "caption": "Sentiment",
                "bgColor": "#ffffff",

                "showBorder": "0",
                "borderAlpha": "20",
                "canvasBorderAlpha": "0",
                "baseFontSize": "14",
                "usePlotGradientColor": "0",
                "plotBorderAlpha": "10",
                "showXAxisLine": "1",
                "showYAxisLine": "0",
                "showYAxisValues": "0",
                "showXAxisValues": "0",
                "showLabels": "1",
                "xAxisLineColor": "#999999",
                "divlineColor": "#999999",
                "showAlternateHGridColor": "0",
                "paletteColors": "#ff2602,#2cb32b,#2786f7,#f9f70e"
              },
              "categories": [{

                "category": []

              }],
              "dataset": [{
                "seriesname": "Negative",
                "data": []
              }, {
                "seriesname": "Positive",
                "data": []
              }, {
                "seriesname": "Neutral",
                "data": []
              }, {
                "seriesname": "Unknown",
                "data": []
              }]
            };

        for (var a = 0; a < sentiData.length; a++) {
            dataJSON.categories[0].category.push({label: bdateForm(sentiData[a].bdate)});
        }

        for (var e = 0; e < sentiData.length; e++) {
                if(sentiData[e].avgsentimentvalue == "1") {
                    dataJSON.dataset[0].data.push({value: sentiData[e].totalcount});
                } else {
                    dataJSON.dataset[0].data.push({value: 0});
                }

                if(sentiData[e].avgsentimentvalue == "3") {
                    dataJSON.dataset[1].data.push({value: sentiData[e].totalcount});
                } else {
                    dataJSON.dataset[1].data.push({value: 0});
                }

                if(sentiData[e].avgsentimentvalue == "2") {
                    dataJSON.dataset[2].data.push({value: sentiData[e].totalcount});
                } else {
                    dataJSON.dataset[2].data.push({value: 0});
                }

                if(sentiData[e].avgsentimentvalue == "") {
                    dataJSON.dataset[3].data.push({value: sentiData[e].totalcount});
                } else {
                    dataJSON.dataset[3].data.push({value: 0});
                }

            }

        FusionCharts.ready(function() {
            var topStores = new FusionCharts({
                type : 'mscolumn2d',
                renderAt : 'sentimentChart',
                width : '100%',
                height : '180',
                dataFormat : 'json',
                dataSource : dataJSON

            }).render();
        });

Now my chart is rendering, but the x axis values are not showing below the table. That's another problem though, and it's not critical, so I'm closing this out.
Adiga, thanks for trying to help!


text:
Q: `phonegap run ios` -> `create: Command failed with exit code ENOENT` With PhoneGap, running phonegap run ios (as admin or not) on Windows 8 in my app's directory gives the following output:
[phonegap] detecting iOS SDK environment...
[phonegap] using the local environment
[phonegap] adding the iOS platform...
{ [Error: C:\Users\Me\.cordova\lib\ios\cordova\3.5.0\bin\create: Command failed with exit code ENOENT] code: 'ENOENT' }
  [error] C:\Users\Me\.cordova\lib\ios\cordova\3.5.0\bin\create: Command failed with exit code ENOENT

I'm trying to use it with the phonegap ios app.  What's wrong?
Thanks!

A: You can't build iOS apps on Windows.
http://docs.phonegap.com/en/3.5.0/guide_platforms_ios_index.md.html#iOS%20Platform%20Guide


text:
Q: Proguard configuration makes APK broken i'm having an issue with proguard.
After adding proguard, i was getting warnings :

Warning: com.actionbarsherlock.internal.ActionBarSherlockCompat: can't find referenced class com.actionbarsherlock.BuildConfig
  Warning: com.slidingmenu.lib.CustomViewBehind: can't find referenced class com.slidingmenu.lib.R$id
  Warning: com.slidingmenu.lib.CustomViewBehind: can't find referenced class com.slidingmenu.lib.R$id
  Warning: com.slidingmenu.lib.CustomViewBehind: can't find referenced class com.slidingmenu.lib.R
  Warning: okio.DeflaterSink: can't find referenced class org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
  Warning: okio.Okio: can't find referenced class java.nio.file.Files
  Warning: okio.Okio: can't find referenced class java.nio.file.Files
  Warning: okio.Okio: can't find referenced class java.nio.file.Files
  Warning: okio.Okio: can't find referenced class java.nio.file.Path
  Warning: okio.Okio: can't find referenced class java.nio.file.OpenOption
  Warning: okio.Okio: can't find referenced class java.nio.file.Path
  Warning: okio.Okio: can't find referenced class java.nio.file.OpenOption
  Warning: okio.Okio: can't find referenced class org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
  Warning: okio.Okio: can't find referenced class java.nio.file.Path
  Warning: okio.Okio: can't find referenced class java.nio.file.OpenOption
  Warning: okio.Okio: can't find referenced class java.nio.file.Path
  Warning: okio.Okio: can't find referenced class java.nio.file.OpenOption
  Warning: okio.Okio: can't find referenced class org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
  Warning: org.solovyev.android.checkout.ActivityCheckout: can't find referenced class javax.annotation.Nonnull
  Warning: org.solovyev.android.checkout.ActivityCheckout: can't find referenced class javax.annotation.Nonnull
  Warning: org.solovyev.android.checkout.ActivityCheckout: can't find referenced class javax.annotation.Nonnull
  Warning: org.solovyev.android.checkout.ActivityCheckout: can't find referenced class javax.annotation.Nonnull
  Warning: org.solovyev.android.checkout.ActivityCheckout: can't find referenced class javax.annotation.Nonnull
  Warning: org.solovyev.android.checkout.ActivityCheckout: can't find referenced class javax.annotation.Nonnull
  Warning: org.solovyev.android.checkout.ActivityCheckout: can't find referenced class javax.annotation.Nonnull
  Warning: org.solovyev.android.checkout.ActivityCheckout: can't find referenced class javax.annotation.Nonnull
  Warning: org.solovyev.android.checkout.ActivityCheckout: can't find referenced class javax.annotation.Nonnull
  Warning: org.solovyev.android.checkout.ActivityCheckout: can't find referenced class javax.annotation.Nonnull
  Warning: org.solovyev.android.checkout.ActivityCheckout: can't find referenced class javax.annotation.Nonnull
  Warning: org.solovyev.android.checkout.ActivityCheckout: can't find referenced class javax.annotation.Nonnull
  Warning: org.solovyev.android.checkout.ActivityCheckout: can't find referenced class javax.annotation.Nonnull
  Warning: org.solovyev.android.checkout.ActivityCheckout: can't find referenced class javax.annotation.Nonnull
  Warning: org.solovyev.android.checkout.ActivityCheckout: can't find referenced class javax.annotation.Nonnull
  Warning: org.solovyev.android.checkout.ActivityCheckout$1: can't find referenced class javax.annotation.Nonnull
  Warning: org.solovyev.android.checkout.BaseInventory: can't find referenced class javax.annotation.Nonnull
  Warning: org.solovyev.android.checkout.BaseInventory: can't find referenced class javax.annotation.Nonnull
  Warning: org.solovyev.android.checkout.BaseInventory: can't find referenced class javax.annotation.Nonnull

And so on, 661 of them. After looking for response, i've ran into it, this is how it goes :
-dontwarn com.actionbarsherlock.**
-dontwarn org.solovyev.android.**
-dontwarn okio.**
-dontwarn com.slidingmenu.**

I added this to my proguard-android.txt file, and it fixed an issue(source for this approach : Gradle Build Failure)
But now, size of an .apk file decreased from 10mb to 5mb, and, as you can guess, it's not working, just crashes.
Question: what should i do to both : remove this warnings so .apk would build, and .apk that will be build would be working?
EDIT: I've got the trace of error for release version and it has somethin to do with ormlite library, with this message :

E/AndroidRuntime(16807): java.lang.NoSuchFieldError
  E/AndroidRuntime(16807):    at libcore.reflect.AnnotationAccess.decodeValue(AnnotationAccess.java:688)
  E/AndroidRuntime(16807):    at libcore.reflect.AnnotationAccess.toAnnotationInstance(AnnotationAccess.java:663)
  E/AndroidRuntime(16807):    at libcore.reflect.AnnotationAccess.toAnnotationInstance(AnnotationAccess.java:641)
  E/AndroidRuntime(16807):    at libcore.reflect.AnnotationAccess.getDeclaredAnnotation(AnnotationAccess.java:170)
  E/AndroidRuntime(16807):    at java.lang.reflect.Field.getAnnotation(Field.java:242)
  E/AndroidRuntime(16807):    at com.tojc.ormlite.android.annotation.OrmLiteAnnotationAccessor.getAnnotationColumnName(Unknown Source)
  E/AndroidRuntime(16807):    at com.tojc.ormlite.android.framework.ColumnInfo.(Unknown Source)
  E/AndroidRuntime(16807):    at com.tojc.ormlite.android.framework.TableInfo.(Unknown Source)
  E/AndroidRuntime(16807):    at com.tojc.ormlite.android.framework.MatcherController.addTableClass(Unknown Source)
  E/AndroidRuntime(16807):    at com.tojc.ormlite.android.framework.MatcherController.add(Unknown Source)
  E/AndroidRuntime(16807):    at com.test.kovla.provider.KovlaContentProvider.a(Unknown Source)
  E/AndroidRuntime(16807):    at com.test.kovla.provider.KovlaContentProvider.onCreate(Unknown Source)
  E/AndroidRuntime(16807):    at android.content.ContentProvider.attachInfo(ContentProvider.java:1737)
  E/AndroidRuntime(16807):    at android.content.ContentProvider.attachInfo(ContentProvider.java:1712)
  E/AndroidRuntime(16807):    at android.app.ActivityThread.installProvider(ActivityThread.java:5437)
  E/AndroidRuntime(16807):    at android.app.ActivityThread.installContentProviders(ActivityThread.java:5032)
  E/AndroidRuntime(16807):    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4972)
  E/AndroidRuntime(16807):    at android.app.ActivityThread.access$1600(ActivityThread.java:177)
  E/AndroidRuntime(16807):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1491)
  E/AndroidRuntime(16807):    at android.os.Handler.dispatchMessage(Handler.java:102)
  E/AndroidRuntime(16807):    at android.os.Looper.loop(Looper.java:135)
  E/AndroidRuntime(16807):    at android.app.ActivityThread.main(ActivityThread.java:5910)
  E/AndroidRuntime(16807):    at java.lang.reflect.Method.invoke(Native Method)
  E/AndroidRuntime(16807):    at java.lang.reflect.Method.invoke(Method.java:372)
  E/AndroidRuntime(16807):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
  E/AndroidRuntime(16807):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
  E/AndroidRuntime(16807): Caused by: java.lang.NoSuchFieldException: INTEGER
  E/AndroidRuntime(16807):    at java.lang.Class.getDeclaredField(Class.java:939)
  E/AndroidRuntime(16807):    at libcore.reflect.AnnotationAccess.decodeValue(AnnotationAccess.java:685)

In fact, i've added -keep class  com.tojc.** {*;} to my proguard-android.txt and it doesn't help but only specified package right, it wasn't

com.tojc.ormlite.android.annotation.OrmLiteAnnotationAccessor.getAnnotationColumnName(Unknown
  Source)

before
Edit: If this is the list that was asked in comment :
repositories {
maven { url 'https://maven.fabric.io/public' }
jcenter()
}

A: Seems you are using bunch of libraries. Please take a look over this repository. And use the progaurd configurations.
EDIT
As per your edit, you are probably having issues with the ormlite library.
Could you try this set of progaurd rules:
-keep interface com.j256.**
-keepclassmembers interface com.j256.** { *; }
-keep enum com.j256.**
-keepclassmembers enum com.j256.** { *; }
-keep class com.j256.**
-keepclassmembers class com.j256.** { *; }

And I would insist on rebuilding the project once.


text:
Q: Correct usage of NSFileCoordinator in Swift3 I'm trying to run my program as an sandboxed app. It's a Drag&Drop PDF Converter.
Everything works fine but creating & converting the file doesn't work well since i turned it into a sandboxed app.
What i tried to do with NSFileCoordinator is:
let temporaryPath = NSTemporaryDirectory()
var temporaryFile = temporaryPath + "temp.pdf"
 var counter2 = 0;
 while (fileM.fileExists(atPath: temporaryFile))
    {
     counter2 = counter2 + 1
     temporaryFile = temporaryPath + "temp" + String(counter2) + ".pdf"
    }
let defaults: UserDefaults = UserDefaults.standard
  if (defaults.value(forKey:"countedSettings") != nil)
     {
       settings = defaults.integer(forKey: "countedSettings")
     }
let settingsAsString = String(settings)
task.arguments = [url.path!, temporaryFile, settingsAsString]
task.launch()
let furl = NSURL.fileURL(withPath: temporaryFile)
let appURL = NSURL.fileURL(withPath: appendingString)
let fc = NSFileCoordinator()
fc.item(at: furl, willMoveTo: appURL as URL)

*

*Create a temporary file

*Read and copy/move the temporary file to the resource path

I know that i use NSFileCoordinator wrong, but i dont know where to start to fix this. Can someone help me with this problem?


text:
Q: When is the Fourier transform of a discrete distribution again discrete? By discrete here, I just mean that it's a linear combination of (potentially infinitely many) delta diracs, with discrete support.
Say a discrete subset of $\mathbb{R}$ is semiperiodic if it's dirac measure satisfies the condition in the title; i.e. it's Fourier transform is a linear combination of delta diracs with discrete support in $\mathbb{C}$.

It's clear that every periodic set is semiperiodic (their dirac measure is a dirac comb), and the semiperiodic sets are closed under finite union. From this, one might conject that every semiperiodic set is a countable union of periodic sets, but strangely enough, an argument involving RH can show that this is unlikely; in particular, assuming RH and that the nontrivial zeroes of RZF are linearly independent over $\mathbb{Q}$, which are both thought likely (but unproven), they form a semiperiodic set which is not the countable union of periodic sets. There are probably unconditional examples of this as well but unfortunately I have difficulties providing constructions of semiperiodic sets apart from using dirac combs.
The structure of these sets is quite fragile; changing semiperiodic sets in small ways causes them to be no longer semiperiodic. If you add a single point to a semiperiodic set, it is no longer semiperiodic as that single point has a continuous Fourier transform which is nonzero everywhere.
Additionally, since the Fourier transform seems to be concerned with "periodic behaviours", it'd be hard to believe that you could nudge a single point in a semiperiodic set in either direction without the resulting set ceasing to be semiperiodic.

Is there some geometric insight to this that I'm missing? I'm struggling to find a pattern in these sets; they seem so rigid and immutable yet so elusive as well. What other methods are there to construct these sets, and is there some nice way to parametrize them?


text:
Q: VBA copying an Excel worksheet to a new worksheet in another workbook I have an Excel Macro that downloads stock Ticker information off Yahoo and saves it as a csv. A function is then called to process the csv, generate a chart and store resulting xlsm file as a html file.
I want to pass successive csv files into the function, process them and store resulting xlsm file into new worksheets on the original xlsm file.

   If (Year = 0) Then
        Application.DisplayAlerts = False
        ActiveWorkbook.SaveAs Filename:=FilePAth & Ticker & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
        ActiveWorkbook.SaveAs Filename:=FilePAth & Ticker & ".htm", FileFormat:=xlHtml, ReadOnlyRecommended:=False, CreateBackup:=False
    Else
        ActiveWorkbook.Copy After:=Workbooks(FilePAth & Ticker & ".xlsm").Sheets(Ticker)
        ActiveWorkbook.SaveAs Filename:=FilePAth & Ticker & ".htm", FileFormat:=xlHtml, ReadOnlyRecommended:=False, CreateBackup:=False
        Workbooks(Ticker & ".csv").Close SaveChanges:=True
    End If

The first part of the above condition creates the xlsm & htm file, the second part attempts to save the worksheet.
An error occurs on the:- ActiveWorkbook.Copy
Can anybody provide any clues please?
thanks in advance.

A: The code looks for the Master workbook. If it doe not find it, then it will open it. With the open Master workbook, the sheet can then move from on to the other. I created a universal way for it to save then close.
This is the line you need.
ThisWorkbook.Sheets(1).Copy After:=Compiled_WB.Sheets(Compiled_WB.Worksheets.Count)

Here is a Sub that puts it all together.
Sub tryit()
Application.DisplayAlerts = False
Dim Ticker As String
Ticker = "DocumentsTicker"
Dim year As Long
year = 1
Dim Compiled_WB As Workbook
If (year = 0) Then
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs Filename:=ThisWorkbook.Path & Ticker & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
    ActiveWorkbook.SaveAs Filename:=ThisWorkbook.Path & Ticker & ".htm",FileFormat:=xlHtml, ReadOnlyRecommended:=False, CreateBackup:=False
Else
    For Each Compiled_WB In Workbooks
      If InStr(Compiled_WB.Name, Ticker) > 0 Then
         GoTo already_open
    End If
  Next
    Workbooks.Open Filename:=ThisWorkbook.Path & Ticker & ".xlsm"
    For Each Compiled_WB In Workbooks
      If InStr(Compiled_WB.Name, Ticker) > 0 Then
        GoTo already_open
      End If
    Next
already_open:

    ThisWorkbook.Sheets(1).Copy After:=Compiled_WB.Sheets(Compiled_WB.Worksheets.Count)

    Dim filetype As String
    If Compiled_WB.FileFormat = 52 Then
        filetype = ".htm"
    Else
        filetype = ".xlsm"
    End If
    Compiled_WB.Save

    Compiled_WB.SaveAs Filename:=Compiled_WB.Path & "\" & Ticker & filetype, FileFormat:=xlHtml, ReadOnlyRecommended:=False, CreateBackup:=False
    Compiled_WB.Close

    Workbooks(Ticker & ".csv").Close SaveChanges:=True
   End If
   End Sub'


text:
Q: Average, minimum, maximum so in my program is where the user enters list of numbers one at a time, and when I would end the list numbers with the "end" statement which is set to -1, and once I do that I get my average, and maximum, and minimum, my problem is that when I do get the  minimum output it would be -1 everytime, I'm having trouble to remove the -1 from the array, any ideas???
import java.util.Scanner; //import scanner to user scanner tool

public class Average { //creating public class

    public static void main(String[]args) { //creating public static main

        Scanner input = new Scanner(System.in); //creating scanner input to grab user input

        System.out.println("Please enter a list of numbers, entering -1 to end the list: ");

        double[] numbers = new double[20]; //creating 20 count array
        double sum = 0;
        int count = 0;
        double average;
        int end = -1;

        for(int i = 0; i<numbers.length; i++) {

            System.out.print("Enter a number: ");
            numbers[i] = input.nextDouble();

            if(numbers[i]== end) {

             break;

            }
            sum+= numbers[i];
            count++;
        }
        // gets average from user input of numbers
        average = sum/count;
        System.out.println("Average is: " + average);
        double max = maxim(numbers);
        System.out.println("Max: " + max);
        double min = minim(numbers);
        System.out.println("Min: " + min);

    }

//method for finding out maximum number from user input

    public static double maxim(double[] array) {

        double maxNum = array[0];
        for(int i = 1; i<array.length; i++) {
            if(array[i] > maxNum) {
                maxNum = array[i];
            }
        }
     return maxNum;
    }
 //method for finding out minimum number from user input

    public static double minim(double[] array) {

        double minNum = array[0];
        for(int i = 1; i<array.length; i++) {
               if(array[i] < minNum && array[i]!=-1) {
                minNum = array[i];
            }

        }
     return minNum;
    }

}

A: You could take the input into a temp variables and store it in the array only if it isn't the end flag (-1). E.g.:
for(int i = 0; i<numbers.length; i++) {

    System.out.print("Enter a number: ");
    double temp = input.nextDouble();

    if(temp == end) {
        break;
    }
    numbers[i] = temp;
    sum += numbers[i];
    count++;
}

A: You need to docouple part of code that responsible for reading user input from code that compute statistics. And for remove -1 from resulting array you need simple don't put this value to result. When user input random number first check if it is not -1, and after that put it in result. Something like that:
import java.util.Scanner;

public class Average {

    public static void main(String[]args) { //creating public static main
        double[] numbers = readInputNumbers();
        System.out.println("Average is: " + average(numbers));
        System.out.println("Max: " + max(numbers));
        System.out.println("Min: " + min(numbers));
    }

    public double[] readInputNumbers() {
      Scanner input = new Scanner(System.in); //creating scanner input to grab user input
      System.out.println("Please enter a list of numbers, entering -1 to end the list: ");
      double[] numbers = new double[20];
      final int endInput = -1;
      for(int i = 0; i < numbers.length; i++) {
          System.out.print("Enter a number: ");
          double nextNumber = input.nextDouble();
          if(nextNumber == endInput) {
              break;
          } else {
              numbers[i] = nextNumber;
          }
      }
      return numbers;
  }

    public static double max(double[] array) {
        double maxNum = array[0];
        for(int i = 1; i<array.length; i++) {
            if(array[i] > maxNum) {
                maxNum = array[i];
            }
        }
     return maxNum;
    }

    public static double min(double[] array) {
        double minNum = array[0];
        for(int i = 1; i<array.length; i++) {
               if(array[i] < minNum && array[i]!=-1) {
                minNum = array[i];
            }

        }
     return minNum;
    }

    public static double average(double[] numbers) {
        double sum = 0;
        for(int i = 0; i < numbers.length; i++) {
            sum = sum + numbers[i];
        }
        return sum / numbers.length;
    }

}

In jdk since 8 version your could be simplify this task like this:
import java.util.Scanner;
import java.util.stream.*;

public class Average {

    public static void main(String[]args) { //creating public static main
        double[] numbers = readInputNumbers();
        DoubleSummaryStatistics statistics = DoubleStream.of(numbers).summaryStatistics();
        System.out.println("Average is: " + statistics.getAverage()));
        System.out.println("Max: " + statistics.getMax());
        System.out.println("Min: " + statistics.getMin());
    }

    public double[] readInputNumbers() {
        Scanner input = new Scanner(System.in); //creating scanner input to grab user input
        System.out.println("Please enter a list of numbers, entering -1 to end the list: ");
        double[] numbers = new double[20];
        final int endInput = -1;
        for(int i = 0; i < numbers.length; i++) {
            System.out.print("Enter a number: ");
            double nextNumber = input.nextDouble();
            if(nextNumber == endInput) {
                break;
            } else {
                numbers[i] = nextNumber;
            }
        }
        return numbers;
    }
}


text:
Q: Making dropped clone element draggable again I have a few table-blocks, and whole table with workout cells .
When dragging I use helper to clone .table-block and later I append it to .workout-cell on drop. When dropped to .workout cell I can't move it anymore. I want to make it draggable again within the table, and be able to move it. How to do this?
Here is code:
$( ".table-block" ).draggable({
  helper : "clone",
});

$(".workout-cell").droppable({
  drop: function(ev, ui) {
    var element=$(ui.draggable).clone();
    $(this).append(element);
  }
});

A: You need to call .draggable on the cloned element:
$(".workout-cell").droppable({
  drop: function(ev, ui) {
    var element=$(ui.draggable).clone();
    $(this).append(element);
    $(element).draggable({helper: 'clone'});
  }
});


text:
Q: Decision Tree - Must be a better way...? Below is my way, albeit a basic way of creating a Decision Tree...The problem is the CSS is getting way out of control and the code  is just awful...is there a better way?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<?php
// Managed or Unmanaged
if ($_GET['st'] == "managed"){
$a1 = "answer-left";
$switch_type = $_GET['st'];
}
else if ($_GET['st'] == "unmanaged"){
$a1 = "answer-right";
$switch_type = $_GET['st'];
}
else if ($_GET['st'] == "smart"){
$a1 = "answer-mid";
$switch_type = $_GET['st'];
}
else {
echo "";
}
// Fast Ethernet or Gigabit
if (($_GET['st'] == "managed") && ($_GET['ss'] == 100)){
$a2 = "answer-left-left";
$switch_type = $_GET['st'];
$switch_speed = $_GET['ss'];
}
else if (($_GET['st'] == "managed") && ($_GET['ss'] == 1000)){
$a2 = "answer-left-right";
$switch_type = $_GET['st'];
$switch_speed = $_GET['ss'];
}
else if (($_GET['st'] == "unmanaged") && ($_GET['ss'] == 100)){
$a2 = "answer-right-left";
$switch_type = $_GET['st'];
$switch_speed = $_GET['ss'];
}
else if (($_GET['st'] == "unmanaged") && ($_GET['ss'] == 1000)){
$a2 = "answer-right-right";
$switch_type = $_GET['st'];
$switch_speed = $_GET['ss'];
}
else if (($_GET['st'] == "smart") && ($_GET['ss'] == 100)){
$a2 = "answer-mid-left";
$switch_type = $_GET['st'];
$switch_speed = $_GET['ss'];
}
else if (($_GET['st'] == "smart") && ($_GET['ss'] == 1000)){
$a2 = "answer-mid-right";
$switch_type = $_GET['st'];
$switch_speed = $_GET['ss'];
}
else {
echo "";
}
?>

Small Business Decision Tree

Managed or Unmanaged

Managed

Smart

Unmanaged

<?
if (isset($_GET['st'])) {
echo"

Switch Speed?

Fast Ethernet (10/100)

GigabitEthernet (1000)

";
    }
else {
echo "";
}
?>
<?
if (isset($_GET['ss'])) {
echo"

Switch Size?

Desktop

Rack-mountable

";
    }
else {
echo "";
}
?>

Thanks,
B.

A: At first you could take the lines
$switch_type = $_GET['st'];
$switch_speed = $_GET['ss'];

out of the conditions, they are the same everywhere. Just do it once before or after the if/elses.
Furthermore I see, that each sub-part of $a2 depends on a specific condition. Maybe you can construct it the following (pseudo-code) way:
...
//$a2 always starts the same
$a2 = "answer";

// Type of line
switch($_GET['st']) {
  case "managed":
    $a2 = $a2 + "-left"; break;
  case "unmanaged":
    $a2 = $a2 + "-right"; break;
  case "smart":
    $a2 = $a2 + "-mid"; break;
}

// speed of line
switch($_GET['ss']) {
  case 100:
    $a2 = $a2 + "-left"; break;
  case 1000:
    $a2 = $a2 + "-right"; break;
}
....

After that $a2 should hold your combined values like 'answer-left-right' and so on. A similar approach could be done with $a1 but I chose $a2 for the example as it's better suited here.

A: I've used associative arrays for this in the past.
In your case, you should be parsing $_GET["st"] & $_GET["ss"] at the top of the script. So you can grab those into two variables $st and $ss (and you should be doing validation on them as well!). Taken that as given, you can come up with something like:
$st_choices = array (
    'managed'    => array (
        '1000'         =>  array (
            'key1'          => 'val1',
            'key2'          => 'val2'
         );
     ),
     'a1'        => 'answer-left',
     'a2'        => 'another-value'

     /** ... **/
);

Then, you use a lookup function to access the array.
Adding more elements means simply adding to the array in the format above, instead of adding more if/else if/else branches.
function return_details($st, $ss) {
    $vals = array();

    if (isset($st_choices[$st]) && isset($st_choices[$st][$ss])) {
        $vals['a1'] = $st_choices[$st]["a1"];
        $vals['a2'] = $st_choices[$st]["a2"];
        $vals['key1'] = $vals[$st][$ss]['key1'];
    }
}

Depending on your situation, you may need to wrap those assignments in isset() also.


text:
Q: Basic question about Sobolev spaces involving time I'm working with Evans PDE book and I can't understand this:
Let $U\subset \mathbb{R}^n$ open and $u\in L^{2}([0,T], H_0^1(U))$ with $u' \in L^2([0,T] , H^{-1}(U))$ and now we consider the mollifications of $u$ and $u'$.
Why this is correct?
For $\epsilon, \delta >0$,
$$\frac{d}{dt} \|u^{\epsilon}(t)- u^{\delta}(t) \|^2_{L^2(U)} = 2\langle u^{\epsilon'}  - u^{\delta'},u^{\epsilon}  - u^{\delta}\rangle  $$

A: Once you convolve $u, u'$ with say a gaussian, they become smooth $\forall t > 0$ (with compact support).  Then this equality comes down to "moving the derivative inside the integral":
\begin{eqnarray*}
\frac{d}{dt} \|u^{\epsilon}(t)- u^{\delta}(t) \|^2_{L^2(U)} &=&
\frac{d}{dt} \int_U |u^{\epsilon}(t)(x) - u^{\delta}(t)(x) |^2 dx \\ &=&
\int_U \frac{d}{dt}  |u^{\epsilon}(t)(x) - u^{\delta}(t)(x) |^2 dx \\ &=&
\int_U  2(u^{\epsilon'}(t)(x)- u^{\delta'}(t)(x))(u^{\epsilon}(t)(x)- u^{\delta}(t)(x))  dx \\
 &=& 2\langle u^{\epsilon'}(t)  - u^{\delta'}(t),u^{\epsilon}(t)  - u^{\delta}(t)\rangle  \\
\end{eqnarray*}
You can move the derivative inside due to Leibniz' Integral Rule.


text:
Q: Upload file without manually constructing HTTP POST with "multipart/form-data; boundary" As iOS programming newbie I wonder, if there is a clean way to upload a file from iPhone to a PHP script - without constructing an awkward custom POST request with multipart/form-data; boundary stuff.
Preferrably using Apple libraries (iOS 7 only is ok) only or at least some clean open source code.
The PHP part I can create myself, but for the Objective C part I've only been able to find examples, which "reinvent" the POST method...

A: ASIHTTPRequest is a popular open source library to handle something like this.


text:
Q: Mathematica or math question: why my own Monte Carlo gives different result from the Mathematica's one? Consider some function of arguments x,y,z, where the latter have some domain of definition $\mathcal{R}$:
function[x_, y_, z_] = Exp[-x^2]/(y^2 + 1.23)*Exp[-z];
zmin[x_, y_] = x + y*Exp[-y^2];
zmax[x_, y_] = 3.4*(x + 1.2*y*Exp[-y]);
ymin[x_] = 0.1*x*Exp[-x^3 - x^2] + 0.1*Exp[-Cos[x]^2];
ymax[x_] = x*Exp[-x^((2/3.)) + 1] + 0.22*Exp[-Cos[x]^4];
xmin = 0;
xmax = 10;

I need to evaluate an integral
$$
\mathcal{I} = \int \limits_{x_{\text{min}}}^{x_{\text{max}}}dx \  \int \limits_{y_{\text{min}}}^{y_{\text{max}}}dy \ \int \limits_{z_{\text{min}}}^{z_{\text{max}}}dz \ f(x,y,z)
$$
For some reason, I would like to implement my own simple Monte Carlo integration. Namely, I start with the formula
$$
\tag 1 \mathcal{I} \approx \frac{\Phi}{N}\sum_{i = 1}^{N}f(x_{i},y_{i},z_{i}), \quad \text{where} \quad \Phi = \int \limits_{x_{\text{min}}}^{x_{\text{max}}}dx\ \int \limits_{y_{\text{min}}}^{y_{\text{max}}}dy \ \int \limits_{z_{\text{min}}}^{z_{\text{max}}}dz, \quad (x_{i},y_{i},z_{i}) \in \mathcal{R}
$$
First, I evaluate the phase space $\Phi$:
Measure =
 NIntegrate[
  1, {x, xmin, xmax}, {y, ymin[x], ymax[x]}, {z, zmin[x, y],
   zmax[x, y]}]

84.0468

Next, I generate random points belonging to $\mathcal{R}$:
RandomxValues[Nevents_] := RandomReal[{xmin, xmax}, Nevents]
RandomyValues =
 Hold@Compile[{{RandomxValuesTable, _Real, 1}},
      Table[RandomReal[{ymin[RandomxValuesTable[[i]]],
         ymax[RandomxValuesTable[[i]]]}], {i, 1,
        Length[RandomxValuesTable], 1}], CompilationTarget -> "C",
      RuntimeOptions -> "Speed"] /. DownValues@ymin /.
   DownValues@ymax // ReleaseHold;
RandomzValues =
 Hold@Compile[{{RandomxValuesTable, _Real,
        1}, {RandomyValuesTable, _Real, 1}},
      Table[RandomReal[{zmin[RandomxValuesTable[[i]],
          RandomyValuesTable[[i]]],
         zmax[RandomxValuesTable[[i]], RandomyValuesTable[[i]]]}], {i,
         1, Length[RandomxValuesTable], 1}], CompilationTarget -> "C",
       RuntimeOptions -> "Speed"] /. DownValues@zmin /.
   DownValues@zmax // ReleaseHold;
RandomxyzPoints[Nevents_] := Block[{},
  RandomxValuesTable = Quiet[RandomxValues[Nevents]];
  RandomyValuesTable = Quiet[RandomyValues[RandomxValuesTable]];
  RandomzValuesTable =
   Quiet[RandomzValues[RandomxValuesTable, RandomyValuesTable]];
  Join[Partition[RandomxValuesTable, 1],
   Partition[RandomyValuesTable, 1], Partition[RandomzValuesTable, 1],
    2]
  ]
(*An example demonstrating the performance of RandomxyzPoints*)
randomPointsTable = RandomxyzPoints[10^6]; // AbsoluteTiming

{0.209248,Null}

It looks like the generator works properly:
randomPointsTable1 = RandomxyzPoints[10^4];
Show[ListPointPlot3D[randomPointsTable1],
 DiscretizeRegion[
  ImplicitRegion[
   xmin < x < xmax && ymin[x] < y < ymax[x] &&
    zmin[x, y] < z < zmax[x, y], {x, y, z}](*,{{xmin,xmax},{0,30},{0,
  30}}*)]]

Finally, my Monte Carlo integral is
FunctionSum =
 Hold@Compile[{{randomPointsTable, _Real, 2}},
     Sum[function[randomPointsTable[[i]][[1]],
       randomPointsTable[[i]][[2]], randomPointsTable[[i]][[3]]], {i,
       1, Length[randomPointsTable], 1}], CompilationTarget -> "C",
     RuntimeOptions -> "Speed"] /. DownValues@function // ReleaseHold
MonteCarloMy[Nevents_] :=
 Measure/Nevents*FunctionSum[RandomxyzPoints[Nevents]]

Comparing with
MonteCarloMathematica =
 NIntegrate[
  function[x, y, z], {x, xmin, xmax}, {y, ymin[x], ymax[x]}, {z,
   zmin[x, y], zmax[x, y]}, Method -> "MonteCarlo"]

0.131921

I find
MonteCarloMy[10^6]

1.49451

My question is: am I stupid since Eq. (1) is incorrect, or I made something wrong in the implementation?
An edit.
Let us simplify the domain of the definition of x,y,z, such that they are all independent:
zmin[x_, y_] = 0;
zmax[x_, y_] = 13;
ymin[x_] = 1.34;
ymax[x_] = 144;
xmin = 0;
xmax = 10;

and relaunch all the remaining code. The results, however, are still different:
MonteCarloMy[10^6]/MonteCarloMathematica

0.8007

I do not understand the reason for this discrepancy.
Edit 2.
So, if continuing with my method, following comments and the answer, I need to define $\Delta z[x,y] = \int\limits_{\mathcal{R}_{x,y}} dz$, $\Delta y[x] = \int\limits_{\mathcal{R}_{x}} dy$, and instead of pure sum of function I need to multiply it with the weights $\Delta z
\times \Delta y$, and divide by the sum of $\Delta z \times \Delta y$.

A: There are two issues at play: Non-uniform sampling and bad convergence.
First, let's consider your example with independent region bounds:
zmin[x_, y_] = 0;
zmax[x_, y_] = 13;
ymin[x_] = 1.34;
ymax[x_] = 144;
xmin = 0;
xmax = 10;

MonteCarloMathematica =
 NIntegrate[
  function[x, y, z], {x, xmin, xmax}, {y, ymin[x], ymax[x]}, {z,
   zmin[x, y], zmax[x, y]}, Method -> "MonteCarlo"]
(* NIntegrate::maxp: The integral failed to converge after 50100 integrand evaluations. NIntegrate obtained 0.4398652196837818` and 0.06682921207520477` for the integral and error estimates. *)
(* 0.439865 *)

MonteCarloMy[10^5]
(* 0.509626 *)

As you note, the results don't appear to match. However, read the warning produced by Mathematica: It estimates that the integral (including error) is 0.440 +- 0.067, which actually matches your result. This is a good point to emphasize again that you should not ignore warning messages produced by Mathematica, especially not numerical methods that might want to warn you about issues. Giving both methods more sampling points reduces the discrepancy:
MonteCarloMathematica =
 NIntegrate[
  function[x, y, z], {x, xmin, xmax}, {y, ymin[x], ymax[x]}, {z,
   zmin[x, y], zmax[x, y]}, Method -> "MonteCarlo", MaxPoints -> 10^8]
(* 0.548626 *)

MonteCarloMy[10^8]
(* 0.546474 *)

Next, to your original situation: As noted by others, your sampling is far from uniform:
function[x_, y_, z_] = Exp[-x^2]/(y^2 + 1.23)*Exp[-z];
zmin[x_, y_] = x + y*Exp[-y^2];
zmax[x_, y_] = 3.4*(x + 1.2*y*Exp[-y]);
ymin[x_] = 0.1*x*Exp[-x^3 - x^2] + 0.1*Exp[-Cos[x]^2];
ymax[x_] = x*Exp[-x^((2/3.)) + 1] + 0.22*Exp[-Cos[x]^4];
xmin = 0;
xmax = 10;

Graphics3D[{AbsolutePointSize@1, Point@RandomxyzPoints[10^5]},
 BoxRatios -> {1, 1, 1}]

Using (highly unoptimized) rejection sampling, we get the following:
function[x_, y_, z_] = Exp[-x^2]/(y^2 + 1.23)*Exp[-z];
zmin[x_, y_] = x + y*Exp[-y^2];
zmax[x_, y_] = 3.4*(x + 1.2*y*Exp[-y]);
ymin[x_] = 0.1*x*Exp[-x^3 - x^2] + 0.1*Exp[-Cos[x]^2];
ymax[x_] = x*Exp[-x^((2/3.)) + 1] + 0.22*Exp[-Cos[x]^4];
xmin = 0;
xmax = 10;

yminGlobal = First@Minimize[{ymin[x], xmin <= x <= xmax}, x]
(* 0.0367879 *)

ymaxGlobal = First@Maximize[{ymax[x], xmin <= x <= xmax}, x]
(* 1.33353 *)

zminGlobal =
 First@Minimize[{zmin[x, y], xmin <= x <= xmax,
    yminGlobal <= y <= ymaxGlobal}, {x, y}]
(* 0.0367382 *)

zmaxGlobal =
 First@Maximize[{zmax[x, y], xmin <= x <= xmax,
    yminGlobal <= y <= ymaxGlobal}, {x, y}]
(* 35.5009 *)

RandomxyzPoint :=
 With[{x = RandomReal[{xmin, xmax}],
   y = RandomReal[{yminGlobal, ymaxGlobal}],
   z = RandomReal[{zminGlobal, zmaxGlobal}]},
  Quiet@If[
    ymin[x] <= y <= ymax[x] && zmin[x, y] <= z <= zmax[x, y], {x, y,
     z}, RandomxyzPoint]
  ]

RandomxyzPoints[Nevents_] := Table[RandomxyzPoint, Nevents]

MonteCarloMathematica =
 NIntegrate[
  function[x, y, z], {x, xmin, xmax}, {y, ymin[x], ymax[x]}, {z,
   zmin[x, y], zmax[x, y]}, Method -> "MonteCarlo", MaxPoints -> 10^6]
(* 0.132109 *)

MonteCarloMy[10^6]
(* 0.13359 *)


text:
Q: How to get tensorflow session from within tf.estimator.Estimator? Where is this documented? Are estimators still recommended or are they just added tech debt onto your learning curve?
Want to get a sess inside the functions you pass to estimator. model_fn, input_fn etc.

A: TensorFlow Estimators are being phased-out in TF 2.0. Keras Models are now the recommended high-level API (youtube source)
I'm not sure what you want to do with the session, but a convenient way to access it is using a SessionRunHook
You can define a new hook, and pass it to the estimator with e.g.
estimator.train(input_fn=train_input_fn, hooks=[my_custom_hook])


text:
Q: File Type To Program Associations And File Location(Windows) In Windows if I have a program association set to invoke my program to open/edit a data file with a specific extension, how will my program - once invoked - know the path and filename of the data file? Preferably solutions using batch, C++, or C. -Tom

A: Look at the command line arguments (i.e. %1, %2... for batch, argv[1]... for C++, C) - they should hold the path and name of the .gb file (or if there's no path, at least a name relative to the current working directory).


text:
Q: Groupby to find min date with conditions in Python I have like 3 columns in a data frame for example
Column_A has 2 categorical values like A,B
Column_B also has 3 categorical values like Type1, Type2, Type3
Date column has values like 2010-06-13,2010-06-10
There are about 20,000 rows so the Categorical Column A,B's values keep repeating.
So  I need the find min date where Column_A='A' and Column_B='type 1' using Python(Pandas,Numpy)

A: Use boolean index with loc and min:
df.loc[(df['Column_A'] == 'A') & (df['Column_B'] == 'type 1'), 'Date'].min()


text:
Q: "RET" in MSP430 taking me to the wrong place? So I'm programming a simple Call function for the MSP430FG4168. And it's working perfectly, except when it comes time to RETURN to the caller, the function simply dumps me back at the beginning of the callee function.
It's a multiply function that takes the values in R13 and R14.
Here's the Function file code:
#include "MSP430.h"

Extern main ;allows the function to be aware of main
PUBLIC mult

zero  DB   0;

RSEG CODE

mult:

PUSH R7; store the value of R7 on the stack for future reference
CLR  R7
MOV  R14, R7; R14's value will be used as a counter. R13 will be added the number of times specified in R14 and the final value will be stored in R14.

CLR R14

DEC R7

f_loop:

ADD R13, R14
DEC R7
CMP zero, R7
JGE f_loop;

f_end:
POP R7; bring the value of R7 BACK from the stack.
RET
END

"RET" is where my problem is. Instead of returning me to my caller, it brings me back to the beginning of mult. What's going on?

A: You're probably somehow messing up the caller's set of registers, or something like a ISR messes up the stack (SP): RET is not really an 430 instruction, but implemented as MOV @SP+,PC, and the same goes for POP (which is MOV @SP+,destination).


text:
Q: Express, run code on a seperate thread on server My Issue

I have a form where when the user submits, I want the server to start a separate  thread and run a function in that thread, then redirect the user back to the main page, where the connection can be closed and the code will still run.

Essentially the goal is that the user clicks a button, the form submits and the server runs the code without the user having to stay on the page.
app.get('/lockout/', async (req, res) => {
var nnumber = req.query.nnumber;
var time = req.query.time;

for (var i = 0; i < time; i++) {
    console.log(nnumber + " is locked out");
    sleep(1000);
}

res.send("Locked out");
});

Notes

Please excuse my inexperience with Node and express, I am new to this so please explain thoroughly, my main languages are C# and C++. I am running an Ubuntu VPS with nginx reverse proxy on DigitalOcean.

A: What you want to do is called "Asynchronus task processing" and needs some more things to it.
I would use bull as a framework to work with your Queue based on Redis. This will let you store a form submit request in a queue and process it in a new process and the user can close the connection after submitting the form.
In NodeJs it could look like
npm install bull --save

const Queue = require('bull');
//....

export class FormQueue{
  constructor(){
    // initialize queue
    this.queue = new Queue('formSubmits');
    // add a worker
    this.queue.process('forms', job => {
      this.sendEmail(job)
    })
  }
  addFormToQueue(data){
    this.queue.add('forms', data)
  }
  async sendEmail(job){
    const { to, from, subject, text, html} = job.data;
    const msg = {
      to,
      from,
      subject,
      text,
      html
    };
    try {
      await sgMail.send(msg)
      // mark the task as complete.
      job.moveToCompleted('done', true)
    } catch (error) {
      if (error.response) {
        job.moveToFailed({message: 'job failed'})
      }
    }
  }
}

Credits / More Information: https://blog.logrocket.com/asynchronous-task-processing-in-node-js-with-bull/