text:
Q: Generating a lognormal distribution from an array in Java I didn't find any help on the subject so I'm posting a new question about it. I have a variable containing three values {min, average, standard dev.}. How do I generate a lognormal distribution of this array that would randomly give me a value of the time from the lognormal distribution. Also If I would run it 1000 times I would want to randomly get a value of the time from the lognormal distribution each of the 1000 times. How would I write this in java code? Also I guess running it 1000 times would give me an average of the average in the array?

A: First, generate standard normal values and convert them to a normal distribution with given parameters. Finally, raise to exponential to get log-normal distribution with given mean and std dev.
Random rng = new Random(0);
double[] logNormalValues = new double[1000];

for (int i = 0; i < logNormalValues.length; i++) {
    double stdNormal   = rng.nextGaussian();
    double normalValue = stdDev * stdNormal + mean;

    logNormalValues[i] = Math.exp(normalValue);
}

A: you can also get a built in function here.  in your above example, you won't actually end up with the stddev and mean noted -- they change when you exp() the values.
https://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/distribution/LogNormalDistribution.html

A: or this
public static double LogNormal(double mean, double stddev) {
    Random randGen = new Random();
    double varx = Math.pow(stddev, 2);
    double ess = Math.log(1.0 + (varx/Math.pow(mean,2)));
    double mu = Math.log(mean) - (0.5*Math.pow(ess, 2));
    return Math.pow(2.71828, (mu+(ess*randGen.nextGaussian() ) ) );

}


text:
Q: calculate the difference between two datetimes I have two primefaces calendar component as following :
<h:outputLabel value="#{prezmsg['MAINTENANCE.DATE_DEBUT']}"/>
<p:calendar id="dateDebut-create"
            value="#{maintenanceMBean.webBean.vo.dateDebut}"
            pattern="dd-MM-yyyy HH:mm:ss" mask="true">
    <p:ajax event="dateSelect" listener="#{maintenanceMBean.webBean.dateDiff}"/>
</p:calendar>
<p:message for="dateDebut-create"/>

<h:outputLabel value="#{prezmsg['MAINTENANCE.DATE_FIN']}"/>
<p:calendar id="dateFin-create"
            value="#{maintenanceMBean.webBean.vo.dateFin}" pattern="dd-MM-yyyy HH:mm:ss"
            mask="true">
    <p:ajax event="dateSelect" listener="#{maintenanceMBean.webBean.dateDiff}"/>
</p:calendar>
<p:message for="dateFin-create"/>

so I want to calculate the difference in only time between these two calendar components, and put the value in another calendar which is time only.
<h:outputLabel value="#{prezmsg['MAINTENANCE.DUREE']}"/>
                <p:calendar id="duree-create" value="#{maintenanceMBean.webBean.vo.duree}" pattern="HH:mm:ss"
                            timeOnly="true" readonly="true"/>
                <p:message for="duree-create"/>

When I select the start date and the end date this function is triggered :
public void dateDiff(SelectEvent event){
        if(getVo().getDateDebut() != null && getVo().getDateFin() != null){

            Date calculatedTime = null;
            long diff = getVo().getDateFin().getTime() - getVo().getDateDebut().getTime();
            long diffSeconds = diff / 1000 % 60;
            long diffMinutes = diff / (60 * 1000) % 60;
            long diffHours = diff / (60 * 60 * 1000);

            try {
                calculatedTime =  new SimpleDateFormat("HH:mm:ss").parse(diffHours+":"+diffMinutes+":"+diffSeconds);
                System.out.print("Calculated Time : " + calculatedTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            getVo().setDuree(calculatedTime);
        }
    }

so in console I've this message : Calculated Time : Fri Jan 02 00:00:00 GMT 1970 and I no value for the third componenet is set.

A: Your Ajax event needs to update third calendar component once you've calculated the difference:
<p:ajax event="dateSelect"
listener="#{maintenanceMBean.webBean.dateDiff}" update="duree-create"/>

redpajama_set_name: RedPajamaStackExchange


text:
Q: BrowseForfolder command not working ;!@Install@!UTF-8!
BrowseForfolder="Yes"
RunProgram="Patch.bat"
DeleteTempFiles="No"
;!@InstallEnd@!

the above code exist in my config.txt file .BrowseForfolder command is not working when i try to run my exe file.(i means the window dialog not appearing to select the path.). directly it is executing my 'Patch.bat' script. Kindly help me on this regard.

A: Actually i used 7zS.sfx for self extracting.but this 7z sfx won't conatin all the properties which i mentioned in the program (i.e BrowseForfolder,DeleteTempFiles).so i used the modeified version of 7z sfx.which is 7zsd.sfx it solved the issue.


text:
Q: Zoom extent issue in d3 axis I am using d3 axis to show the bar graph and i have added zoom interaction to it.
I am adding zoom interaction like this,
d3.zoom(xScale).on("zoom", jQuery.proxy(function(){
       //Do somthing on zooming.
       },this));
},this));

On Zooming the axis i have to get the at what level the axis is zoomed,
suppose consider i have time axis on zooming it will show the labels in day level, after zooming again it will show the axis in hour level. So how to get whether it is zoomed in day level or hour level after zooming?

A: Assuming you are targeting d3 version 4, the best way to handle this is with the zoom functionality's rescaleX.  Say we have the following zoom handler where x is the scale tied to the x-axis:
function zoomed() {
  var newScale = d3.event.transform.rescaleX(x));
  console.log(newScale.domain());
}

Would log the bounds (min/max) of your zoomed axis.


text:
Q: Why won't this Javascript scroll function work? I am mightily confused to why this won't run. I am trying to get the click to scroll button to scroll down.
https://jsfiddle.net/n9jqvas9/
<script>
 $("button").click(function() {
    $('html,body').animate({
     scrollTop: $("s2text").offset().top},
    'slow');
  });
</script>

A: You are missing both jQuery (in your example) and a dot before s2text because it is a class.
$("#button").click(function() {
    $('html,body').animate({
        scrollTop: $(".s2text").offset().top},
        'slow');
  });

Here is your updated jsfiddle.

A: You need to add JQuery library and set the class selector:
$(".s2text").offset().top

Intead:
$("s2text").offset().top

Working example.

A: You are missing the dot (.) class name.

$("button").click(function() {
    $('html,body').animate({
        scrollTop: $(".s2text").offset().top},
        'slow');
  });


text:
Q: Linker error LNK2019 and LNK1120 I know this problem is well known, but none of the solutions work for me. I know a popular cause of this error is the compiler can't find the definition of a function in any of the source files, but I have defined the function them.
I am using Visual studio 2015 community.
Form.h
#pragma once
template<typename T>
class Form
{
public:
    void GenerateForm(T i);
};

Form.cpp
#include "stdafx.h"
#include "Form.h"

template<typename T>
void Form<T>::GenerateForm(T i)
{
    std::cout << i << endl;
}

Main.cpp
#include "stdafx.h"
#include "Form.h"

int main()
{
    Form<int> f;
    f.GenerateForm(12);
    return 0;
}

Error:
PrimeForm.obj : error LNK2019: unresolved external symbol "public: void __thiscall Formula<double>::GenerateForm(int)" (?GenerateForm@?$Formula@N@@QAEXH@Z) referenced in function _main
C:\Users\John\Dropbox\Visual Studio 2015\PrimeForm\Debug\PrimeForm.exe : fatal error LNK1120: 1 unresolved externals

A: When you try to compile form.cpp the compiler doesn't know what type T will be. Therefore it won't be able to compile this as an object file to be linked with your compiled main.cpp object file.
You'll need to include all of the declarations and definitions of a templated class to the files that need it (in this case your main.cpp file).
This can be simply done as follows:
Form.h
 #pragma once
 template<typename T>
 class Form
 {
 public:
     void GenerateForm(T i);
 };

 #include "Form.template"  /* Note include Form.template here */

Form.template
#include "stdafx.h"
/* Don't include form.h in this file */

template<typename T>
void Form<T>::GenerateForm(T i)
{
    std::cout << i << std::endl;
}

main.cpp
#include "stdafx.h"
#include "Form.h"  /* including Form.h will include Form.template as well */

int main()
{
    Form<int> f;        /* Compiler now knows to instantiate a Form class with type Int as the template parameter */
    f.GenerateForm(12);
    return 0;
}

Note the main difference is that you don't include "Form.h" in Form.template but include "Form.template" at the bottom of Form.h
It is better practice to use the ".template" file ending for templated class implementation files.


text:
Q: Повторить запрос при 202 коде Android Kotlin Мне нужно реализовать повтор запроса если приходит 202 код используя RxJava 2, проблема в том что когда я пытаюсь это сделать, то при 202 коде в ответе от сервера пусто, а при успешном ответе приходит нужная модель, поэтому при 202 коде получаю ошибку, и дальнейшей обработки по коду ответа не происходит.
@GET("dogs")
fun getDogs(): Observable<Response<Any>>

Это обработка ответа
private inline fun <reified T> Observable<Response<Any>>.handle202(): Observable<T> {
        return this
            .flatMap {
                when (it.code()) {
                    HttpStatusCode.ACCEPTED -> {
                        Observable.timer(1, TimeUnit.SECONDS)
                            .flatMap {
                                this.flatMap {
                                    if (it.code() == HttpStatusCode.ACCEPTED) {
                                        throw HttpException(202, "", emptyMap(), "")
                                    }
                                    Observable.just(it.body() as T)
                                }
                            }
                    }
                    else -> {
                        Observable.just(it.body() as T)
                    }
                }
            }
    }

При дебаге ловлю это:


text:
Q: Export files from Xcode project I currently have an Xcode workspace with an app project and the pod project (as commonly happens). I would like to "export" some of the files containing classes and structs that would be preparatory for a new project that should begin soon. These files are totally separate from each other and should not be exported as a library or framework because that should require to keep everything updated. Instead, I would rather bring these files out of the app project, but keep them into the workspace. Is it possibile? If so, how can I achieve this goal?

A: When you want to keep your common code and be able to maintain it as one code on both projects then I suggest you still use a framework. It is hard to tell from your question what you mean by "because that should require to keep everything updated" but using a framework within your workspace works awesomely in Xcode and any change you do within framework is instantly reflected in your code. So no extra  deployment work is needed at all. To do so you simply do the following:

*

*Create a new project selecting Framework

*When creating the project select your workspace from dropdown menu (it is at step where you select project folder location)

*In Xcode file navigator in newly created framework project open "Products" directory which should contain (in red) FrameworkName.framework

*Open your main project target settings and open General, scroll down to Frameworks, Libraries... and drag that .framework file in this list

That is all. Now you can use your framework in your code. Simply import it in any Swift file you want to.
If at this point you are worried that you need to add import MyFramework into each and every Swift file where you use it then there is a shortcut. You can simply add a new Swift file and use type aliases to avoid this problem:
import MyFramework

typealias Class1 = MyFramework.Class1
typealias Class2 = MyFramework.Class2
typealias Class3 = MyFramework.Class3

Not the cleanest solution but it does the job.
On the other hand if you wish to extract files and use them in a new project but not share the code. So then each of the projects may eventually end up with different implementations of these files then you need to duplicate the files. You can do that easiest with file system by copying source files themselves.
You can then put them into workspace under whatever you want. If you wish that currently none of the projects contain these files you may simply select files in Xcode and uncheck Target Membership for all projects on file settings.


text:
Q: GCC Linking with .o file I'm trying to compile my code but it isn't working. I got this to compile at school but I can't compile this on my home computer. I can't seem to figure out why. I need this error fixed in order to continue my assignment. Also, this list.o file is the profs file. I have to use this file.
Solutions I've tried kind of?
I've updated gcc to gcc-7.
I've located libc.a
/usr/lib/x86_64-linux-gnu/libc.a
/usr/share/doc/libklibc/README.klibc.arch

Edit: I have tried compiling without -fPIC
gcc -m64 -pthread -Wall -std=c99 -o run main.o as2.o list.o
/usr/bin/ld: list.o: relocation R_X86_64_32S against undefined symbol...

This is from the terminal:
gcc -m64 -pthread -Wall -std=c99 -fPIC  -o run main.o as2.o list.o
/usr/bin/ld: list.o: relocation R_X86_64_32S against undefined symbol `headlist' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: Nonrepresentable section on output
collect2: error: ld returned 1 exit status

This is my make file:
CC = gcc
CFLAGS = -m64 -pthread -Wall -std=c99 -fPIC
PROG = run
OBJS = main.o as2.o list.o

run: $(OBJS)
    $(CC) $(CFLAGS) -o $(PROG) $(OBJS)

main.o: main.c list.h as2.h
     $(CC) $(CFLAGS) -c main.c

as2.o: as2.c as2.h list.h
    $(CC) $(CFLAGS) -c as2.c

clean:
    rm main.o as2.o run

This is my includes:
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "list.h"
#include "as2.h"

Any ideas/solutions?

A: EDIT:
changed the spelling from LFLAGS to LDFLAGS to appease some comment.
EDIT:
moved the -c option to appease some comment.
Note: all is normally the first target in a make file.
Note: used := rather than = so the macros would only be evaluated once.
Note: the list.o is already available in the current directory (per the OPs question) so is not compiled in the makefile.  But is only linked with the other object files to produce the executable
your makefile seems to have a few oversights.  Suggest:
CC := gcc
RM := rm -f

CFLAGS := -ggdb -m64 -pthread -Wall -Wextra -pedantic -std=c99
#LDFLAGS :=   <-- use the default value

PROG := run
OBJS := main.o as2.o list.o
HDRS := list.h as2.h

.PSEUDO: all clean

all: $(PROG)

$(PROG): $(OBJS)
    $(CC)  -ggdb -o $(PROG) $(OBJS) $(LDFLAGS)

main.o: main.c $(HDRS)
     $(CC) $(CFLAGS) -c main.c -o main.o -I.

as2.o: as2.c $(HDRS)
    $(CC) $(CFLAGS) -c as2.c -o as2.o -I.

clean:
    $(RM) main.o as2.o run


text:
Q: Custom Info Window Adapter and 2 other issues So  i was searching for a solution and bumped into the code from this answer on stackoverflow
I am getting error here:
googleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(
                GPSTracker.this)); saying that cannot be resolved to a type.
also Share cannot be resolved to a variable
private void GetCurrentLocation() {

    double[] d = getlocation();
    Share.lat = d[0];
    Share.lng = d[1];

    googleMap.addMarker(new MarkerOptions().position(new LatLng(Share.lat, Share.lng)).title("Current Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.red)));

I couldn't get any solution for CustomInfoWindowAdapter and i do not understand what does Share stands for.
Any help in understanding and solving my issue would be very much appreciated. Thank you for your time.

A: This may help you
https://developers.google.com/maps/documentation/android/intro
custom info window adapter with custom data in map v2


text:
Q: Parsing XML with Javascript (in Google Scripts) I have temperature sensors streaming the temperature of three beehives, and would like to be able to parse the XML stream to provide the last value of the sensor.
I'd like to have:

*

*Sensor 1: 75 degrees (updated: 9:04 pm)

*Sensor 2: 75 degrees (updated: 9:04 pm)

etc.
I'm running following script in Google Scripts, but keep getting an error:

Cannot find function getContentText in object <?xml version="1.0" encoding="UTF-8"?>

Here is the simple script:
function XMLing() {

  var response = UrlFetchApp.fetch("https://api.cosm.com/v2/feeds/79697.xml?key=[private key here]");

  var doc = Xml.parse(response.getContentText(), true);
  var records = doc.getElements("current_value");
  var details = records[0].getText();

  return details;

}

Here is the XML:
<eeml xmlns="http://www.eeml.org/xsd/0.5.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="0.5.1" xsi:schemaLocation="http://www.eeml.org/xsd/0.5.1 http://www.eeml.org/xsd/0.5.1/0.5.1.xsd">
  <environment updated="2012-10-21T00:44:32.162393Z" created="2012-10-10T21:19:43.373591Z" id="79697" creator="https://cosm.com/users/greennomad">
    <private>false</private>
    <data id="sensor1tem">
      <current_value at="2012-10-21T00:44:32.019058Z">67.00</current_value>
      <max_value>618.0</max_value>
      <min_value>611.0</min_value>
    </data>
    <data id="sensor2tem">
      <current_value at="2012-10-21T00:44:32.019058Z">60.57</current_value>
      <max_value>61.5</max_value>
      <min_value>60.41</min_value>
    </data>
...

A: The error message is fairly obvious: your response object is actual text (the XML response) and not an object which has a getContentText() method. So this should work:
var doc = Xml.parse(response, true);

A: You could check which methods are available:
if (!response.getContentText) {
    var props = [];
    for (var p in response) {
        props.push(p);
    }

    var name = typeof response;
    if (response.contructor) name = response.contructor.name;

    return name + " { " + props.join(", ") + " }";
}

My guess is that UrlFetchApp.fetch() is either returning some error-code, or has a special response for XML-documents.

From the error-message, it would seem that UrlFetchApp.fetch() is returning an XML-document directly. You might not need to call Xml.parse():
function XMLing() {

  var response = UrlFetchApp.fetch("https://api.cosm.com/v2/feeds/79697.xml?key=[private key here]");

  var doc = null;
  if (response.getContentText) {
    doc = Xml.parse(response.getContentText(), true);
  }
  else if (response.getElements) {
    doc = response;
  }
  else {
    var name = typeof response;
    if (response.constructor) name = response.constructor.name;
    throw new Exception("Incompatible type: " + name);
  }

  var records = doc.getElements("current_value");
  var details = records[0].getText();

  return details;

}


text:
Q: How to send HTML formatted data in Json In one of application I'm working on user can send message from Web client to Mobile client.
There in Web client when user copy from other Source which contain HTML Tag(like Hyperlink), it copied as it is and display as HTML text content. But same when it received from web to Mobile client, it's display as plain text data.
What could be way to display same HTML text content to mobile client also.

A: var htmlElement = document.querySelector('html');

//for post send
var postObject = {
   formatedHtml:htmlElement.innerHTML
}

$.post('http://blabla.com', postObject);
//or
$.post('http://blabla.com', JSON.stringify(postObject));

//for get send
var queryString = encodeURIComponent(htmlElement.innerHTML)

$.get('http://blabla.com', queryString);

String html text to html bind
document.querySelector('.content').innerHTML = formatedHTMLString


text:
Q: Difficulty understanding the asymmetry in compatibility between LLVM text IR vs binary representation across versions Whilst reading through a variety of articles about LLVM and its own documentation I've seen references to a property I find strange concerning the backwards compatibility of its IR.
Much of the documentation concerning the IR mentions that it is unstable and can break at pretty much any time. However, it also often mentioned that the bitcode IR is more backwards compatible (as in 'often valid across more versions') than the text IR for a given specific LLVM version.
My understanding is that the bytecode -> bitcode transformation is pretty much a direct mapping. Knowing this, why/how is it that the text IR is less compatible? I can't seem to find documentation on the actual mechanism that drives this behavior.
One example of such a statement about IR compatibility can be found here: http://llvm.org/docs/DeveloperPolicy.html#ir-backwards-compatibility

A: Speaking as a developer and not one that developed LLVM.
As you would imagine, the bitcode is more like a virtual machine that has a specific instruction set up to 64 bit that, until quantum computer instructions are popular, will rarely change. As new 64 bit chips are delivered with incremental enhancements it is not major surgery to 'append' new bitcode handling.
The IR, on the other hand, is a textual representation that will go through one or more passes to get to either bitcode or machine code. To support new capabilities there is obviously a net 'add' (new instructions) as well as modifications to existing. This will not only impact the IR parsers/emitters but potentially many intermediate/ephemeral data models used between them. Clearly this would also impact the C/C++ LLVM API. Very costly propositions to maintain backwards compatibility indeed.

A: I think the LLVM developers chose to promise more compatibility for bitcode because there are more obvious use cases that benefit from having backwards compatible bitcode than there are for the textual representation.
You may for example store and distribute libraries as LLVM bitcode and load them into some kind of just-in-time compiling interpreter for a user language. It could be inconvenient to have to upgrade the bitcode whenever the interpreter is upgraded. Bitcode is a machine interface, that is more useful with well defined compatibility.
Textual LLVM IR is more often used for debugging, documentation, or internal testing of LLVM, where changing any failing code whenever (infrequent) changes to the representation are made is more practical. It seems less likely that intermediate code is stored in the long term or distributed widely.
Since maintaining backwards compatibility can negatively impact both implementation effort (see e.g. a C++ parser) and the future evolution of a language (think of the struggles of modern programming languages to deal with retrospectively unwise decisions of the past),
the LLVM community chose to only do so when there are clear benefits. I do not think there is a technical reason inherent in the formats, since both formats have to be parsed and handled correctly.


text:
Q: Solving inequalities number line So I am currently doing inequality problems and i have the answer to the question but am unsure on how to put that onto a number line.
The question is $-7+b≤6b-2<7b+1$.
The answers i got for this are $b≥-1$ and $b>-3$ and am wondering on if the answer is correct and how to put this onto a number line help would be greatly appreciated.

A: Go step wise!
First solve $-7+b\le 6b-2\implies -7+2\le 6b-b\implies b\ge-1$
Now next $6b-2< 7b+1\implies -2-1< 7b-6b\implies b> -3$
So yes, you are right. Now to proceed note that $-1>-3$. Thus $b\ge -1$ staisfies both conditions.

A: I like the following way:
$$-7+b\leq 6b-2<7b+1$$ it's
$$-5\leq 5b<6b+3$$ or
$$-1\leq b$$ and $$b>-3$$ or
$$b\geq-1.$$

A: $\color{red}{-7+b} ≤ \color{green}{6b-2} < \color{blue}{7b+1}$ means two inequalities:
$(1)$ $\color{red}{-7+b} ≤ \color{green}{6b-2}$.
Solving $(1)$ gives $-1 \leq b$.
$(2)$ $ \color{green}{6b-2} < \color{blue}{7b+1}$.
Solving $(2)$ gives $-3 < b$.
In total we have $b \geq -1 >-3$.
$b \geq -1$ is enough.


text:
Q: using latent dirichlet allocation to reduce the number of dimensions in bag of words model? Does anyone have experience reducing the dimensions in a traditional bag of words model?
For example, if you want to train a decision tree on a large set of reviews, the size of the vocabulary would lead to the curse of dimensionality. Would it make sense to run latent dirichlet allocation, then take the ~top10 words in each topic and use that set of words to represent all of the vocabulary?

A: This is not really an answer but rather a comment (don't have the rep yet) - in general, LDA is perfect for dimensionality reduction under the bag-of-words assumption. But you wouldn't really do that the way you suggested (or at least I haven't seen it done like this). Using LDA you would estimate two things - topics (that is distributions over the vocabulary) and the document specific mixing proportions (how much of each topic is there in each of the documents?). You can now use those mixing proportions as a lower dimensional representation of your documents (instead of using full vector of term counts for example). Another solution would be to look into word embeddings such as word2vec.


text:
Q: stringify function with function inside is there any way to stringify function which has function inside? I want to stringify bar function.
const foo = (x) => {
  return x + x;
};
const bar = (y) => {
  return foo(y)
};

bar.toString() returns
function bar(y) {
  return foo(y);
}

but I want something like:
const bar = (y) => {
  const foo = (x) => {
    return x + x;
  };
  return foo(y);
};

Is it even possible? I want to use bar as follow:
// I don't have control below this line
import bar from 'bar';

`<script>(${bar})(5)</script>`

A:
Is it even possible?

Probably. It is not, at all, simple. To do it, you'd have to use a JavaScript parser like Esprima or the ones in Babel, ESLint, etc. to parse the source code that contains both bar and foo and use the resulting AST to identify the functions that bar calls, convert those functions to source code, convert bar to source code, and insert the functions it calls into the beginning of it. And even then, depending on what those functions call and what things they use that they close over, you may have more work to do.
It's tempting to think "Well, I could just use toString on the functions and then a bit of regular expression to figure out what functions bar calls." But JavaScript source code syntax is far too complex to correctly identify function calls in a function's code with a regex or two. You need a proper parser.
As someone said in the comments (now deleted), this sounds like an X/Y problem — like you're trying to solve some other problem by doing this odd conversion of bar. I would focus on solving that problem a different way instead.


text:
Q: GetElementByID failing in IE, works in Chrome and FF I've looked and looked, but can't find solution to this exact issue.  I have a form that returns a couple of values into the variables _ and _.  I'm using those values to update other form values with the 'setfilenameinbox' function.  This works fine in both Chrome and Firefox, but the value doesn't get updated in all versions of IE that I've tested with (both 7 & 8).
Would very much appreciate knowing why code won't work in IE.
<script type="text/javascript">

   function setfilenameinbox(uploadname, url){
       document.getElementById("textboxFileName").value = uploadname;
       document.getElementById("FPFileURL").value = url;
   }

   function openFilePicker(){

      filepicker.setKey('***edited out for help***');

      filepicker.pick({
          extensions: ['.pdf', '.jpg'],
          container: 'window',
          services:['COMPUTER', 'DROPBOX', 'GOOGLE_DRIVE'],
            },
            function(FPFile){
                console.log(JSON.stringify(FPFile));

                //upload complete
                setfilenameinbox(FPFile.filename, FPFile.url);
                },
            function(FPError){
                console.log(FPError.toString());
                }
        );
    }
</script>

A: I think IE7 and 8 have no console object (unless some library or plugin supplied it with one). The console.log should break your code in < IE8. I suggest you remove console commands in production.


text:
Q: how to stop form submit if empty fields? my website is based off of only one php index file that changes the contents of the site based on the header variables. www.mydomain.com/?page=contact loads and brings up a form that i am having the user fill out.
i have some jQuery that SHOULD detect if there are any missing fields:
$("form").submit(function() {
    var isFormValid = true;
    $(".required").each(function() {
        if ($.trim($(this).val()) == "") {
            $(this).addClass("highlight");
            isFormValid = false;
        } else {
            $(this).removeClass("highlight");
        }
        if (!isFormValid) alert("Please fill in all the required fields (indicated by *)");
        return isFormValid;
    });
});

but it is not working....

A: Put return isFormValid out of loop (otherwise you are overwriting its value again and again):
$("form").submit(function() {
    var isFormValid = true;
    $(".required").each(function() {
        if ($.trim($(this).val()) == "") {
            $(this).addClass("highlight");
            isFormValid = false;
        } else {
            $(this).removeClass("highlight");
        }

    });

    if (!isFormValid) alert("Please fill in all the required fields (indicated by *)");
    return isFormValid; // put out of loop
});

A: Maybe something like this?
$("form").submit(function() {
    var isFormValid = true;
    $(".required").each(function() {
        if ($.trim($(this).val()) == "") {
            $(this).addClass("highlight");
            isFormValid = false;
        } else {
            $(this).removeClass("highlight");
        }
    });
    // the following lines should be placed here
    if (!isFormValid) {
        alert("Please fill in all the required fields (indicated by *)");
    }
    return isFormValid;
});

Or even shorter:
$("form").submit(function() {
    var isFormValid = $(".required").removeClass("highlight").filter(function() {
        return $.trim(this.value) == "";
    }).addClass("highlight").length == 0;

    if (!isFormValid) {
        alert("Please fill in all the required fields (indicated by *)");
    }
    return isFormValid;
});

DEMO: http://jsfiddle.net/YS6gw/

A: Can you post the html works perfectly fine for me.
Here is my Code :
------------------------

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

    <title></title>

<form action="#" method="post">

        <input type="checkbox" id="checkBox1">
        <input type="text" class ="required"  id="text1"/>
        <input type="text" class ="required" id="text2"/>
        <input type="text" class ="required" id="text3"/>
        <button type="submit" id="btnSubmit">Submit</button>

</form>


text:
Q: Packages for Pacemaker & Corosync for Ubuntu 14.04.1 LTS Current version of the stack pacemaker & corosync included in Ubuntu 14.04.1 LTS are 1.1.10 & 2.3.3. Anybody knows of a repository with newer versions? (Sure, I can compile the sources, but I would appreciate to reuse some work here.)
Thanks!

A: I'm looking it too :)
Maybe you can find it from below links.
Pacemaker
https://github.com/ClusterLabs/pacemaker

A: I cannot paste more than two links by newbie, so divided.
Corosync
https://github.com/corosync/corosync


text:
Q: How to get relative paths with Pathlib I started using from pathlib import Path in place of os.path.join() to concatenate my paths. Taking the following code into consideration:
from pathlib import Path
import cv2

rootfolder = "rootyrooty"
file = "alittlefile"
image_path = Path(rootfolder, file)
image = cv2.imread(image_path.as_posix())

I'm using image_path.as_posix() to get a full string so I can pass image_path into imread function. Directly typing image_path doesn't works since it returns WindowsPath('rootyrooty/alittlefile') but I need "rootyrooty/alittlefile" (Since imread accepts strings instead of windowsPath objects). Do I have to use another component from pathlib instead of Path so I can just feed image_path into imread function. Like:
from pathlib import thefunctionyetidontknow
image_path = thefunctionyetidontknow("rootyrooty","alittlefile")
print("image_path")
# returns "rootyrooty/alittlefile"

Thanks.

A: You can convert the Path object to a string with Python's builtin str function:
from pathlib import Path
import cv2

rootfolder = "rootyrooty"
file = "alittlefile"
image_path = Path(rootfolder, file)
image = cv2.imread(str(image_path))

A: The way you are combining paths is perfectly fine.
What is questionable is the usage of as_posix() on a Windows machine. Some libs that accept a string as a path may be fine with posix path separators, but it may be preferable to use the os separator instead. To get path with filesystem separators, use str.
See https://docs.python.org/3/library/pathlib.html

The string representation of a path is the raw filesystem path itself (in native form, e.g. with backslashes under Windows), which you can pass to any function taking a file path as a string:
>> p = PurePath('/etc')
>> str(p)
'/etc'
>> p = PureWindowsPath('c:/Program Files')
>> str(p)
'c:\\Program Files'


text:
Q: Mageto2 product listing page random product when we refresh the product listing page , it always show the random position for the products. we set the default sort by the position and did not assign any position to products for this category.
what could be wrong ?
Thanks

A: By default under these circumstances it should return a list of products by entity_id unless filters are specified.


text:
Q: MVC3 Loosly coupled authentication Out of the box MVC3 applications allow Windows Authentication when using the Intranet project template, or the Forms Authentication for an Internet project template.  I've got a site that I'd like to use either.  In addition, I've got an existing site that uses it's own custom type of authentication that authenticates users (no authorization or roles, just identification).  I may need to use functionality of each, in addition to the data from the legacy system for authentication.  Due to this, I'm trying to determine a way to abstract my authentication and decouple it.  I'd like to use some kind of dependency injection, based entirely upon configuration, so I could deploy this same site in two different locations, and switch the authentication model (Windows Auth/Forms Auth/ Custom Auth), by changing configuration only.
Currently, all the ASP.NET applications I've worked with, including the MVC3 template projects, seem to be very tightly coupled with the authentication type used.
Am I thinking too far outside of the box on this one?
Is this possible, or is there a reason for this tight coupling?
UPDATE
The real problem I have is between the existing legacy authentication I need to use for some users, versus the Forms Authentication I need for others.
The Windows versus Forms authentication isn't really a problem, due to the LogIn form not being used for one.  But consider the Custom Authentication and Forms Authenication.  The LogIn form is tightly coupled to FormsAuthentication, more specifically to System.Web.Security. (i.e. Membership.ValidateUser, FormsAuthentication.SetAuthCookie, etc...).
I'd like to Inject into my AccountController the authentication to use, rather than having FormsAuthentication and Membership be used.
Does this make more sense in so far a what my problem is?

A: They're actually not so tightly coupled. The templates are just trying to get you up and running quickly.
ASP.NET membership supports both Forms and Domain auth.
In a site configured for Forms auth, e.g., you'll see a line in Web.config like:
<authentication mode="Forms">

You can change that to:
<authentication mode="Windows">

That's not the only difference (with Windows auth, e.g., you don't need a login page), but it's the most significant. You write your code based on the ASP.NET Membership API and only target Forms authentication in particular when you have to.

A: I agree with Craig's answer. The only thing I have to add is that I consider just about anything you can change in the web.config to be loosely coupled. The reason is that you can apply web.config transforms when you create a deployment package for your MVC app.
We use Unity for DI/IoC, and you can also specify your injection dependencies in web.config using Unity. You would just write your Web.Auth1.config to configure your app for one kind of authentication, and Web.Auth2.config to configure it for another kind of authentication. Then when you deploy, you just pick the target and VS builds the correct configuration for you.
If your source code needs to know which type of auth is used in the deployment, you could tell it with a web.config appSetting, which can also be changed with a web.config transform during deployment.


text:
Q: Partition size inconsistent I have a MAC that had Windows installed (using Bootcamp) with a damaged HDD (15 S.M.A.R.T. Errors).
If i attach the disk to a linux machine it reports the following data:
Disk /dev/sdc: 1953525168s
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Disk Flags:

Number  Start        End          Size        File system  Name                  Flags
 1      40s          409639s      409600s     fat32        EFI system partition  boot, esp
 2      409640s      586498047s   586088408s  hfs+         Customer
 3      586498048s   587767583s   1269536s    hfs+         Recovery HD
 4      1565007872s  1953521663s  388513792s  ntfs         Basic data partition  msftdata

So far everything seems right, apart from the fact that the NTFS partition is very small and there are 977.240.289 sectors unused (which makes no sense to do so). If i try to mount it:
root@werkstatt-debian-lenovo:~# mount /dev/sdc4 /mnt/
mount: wrong fs type, bad option, bad superblock on /dev/sdc4,
       missing codepage or helper program, or other error

       In some cases useful info is found in syslog - try
       dmesg | tail or so.

Then I opened it in Windows, which showed me a full 651,24 GB Partition.

The data on the partition, as detected using Windows seems fine, apart from the fact that Windows is not booting, but that's another story.
Using a RAW disk editor on windows reveals the following structure:
The raw (protective) MBR:

The raw GPT:

What's confusing me is the fact, that windows acts like it's GPT, but the raw disk editor and Linux say it's MBR. Could the MBR be wrong, but the GPT right?

A: The drive is using a hybrid partition scheme. This means Windows uses the values in the Master Boot Record (MBR) table. OS X (macOS) uses the values in the GUID Partition Table (GPT). Most of the time, Linux also uses the values in the GPT. Hybrid partitioning usally results in the common values stored in the 2nd, 3rd and 4th entries of the MBR partition table are repeated in the GPT. By common, I mean the values representing the type of partition and where the partition resides.
OS X (macOS) is aware there are values stored in both the MBR partition table and the GPT. However, Windows only knows of the MBR partition table.
Your question is repeated below:

What's confusing me is the fact, that windows acts like it's GPT, but the raw disk editor and Linux say it's MBR. Could the MBR be wrong, but the GPT right?

No, you are wrong. Windows acts like it is MBR and Linux says it is GPT. In fact there are two partition tables: the MBR partition table and a GPT.
The 2nd and 3rd entries in both the MBR partition table and GPT are the same (as they should be), but the 4th entry for Windows is different. If the MBR partition table entry is correct, then linux is reading the wrong values stored in the GPT.
The start value (First LBA) of 1565007872 sectors in the 4 entry of the GPT probably should be the value 587767808, which is the start value in the MBR partition table. A suppose one could do a hex dump of the first sector of the partition to see if the NTFS header looks OK. Or, make the change and see if the partition (NTFS volume) mounts.


text:
Q: asp.net mvc - convert
 to  in c# My application is ASP.NET MVC2 C#, I am using Telerik MVC Editor and itextsharp to produce a PDF file.  My challenge is
 shows in the PDF rather than a new paragraph.
In the editor I have:
.Encode(false)

In the controller I am using:
er.Comments = HttpUtility.HtmlDecode(recommendation.Comments);

so far everything works well.
To produce my PDF, I am using:
BPR = HttpUtility.HtmlEncode(this.Recommendations.**Comments**)
List<IElement> htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(BPR ), null);

Comments is stored as in the database as:
First Paragraph
 Second paragraph

However when I debug the program, BPR is converted to:
First Paragraph <br /> Second paragraph

Is there a way to convert <br /> back to
?

A: The problem was in this line:
BPR = HttpUtility.HtmlEncode(this.Recommendations.Comments)

Since I getting the values from a database some of the data were already encoded.


text:
Q: Using a single JTextArea with multiple UndoManagers I have a JTextArea and a JComboBox to allow me to cycle through various open files - the contents of the JTextArea change as I select a different file. I am trying to maintain a different Undo buffer per file and have defined a separate UndoManager per file.
I have created a simpler SSCCE to demonstrate my problem using two buffers, which I call "One" and "Two" - with a simple button to switch between them. Once an UndoableEdit happens, it checks the active buffer and performs an addEdit() on the respective UndoManager. When the "Undo" button is pressed, then it checks canUndo() and performs an undo() on the respective UndoManager. I have a flag called ignoreEdit, which is used when switching between buffers to ignore those edits from being recorded.
If I never switch between the buffers, then I don't have a problem, Undo works as expected. It is only when I switch between the buffers and appear to "break" the Document, does it fail. The following steps can be used to recreate the problem:
In buffer "One", type:
THIS
IS ONE
EXAMPLE

Switch to buffer "Two", type:
THIS
IS ANOTHER
EXAMPLE

Switch to buffer "One" and press the "Undo" button multiple times. After a few Undo operations, the buffer looks like this (with no way for the cursor to select the first two lines). However, the contents of textArea.getText() are correct as per the System.out.println() - so, it looks like a rendering issue?
THIS

THISIS ONE

This can't be the first time that someone has tried to implement independent Undo buffers per file? I am obviously doing something wrong with the Document model and inherently breaking it, but I looking for some advice on how best to fix this?
The code for the SSCCE is included below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.undo.*;

public class SSCCE extends JFrame implements ActionListener, UndoableEditListener {
  private final JLabel labTextArea;
  private final JTextArea textArea;
  private final JScrollPane scrollTextArea;
  private final Document docTextArea;
  private final JButton bOne, bTwo, bUndo;
  private final UndoManager uOne, uTwo;
  private String sOne, sTwo;
  private boolean ignoreEdit = false;

  public SSCCE(String[] args) {
    setTitle("SSCCE - Short, Self Contained, Correct Example");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(300, 200);
    setLocationRelativeTo(null);

    labTextArea = new JLabel("One");
    getContentPane().add(labTextArea, BorderLayout.PAGE_START);

    uOne = new UndoManager();
    uTwo = new UndoManager();
    sOne = new String();
    sTwo = new String();

    textArea = new JTextArea();
    docTextArea = textArea.getDocument();
    docTextArea.addUndoableEditListener(this);
    scrollTextArea = new JScrollPane(textArea);
    getContentPane().add(scrollTextArea, BorderLayout.CENTER);

    JPanel pButtons = new JPanel();
    bOne = new JButton("One");
    bOne.addActionListener(this);
    bOne.setFocusable(false);
    pButtons.add(bOne, BorderLayout.LINE_START);
    bTwo = new JButton("Two");
    bTwo.addActionListener(this);
    bTwo.setFocusable(false);
    pButtons.add(bTwo, BorderLayout.LINE_END);
    bUndo = new JButton("Undo");
    bUndo.addActionListener(this);
    bUndo.setFocusable(false);
    pButtons.add(bUndo, BorderLayout.LINE_END);
    getContentPane().add(pButtons, BorderLayout.PAGE_END);

    setVisible(true);
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    if (e.getSource().equals(bOne)) {
      if (!labTextArea.getText().equals("One")) {
        sTwo = textArea.getText();
        ignoreEdit = true;
        textArea.setText(sOne);
        ignoreEdit = false;
        labTextArea.setText("One");
      }
    }
    else if (e.getSource().equals(bTwo)) {
      if (!labTextArea.getText().equals("Two")) {
        sOne = textArea.getText();
        ignoreEdit = true;
        textArea.setText(sTwo);
        ignoreEdit = false;
        labTextArea.setText("Two");
      }
    }
    else if (e.getSource().equals(bUndo)) {
      if (labTextArea.getText().equals("One")) {
        try {
          if (uOne.canUndo()) {
            System.out.println("Performing Undo for One");
            uOne.undo();
            System.out.println("Buffer One is now:\n" + textArea.getText() + "\n");
          }
          else {
            System.out.println("Nothing to Undo for One");
          }
        }
        catch (CannotUndoException ex) {
          ex.printStackTrace();
        }
      }
      else if (labTextArea.getText().equals("Two")) {
        try {
          if (uTwo.canUndo()) {
            System.out.println("Performing Undo for Two");
            uTwo.undo();
            System.out.println("Buffer Two is now:\n" + textArea.getText() + "\n");
          }
          else {
            System.out.println("Nothing to Undo for Two");
          }
        }
        catch (CannotUndoException ex) {
          ex.printStackTrace();
        }
      }
    }
  }

  @Override
  public void undoableEditHappened(UndoableEditEvent e) {
    if (!ignoreEdit) {
      if (labTextArea.getText().equals("One")) {
        System.out.println("Adding Edit for One");
        uOne.addEdit(e.getEdit());
      }
      else if (labTextArea.getText().equals("Two")) {
        System.out.println("Adding Edit for Two");
        uTwo.addEdit(e.getEdit());
      }
    }
  }

  public static void main(final String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        new SSCCE(args);
      }
    });
  }
}

A: Previously I had attempted to create a new instance of the Document class (each referencing the same Undo listener) and was going to use JTextArea.setDocument() instead of JTextArea.setText(). However, Document is an interface and can't be instantiated, but after reading the reference that mKorbel posted, I tried this using the PlainDocument class instead, which worked.
I have decided to maintain a HashMap<String, Document> to contain my Document classes and switch between them. When I switch the Document, I don't see the Undo/Redo issue - I suppose as I am no longer breaking the Document.
Updated SSCCE below which now uses JTextArea.setDocument() instead of JTextArea.setText(). This also has the advantage of not requiring the ignoreEdit boolean as setDocument() doesn't trigger an UndoableEditEvent, whereas setText() does. Each Document then references the local classes UndoableEditListener.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.undo.*;

public class SSCCE extends JFrame implements ActionListener, UndoableEditListener {
  private final JLabel labTextArea;
  private final JTextArea textArea;
  private final JScrollPane scrollTextArea;
  private final Document docTextArea;
  private final JButton bOne, bTwo, bUndo;
  private final UndoManager uOne, uTwo;
  private Document dOne, dTwo;

  public SSCCE(String[] args) {
    setTitle("SSCCE - Short, Self Contained, Correct Example");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(300, 200);
    setLocationRelativeTo(null);

    labTextArea = new JLabel("One");
    getContentPane().add(labTextArea, BorderLayout.PAGE_START);

    uOne = new UndoManager();
    uTwo = new UndoManager();
    dOne = new PlainDocument();
    dTwo = new PlainDocument();
    dOne.addUndoableEditListener(this);
    dTwo.addUndoableEditListener(this);

    textArea = new JTextArea();
    docTextArea = textArea.getDocument();
    docTextArea.addUndoableEditListener(this);
    textArea.setDocument(dOne);
    scrollTextArea = new JScrollPane(textArea);
    getContentPane().add(scrollTextArea, BorderLayout.CENTER);

    JPanel pButtons = new JPanel();
    bOne = new JButton("One");
    bOne.addActionListener(this);
    bOne.setFocusable(false);
    pButtons.add(bOne, BorderLayout.LINE_START);
    bTwo = new JButton("Two");
    bTwo.addActionListener(this);
    bTwo.setFocusable(false);
    pButtons.add(bTwo, BorderLayout.LINE_END);
    bUndo = new JButton("Undo");
    bUndo.addActionListener(this);
    bUndo.setFocusable(false);
    pButtons.add(bUndo, BorderLayout.LINE_END);
    getContentPane().add(pButtons, BorderLayout.PAGE_END);

    setVisible(true);
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    if (e.getSource().equals(bOne)) {
      if (!labTextArea.getText().equals("One")) {
        textArea.setDocument(dOne);
        labTextArea.setText("One");
      }
    }
    else if (e.getSource().equals(bTwo)) {
      if (!labTextArea.getText().equals("Two")) {
        textArea.setDocument(dTwo);
        labTextArea.setText("Two");
      }
    }
    else if (e.getSource().equals(bUndo)) {
      if (labTextArea.getText().equals("One")) {
        try {
          if (uOne.canUndo()) {
            System.out.println("Performing Undo for One");
            uOne.undo();
            System.out.println("Buffer One is now:\n" + textArea.getText() + "\n");
          }
          else {
            System.out.println("Nothing to Undo for One");
          }
        }
        catch (CannotUndoException ex) {
          ex.printStackTrace();
        }
      }
      else if (labTextArea.getText().equals("Two")) {
        try {
          if (uTwo.canUndo()) {
            System.out.println("Performing Undo for Two");
            uTwo.undo();
            System.out.println("Buffer Two is now:\n" + textArea.getText() + "\n");
          }
          else {
            System.out.println("Nothing to Undo for Two");
          }
        }
        catch (CannotUndoException ex) {
          ex.printStackTrace();
        }
      }
    }
  }

  @Override
  public void undoableEditHappened(UndoableEditEvent e) {
    if (labTextArea.getText().equals("One")) {
      System.out.println("Adding Edit for One");
      uOne.addEdit(e.getEdit());
    }
    else if (labTextArea.getText().equals("Two")) {
      System.out.println("Adding Edit for Two");
      uTwo.addEdit(e.getEdit());
    }
  }

  public static void main(final String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        new SSCCE(args);
      }
    });
  }
}

A: This is not an answer per se, but a demonstration of a different way of approaching the same problem.
What this does is wraps the UndoableEditListener in a self managed proxy, which has it's own UndoManager and Document.
Tested this with Java 7 and Java 8:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;
import javax.swing.undo.UndoManager;

public class UndoExample {

    public static void main(String[] args) {
        new UndoExample();
    }

    private int index = 0;
    private Map<String, Undoer> mapUndoers;
    private JTextArea ta;
    private Undoer current;

    public UndoExample() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                mapUndoers = new HashMap<>(2);
                mapUndoers.put("One", new Undoer());
                mapUndoers.put("Two", new Undoer());

                ta = new JTextArea(4, 20);
                ta.setWrapStyleWord(true);
                ta.setLineWrap(true);

                JButton btnOne = new JButton("One");
                JButton btnTwo = new JButton("Two");
                ActionListener al = new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        install(e.getActionCommand());
                    }
                };
                btnOne.addActionListener(al);
                btnTwo.addActionListener(al);

                JButton undo = new JButton("Undo");
                undo.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if (current != null) {
                            current.undo();
                        }
                    }
                });

                JPanel panel = new JPanel(new GridBagLayout());
                panel.add(btnOne);
                panel.add(btnTwo);
                panel.add(undo);

                install("One");

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JScrollPane(ta));
                frame.add(panel, BorderLayout.SOUTH);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    protected void install(String name) {
        Undoer undoer = mapUndoers.get(name);
        if (undoer != null) {
            current = undoer;
            undoer.install(ta);
        }
    }

    public class Undoer implements UndoableEditListener {

        private UndoManager undoManager;
        private Document doc;

        public Undoer() {
            undoManager = new UndoManager();
            doc = createDocument();
            doc.addUndoableEditListener(this);
        }

        public void undo() {
            undoManager.undo();
        }

        public void undoOrRedo() {
            undoManager.undoOrRedo();
        }

        protected Document createDocument() {
            return new PlainDocument();
        }

        public void install(JTextComponent comp) {
            comp.setDocument(doc);
        }

        @Override
        public void undoableEditHappened(UndoableEditEvent e) {
            undoManager.addEdit(e.getEdit());
        }

    }

}


text:
Q: Let $(X_t)$ be a continuous Markov chain and $\tau$ a stopping time. How to compute $\mathbb E [e^{-r\tau} \phi (X_\tau)]$? Let $(X_t)$ be a continuous-time Markov chain on probability space $(\Omega, \mathcal F, \mathbb P)$ such that

*

*$X_0 = a$ almost surely.

*The state space $V$ is finite and endowed with discrete topology.

*The infintesimal generator is $L: V^2 \to \mathbb R$.
Moreover, we have $\phi: V \to \mathbb R_+$ and $D \subseteq V$. Consider the stopping time $$\tau = \inf \{ t \ge 0 \mid X_t \in D\}$$ Then I'm interested in computing $$\alpha = \mathbb E [e^{-r\tau} \phi (X_\tau)] \tag{1}$$

My attempt:
Let $Y = e^{-r\tau} \phi (X_\tau)$. Then $Y$ is a random variable defined by $$\forall \omega \in \Omega:Y (\omega) = e^{-r\tau(\omega)} \phi (X_{\tau(\omega)}(\omega))\tag{2}$$ It follows that $$\alpha = \int Y (\omega) \, \mathrm{d} \mathbb P (\omega) \tag{3}$$

In class, I'm given a random variable $Z$ with p.d.f $f$. Then I compute $\mathbb E[Z]$ by $$\mathbb E[Z] = \int zf(z) \, \mathrm{d}z \tag{4}$$, which is usually the Riemann integral.
This is the first time I'm required to compute the integral $(1)$. Could you please elaborate on how to compute $\alpha$ in $(1)$? Any reference is appreciated.

A: I convert @gt6989b's comment as answer to close this question.

How is this different from the Law of the Unconscious Statistician giving $$\mathbb{E}[e^{-r\tau}\phi(X_\tau)] = \int_\mathbb{R} e^{-rt} \phi(X_t) f_\tau(t) dt,$$ where $f_\tau(\cdot)$ is the pdf of the stopping time $\tau$?


text:
Q: How to find the latest date and price>0 per id? In POSTGRESQL 13, I have a table of ids,dates, prices.
I simply want to have the latest date where the price is greater than 0 per id.
One row per id.
So the optimal output is :
id | the_date | price
1   2013-08-09  0.45
2   2013-08-11  0.34

I have an SQL fiddle at this link :
https://dbfiddle.uk/?rdbms=postgres_13&fiddle=a89bbbc922601be5465ad764fd035161
I have tried an INNER JOIN with the MAX date unsuccessfully.

A: SELECT DISTINCT ON (id)
  id, the_date, price
FROM inventory
WHERE price>0
ORDER BY id ASC, the_date DESC

A: This might work for you.
SELECT inventory.id, the_date, price
FROM inventory
join (select id,max(the_date) md from inventory where price>0 group by id ) d
on inventory.id=d.id and the_date=d.md

If you want a row for id's with not price you'd use left join.

A: You can do something like this:
select i.id, i.the_date, i.price
from inventory as i, (
    select id, max(the_date) as max_date
    from inventory
       where price > 0
    group by id
) as c where c.id = i.id and i.the_date = c.max_date

Demo in dbfiddle.uk


text:
Q: different ways to append html? I just wanted to know the differences between the methods of adding html in jquery.
both will do samething right?
$('body').append($("

"));

and
var div = $("
");
var img = $("").attr({"src" : "somesource", "alt" : "something"});
div.append(img);
$('body').append(div);

which is the best practice to follow?

A: The second is better. Because you often see people doing this:
var alt = 'This is " the title containing a double quote';
$('body').append($('

'));

and then wonder why something got eaten :-). Whereas when you use the second you have absolutely nothing to worry about:
var alt = 'This is " the title containing a double quote';
var div = $('
');
var img = $('').attr({ src : 'somesource', alt : alt });
div.append(img);
$('body').append(div);

UPDATE:
I was too hasty in saying that you have nothing to worry about with the second approach. As others have already pointed out you have to worry about performance.

A: The second method looks better and there are lesser chances of error. But performance wise, the second method is slower. So if you're going to be doing a lot of appending, I would recommend going with the the first case - albeit, carefully.
Here's a small test case up on JS-Perf comparing the two methods

A: Normally I would say DOM-scripting is the better option (the second approach); it's more structured, and easier to catch issues than by inserting a mass of HTML prepared as a string.
That said, there are performance concerns. Inserting loads of elements via DOM-scripting, particularly in a loop, can cause significant slowdown and there are cases where inserting as a string is much quicker.
Also, the fewer inserts you do - by whatever means - the fewer repaints/refreshes you force the browser to make. Again, these all require browser attention, so the fewer the better.

A: See also my answer on When do you use DOM-based Generation vs. using strings/innerHTML/JQuery to generate DOM content?

The difference is that you have two variables pointing to the jQuery instances. You might can need them for eventListener-adding or manipulating them lateron in the code.
Also, DOM-based element generation has the advantage of automatically escaping the strings, which is especially useful when designing functions with parameters and absolutely needed for user input.
Therefore, the second method is most often preferred. You can also nest the appending process to make the structure clear (OK, in this example the one-liner would be clear as well):
var div = $("
");
var img = $("", {"src":"somesource", "alt":"something"});
$('body').append(
  div.append(
    img
  )
);

A: I believe you are better off using template libraries for inserting objects. An example of one such library is here: http://api.jquery.com/category/plugins/templates/
Those libraries are build for performance and ease the burden on parsing HTML blobs.

A: Adding a string of HTML content is about 10 times faster
than using second method
Here is a reference

A: I would prefer the second one as the first one could lead to very long lines and if you need to bind events to certain elements you already have a variable that is pointing to it.


text:
Q: Function $(2.2)^n$ -- what is it? The running time of an algorithms is $(2.2)^n$. I have to tell what is the maximum $n$ for reaching 1.000.000 steps.
What type of a function is $(2.2)^n$? How its output depends on the input $n$?
Thank you very much in advance for your help!
Best,
Ina

A: $2.2^n$ is the same as $\frac{22^n}{100^n}$, this should tell you how it is calculated. We have the following inequality:
$2^n<2.2^n<3^n$. So it is exponential time, if your algorithm takes approximately $2.2^n$ operations then for an input of $25$ you need approximately $3\times 10^8$ operations, which is going to take a somewhere between half a second and half a minute. However, any input above $40$ will take more than a decade.


text:
Q: How to print image with Bluebamboo device using objective C? I am new in objective c development and working on a project, in which I am using External Accessory the device is Bluebamboo P25M printer and credit card swapper.
I have to print Image using this printer. Bluebamboo provided a SDK but in this SDK they are using a char type array of bitmap image. Now how can i made such array of my image so that it can print any image.
here is my code
if (normalPrint==3)//print image
    {
            unsigned char buffer3[796]={
            0x55 ,  0x66 ,  0x77 ,  0x88 ,  0x44 ,  0x1B ,  0x58 ,  0x31 ,
            0x19, 0x20,
             0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x80 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x01 ,0xC0 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x01 ,0x80 ,0x00 ,0x03 ,0x60 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x03
            ,0xA0 ,0x00 ,0x07 ,0xB0 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x05 ,0x60 ,0x00 ,0x07 ,0xD8 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x05 ,0xA0 ,0x00 ,0x13 ,0xEC ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x04
            ,0x20 ,0x00 ,0x29 ,0xF4 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x03 ,0xC0 ,0x00 ,0x64 ,0xF9 ,0x00
            ,0x0F ,0xFF ,0x9C ,0x01 ,0xC0 ,0x19 ,0xFF ,0xC0 ,0x7F ,0xFC ,0x7F ,0xF9 ,0xC0 ,0x3D ,0xFF
            ,0xF1 ,0xFF ,0xE3 ,0xFF ,0xC0 ,0x00 ,0x00 ,0xF2 ,0x73 ,0x80 ,0x0F ,0xFF ,0x9C ,0x01 ,0xC0
            ,0x19 ,0xFF ,0xC0 ,0x7F ,0xFE ,0x7F ,0xFD ,0xE0 ,0x3D ,0xFF ,0xF1 ,0xFF ,0xE3 ,0xFF ,0xC0
            ,0x00 ,0x00 ,0x79 ,0x26 ,0xC0 ,0x0F ,0xFF ,0xDC ,0x01 ,0xC0 ,0x19 ,0xFF ,0xC0 ,0x7F ,0xFE
            ,0xFF ,0xFD ,0xF0 ,0x7D ,0xFF ,0xFB ,0xFF ,0xF7 ,0xFF ,0xE0 ,0x00 ,0x03 ,0x3C ,0x8F ,0x60
            ,0x0C ,0x01 ,0xDC ,0x01 ,0xC0 ,0x19 ,0x80 ,0x00 ,0x70 ,0x0E ,0xE0 ,0x1D ,0xF0 ,0x7D ,0x80
            ,0x3B ,0x80 ,0x77 ,0x00 ,0xE0 ,0x00 ,0x04 ,0x9E ,0x8F ,0xB0 ,0x0E ,0x01 ,0xDC ,0x01 ,0xC0
            ,0x19 ,0x80 ,0x00 ,0x70 ,0x0E ,0xE0 ,0x1D ,0xF8 ,0xFD ,0x80 ,0x33 ,0x80 ,0x77 ,0x00 ,0xE0
            ,0x00 ,0x0E ,0x4F ,0x27 ,0xD8 ,0x0F ,0xFF ,0x9C ,0x01 ,0xC0 ,0x19 ,0xFF ,0xC0 ,0x7F ,0xFC
            ,0xE0 ,0x1D ,0xF9 ,0xFD ,0xFF ,0xF3 ,0x80 ,0x77 ,0x00 ,0xE0 ,0x00 ,0x0F ,0x26 ,0x53 ,0xC8
            ,0x0F ,0xFF ,0x9C ,0x01 ,0xC0 ,0x19 ,0xFF ,0xC0 ,0x7F ,0xFC ,0xEF ,0xFD ,0xDD ,0xDD ,0xFF
            ,0xF3 ,0x80 ,0x77 ,0x00 ,0xE0 ,0x00 ,0x07 ,0x90 ,0xC9 ,0xF0 ,0x0F ,0xFF ,0xDC ,0x01 ,0xC0
            ,0x19 ,0xFF ,0xC0 ,0x7F ,0xFE ,0xEF ,0xFD ,0xDF ,0x9D ,0xFF ,0xFB ,0x80 ,0x77 ,0x00 ,0xE0
            ,0x00 ,0x03 ,0xC9 ,0xE4 ,0xE0 ,0x0C ,0x00 ,0xDC ,0x01 ,0xC0 ,0x19 ,0x80 ,0x00 ,0x70 ,0x06
            ,0xE7 ,0xFD ,0xCF ,0x9D ,0x80 ,0x3B ,0x80 ,0x77 ,0x00 ,0xE0 ,0x00 ,0x01 ,0xF0 ,0xF2 ,0x40
            ,0x0E ,0x01 ,0xDC ,0x00 ,0xC0 ,0x19 ,0x80 ,0x00 ,0x70 ,0x0E ,0xE0 ,0x1D ,0xCF ,0x1D ,0x80
            ,0x3B ,0x80 ,0x77 ,0x00 ,0xE0 ,0x00 ,0x00 ,0xE6 ,0x79 ,0x00 ,0x0F ,0xFF ,0xDF ,0xFC ,0xFF
            ,0xF9 ,0xFF ,0xC0 ,0x7F ,0xFE ,0xE0 ,0x1D ,0xC7 ,0x1D ,0xFF ,0xFB ,0xFF ,0xF7 ,0xFF ,0xE0
            ,0x00 ,0x00 ,0x49 ,0x3D ,0x00 ,0x0F ,0xFF ,0x9F ,0xFC ,0xFF ,0xF9 ,0xFF ,0xC0 ,0x7F ,0xFE
            ,0xE0 ,0x1D ,0xC2 ,0x1D ,0xFF ,0xF1 ,0xFF ,0xE3 ,0xFF ,0xC0 ,0x00 ,0x00 ,0x1C ,0x9E ,0x00
            ,0x0F ,0xFF ,0x1F ,0xFC ,0x7F ,0xE1 ,0xFF ,0xC0 ,0x7F ,0xFC ,0xE0 ,0x1D ,0xC0 ,0x1D ,0xFF
            ,0xE0 ,0xFF ,0xC1 ,0xFF ,0x80 ,0x00 ,0x00 ,0x1E ,0x4C ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x0F ,0x20 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x07 ,0x90 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x03 ,0xE0 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x01 ,0xC0 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x80 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
            ,0x00 ,0x00 ,0x00
            };

        //[self addLabel:@"buffer3 is selected"];
        [[session outputStream] write:(const uint8_t *)buffer3 maxLength:796];//send print package

In this code first 10 values in array [0x55,  0x66,  0x77,  0x88,  0x44,  0x1B,  0x58,  0x31, 0x19, 0x20,] are command to printer and rest is image data.

A: You don't specify what format is the image data for that printer. Is it RGB? CMYK? CMY?
I think the general question is, how do you get at the raw bytes of an image. There are multiple ways to do this. First, you can get a TIFF version of the image: can you transform a TIFF in your data format?
NSImage *myImage = ...;
NSData *bytes = [myImage TIFFRepresentation];

Once you have NSData, you can get at its buffer (raw bytes) and the buffer's length in your write: routine.
More generally, you can create bitmap representations like this:
CIImage *myImage = ...;
NSBitmapImageRep *bitmapRep = [[NSBitmapImageRep alloc] initWithCIImage:myImage];
NSData *jpegData [bitmapRep representationUsingType:NSJPEGFileType properties:nil];

[jpegData writeToFile:@"/Users/username/Desktop/MyImage.jpeg" atomically:YES];
This will give you the raw bytes in JPEG format.


text:
Q: Parser with multiple return types I have problem with parsers that can manage multiple types, e.g., the parser for arithmetic expressions. At the moment my parser takes in input only integers:
aexpr :: Parser Int
aexpr = aterm `chainl` addOp

aterm :: Parser Int
aterm = afactor `chainl` mulOp

afactor :: Parser Int
afactor = parenP '(' aexpr ')'
          <|>
          do
            s <- sign
            a <- aexpr
            return (s * a)
          <|>
          token int_const

This works well for two integers, but I am introducing the float type, so the parser for arithmetic expressions can have in input two Int, two Float or two mixed types of Int and Float. The result type of the parser should be Int or Float based on the inputs (i.e., Int if both inputs are Int, Float otherwise).
My question is: what is the best way to manage this? A simple way is to just manage all the inputs as Float, so integer values are converted into float values. But I don't like this solution: the end result will be always Float.
Should I create two different parsers, i.e., one for Int and one for Float? But the two parsers would be pretty much the same.
There is a better solution?

A: When designing DSLs, it's very common to define a new data type representing all the different shapes values can have:
data Value
    = I Int
    | D Double
    deriving (Eq, Ord, Read, Show)

You may want to implement some helper functions, like:
binOp :: (forall a. Num a => a -> a -> a) -> Value -> Value -> Parser Value
binOp f (I a) (I b) = pure (I (f a b))
binOp f (D a) (D b) = pure (D (f a b))
binOp _ _ _ = fail "oof, tried to mix Ints and Doubles"

Then your mulOp and addOp implementations could call binOp (*) and binOp (+) somewhere in their implementation, for example.
But I would consider another approach than using such helpers directly. I would propose introducing an intermediate representation for which parsing "always succeeds", then add a separate type-checking phase where you can throw errors about mixing ints and doubles... or do appropriate casts, or whatever your DSL wants to happen there. So:
data BinOp = Plus | Times deriving (Bounded, Enum, Eq, Ord, Read, Show)
data Type = Int | Double deriving (Bounded, Enum, Eq, Ord, Read, Show)
data DSL
    = ILit Int
    | DLit Double
    | BinOp BinOp DSL DSL
    deriving (Eq, Ord, Read, Show)

Then you can write things with types like
typeCheck :: DSL -> These [TypeError] Type -- check for mixing
unsafeEval :: DSL -> Value -- implementation uses incomplete patterns and assumes no mixing

eval :: DSL -> Either [TypeError] Value
eval t = case typeCheck t of
    That _ -> Right (unsafeEval t)
    These [] _ -> Right (unsafeEval t)
    These es _ -> Left es
    This es -> Left es

or whatever.


text:
Q: split file and pass split parts as file, not pipe to stdin How to take file (seq 1000000), split it into multiple smaller ones, which will be then passed into process as a file, not a pipe? I.e.
parallel -a <(seq 1000000) -j 6 -l 10000 <what here?> /root/someProcess

where someProcess will process the part as:
/root/someProcess <(seq 500)

i.e. it will take file as a parameter and process it.

A: <(seq 1000000) is not a regular file. It creates a fifo that can only be read once.
To use that with GNU Parallel you use --pipe:
seq 1000000 | parallel --pipe ...

If, OTOH, you have a regular big file, look at split file and pass split parts as stdin


text:
Q: custom output in javascript I have code which generates a time in zulu. Now I want it to have multiple output options, but the easy way. Is there a quicker way to do this:
function zuluTime(format) {
    if(!format) { return false; }

    format      = format.toLowerCase();
    zuluDate    = new Date();

    zuluHour    = zuluDate.getUTCHours();
    zuluMin     = zuluDate.getUTCMinutes();
    zuluSec     = zuluDate.getUTCSeconds();

    zuluHour    = (zuluHour <= 9) ? '0'+zuluHour : zuluHour;
    zuluMin     = (zuluMin  <= 9) ? '0'+zuluMin  : zuluMin;
    zuluSec     = (zuluSec  <= 9) ? '0'+zuluSec  : zuluSec;
    zuluTenths  = Math.floor((zuluSec / 60) * 10)
    zulu        = '<span>Z</span';

    if(format == 'hhmmss')  { time = (zuluHour+':'+zuluMin+':'+zuluSec+zulu);           }
    if(format == 'hhmm')    { time = (zuluHour+''+zuluMin+zulu);                        }
    if(format == 'hhmm.s')  { time = (zuluHour+''+zuluMin+'.'+zuluTenths+''+zulu);      }

    return time;
}

Is it possible to make some function which recognizes if the format contains hh.s for example without having to if else?

A: You could use a RegExp in String.prototype.replace with a function as the second argument
var re = /hh|mm|ss|s/g,
        map = {
        hh: zuluHour,
        mm: zuluMin,
        ss: zuluSec,
        s: zuluTenths
    };
function replacor($0) {
    if ($0 in map)
        return map[$0];
    return $0;
}

time = format.replace(re, replacor);

This method is easily expanded to permit more variables and will work on any "formatting", e.g. Thh:mm:ssZ will become T16:31:58Z, even though you didn't teach it with a list what to do for that specific format.
If hhmmss is meant to be equal to hh:mm:ss you will need to apply this transformation to format first.


text:
Q: trying to get an output from a file using the user input value then print the value in python I'm trying to learn python and I wrote this script, that not shows me the right output.. What am i missing?
I have a text file like this:

test
test1
test2
test3
test4
#test5
test6
#test7
#test8

TASK 1:

*

*open file: i got this part

**do not print or ignore any line that starts with "#": i think i got this part (fread2)

Here is my code:
fopen=open('file1.txt',mode='r+')
fread=fopen.read()
fread2="\n".join([line.strip() for line in fread.splitlines() if not line.startswith('#')])

print(fread2)

fopen.close()

Output:

test
test1
test2
test3
test4
test6

Note: test5, 7 and 8 did not print. Success!
TASK 2:

*

*ask user to input a text: completed

*from fread2 output - use the user "input" value and if value exit, then print that line only: failed!!

See the following code:
fopen=open('file1.txt',mode='r+')
fread=fopen.read()
fread2="\n".join([line.strip() for line in fread.splitlines() if not line.startswith('#')])
text=input("Enter text: ")
for x in fread2:
    if text == "":
        continue
    if text in x:
        print(x)
fopen.close()

Output

Enter text: test

Where I'm wrong?

A: Your fread2 is a single string, so when you call for x in fread2 you are iterating on every single letter, not on every row of the file. You can see this by doing:
for x in fread2:
    print(x)

You have to save all the lines in a list or iterate on the file rows.
EXAMPLE
Try to follow this code:
fopen=open('file1.txt',mode='r+')
fread=fopen.read()

fread2=[]

for line in fread.splitlines():
    if not line.startswith('#'):
        fread2.append(line) #this is important!
                            #If you write "+=" you'll iterate on every single letter

text=input("Enter text: ")
for x in fread2:
    if text in x:
        print("I've found "+x)
fopen.close()

If the user write "2", your output will be:

UPDATE
As requested in the comments, If you want to check if the user input equals a file line you have to replace
if text in x:

with
if text==x:

So, if the user write "text", the lines "text2", "text3" etc. will be not printed!
Here is an output example:

A: As mentioned in the comments, the fread2 variable is one big string containing all lines. When you iterate over a string, you iterate over its characters. So an example iteration of your loop is:
if "test" in "e":
    print(x)

It's easy to see that this is not what you were going for.
To solve this, you can iterate through the lines by doing:
for x in fread2.split("\n"):

But, personally I think a more elegant solution would be to save the lines in a list to begin with, and only change the way you print it:
with open('file1.txt',mode='r+') as fopen:
    fread = [line.strip() for line in fopen if not line.startswith('#')]

# first assignment
print(*fread, sep='\n')

#second assignment
text = input("Enter text: ")
for line in fread:
    if text == line:
        print(line)

Note that I used with to open the file which is the idiomatic way of doing so.


text:
Q: Wanted: Rikulo UXL example(s) I want to get some UXL working with the Dart Editor.  I'm afraid that I feel the sample code on UXL Overview is either out of date or lacks some critical steps to let it perform.  (See also: What is Rikulo dart really?, which directs people to the blogs).
I want to get up to speed with something like the UXL mark-up for the Dart environment.  So are the only examples I've found are on the blog/documentation and the seem to be incomplete.

*

*https://github.com/rikulo/uxl
And it seems like it may not be 'just me' I find the examples confusing.  Is a UXL mark-up a 'abc.UXL' or 'abc.uxl.XML' file?  For now I'm looking at Rikulo because I see it as the kind of extremely helpful framework I like to see.
That said, please rikulo people, provide three or four examples that work with a few tweaks and a bit of thought.
I'll put that same thing out there for others wanting doing tools and frameworks.  Examples teach.  And make sure your examples always work.  Make them part of your unit testing.
Cheers, Will.

A: AFAIK, all samples in the document shall work fine. If we changed spec, we will update the document accordingly.
You can name it .uxl or .uxl.xml, but I'd suggest .uxl.xml if your editor supports XML. Otherwise, you have to configure it to recognize .xul.

Not sure what critical steps you mean or expect. Better to provide a more specific question.

A helpful example [ed. Will] ...
I made a small addition to the ScrollView example that is saved on GitHub for the UXL project.
ScrollView.uxl.xml
<!-- ScrollViewTemplate -->
<?dart
part of ScrollViewDemo;
?>

<Template name="ScrollViewTemplate" args="rows: 30, cols: 30">
  <ScrollView class="scroll-view"
  profile="location: center center; width: 80%; height: 80%">
    <Apply forEach="r = 0; r < rows; ++r">
      <Apply forEach="c = 0; c < cols; ++c">
        <View style="border: 1px solid #553;
              background-color: ${CssUtil.color(250 - r * 4, 250 - c * 4, 200)}"
              left="${r * 50 + 2}" top="${c * 50 + 2}"
              width="${46}" height="${46}">
         ( ${r}, ${c} )
        </View>
      </Apply>
    </Apply>
  </ScrollView>
</Template>

build.dart
//import 'package:polymer/builder.dart';
import 'package:rikulo_uxl/uc.dart';

void main(List<String> args) {
    build( args );
}

What makes this different from the GitHub example?

*

*This includes the build.dart file

*Each cell shows its coordinates.  That shows two things.

*

*How to use UXL values inside the UXL mark-up and

*In the runtime it shows you how the scrolling works with the cells

*This demo runs on Dart Editor download

*

*Dart Editor version 1.3.0.dev_06_01 (DEV)

*Dart SDK version 1.3.0-dev.6.1

*The sample didn't work with the 6.0 version

I would also point out that for me, it seems unusual to need to download the UXL project to find one demo.  And I need to clarify what a 'demo' might be to "me" as the code I downloaded wasn't an example of anything it just demonstrated one or three UXL features.
I understand people are busy and stuff.  And still, in my opinion testing, integration, documentation and examples make 80% of a project the other 20% being code.  Others have different opinions.  (I think the proportions will be congruent if you have done this for more than 5 years though. Just guessing.)


text:
Q: Shapely install on Mac with pyenv-virtualenv failed OS: mac, El Capitan
Python version: 2.7.11
I tried to install shapely after setting up a brand new pyenv-virtualenv and changing my directory to use that 'pyenv version' and I get the following error:
dhcp-uris-1290:seam Chelsea$ pip install shapely
Collecting shapely
Using cached Shapely-1.5.15.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/private/var/folders/1l/r_vh6y997rdgk6sdnkqsntpr0000gn/T/pip-build-odrxBR/shapely/setup.py", line 38, in <module>
    from shapely._buildcfg import geos_version_string, geos_version, \
  File "/private/var/folders/1l/r_vh6y997rdgk6sdnkqsntpr0000gn/T/pip-build-odrxBR/shapely/shapely/_buildcfg.py", line 88, in <module>
    clibs = get_geos_config('--clibs')
  File "/private/var/folders/1l/r_vh6y997rdgk6sdnkqsntpr0000gn/T/pip-build-odrxBR/shapely/shapely/_buildcfg.py", line 71, in get_geos_config
    stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  File "/Users/Chelsea/.pyenv/versions/2.7.11/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/Users/Chelsea/.pyenv/versions/2.7.11/lib/python2.7/subprocess.py", line 1334, in _execute_child
    child_exception = pickle.loads(data)
  File "/Users/Chelsea/.pyenv/versions/2.7.11/lib/python2.7/pickle.py", line 1388, in loads
    return Unpickler(file).load()
  File "/Users/Chelsea/.pyenv/versions/2.7.11/lib/python2.7/pickle.py", line 864, in load
    dispatch[key](self)
  File "/Users/Chelsea/.pyenv/versions/2.7.11/lib/python2.7/pickle.py", line 972, in load_string
    raise ValueError, "insecure string pickle"
ValueError: insecure string pickle
-----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/1l/r_vh6y997rdgk6sdnkqsntpr0000gn/T/pip-build-odrxBR/shapely/

The whole reason I got into this virtualenv business is because I was getting insecure string pickle errors when trying to use matplotlib with system python on el capitan, which is known to be an issue (https://github.com/matplotlib/matplotlib/issues/5314) , so I tried to build my own new framework and run it, that didn't work, and now tried to set up a virtualenv but it looks like virtualenv might just not play nicely with certain python packages? :'(
Shapely install correctly OUTSIDE of a virtualenv on my machine, with system python. Sadly system python, as mentioned, was not playing nicely with matplotlib.
P.S. these are the packages I have installed in this particular pyenv-virtualenv:
cycler (0.10.0)
distribute (0.7.3)
matplotlib (1.5.1)
numpy (1.11.0)
pip (8.1.2)
pyparsing (2.1.4)
python-dateutil (2.5.3)
pytz (2016.4)
setuptools (21.1.0)
six (1.10.0)
wheel (0.29.0)


text:
Q: NSURLSessionDataTask in App Delegate I am trying to run a NSURLSessionDataTask in my app delegate on a background fetch but although I get valid data from the completion handler the app isn't firing the method. Here is my code
 - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

    NSURLSession *serverConfigure = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSessionConfiguration *serverSession = [NSURLSession sessionWithConfiguration:serverConfigure delegate:self delegateQueue:nil];

    NSURLSessionDataTask *serverDownload = [serverSession dataTaskWithURL:[NSURL URLWithString:@"myurl"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSArray *downloadedData = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

        [self handleData:downloadedData];

    }];

    [serverDownload resume];

}

A: In backgroundFetch your application will call this method in background
-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
for this you have to activate background fetch mode
...just go through this link http://www.appcoda.com/ios7-background-fetch-programming/


text:
Q: The right location of src files to compile? I have several programs I want to download their src files and compile.
They are fetched through git, so I can easily pull updates and recompile them.
The right location of these files, to my understanding, is /usr/local/src.
But aren't some (most? any?) deter the use of sudo for source compilation aside make install?
So should I give /usr/local/src user permissions?
Or am I completely mistaking?

A: The configure and make portion of the process should be performed without escalated privilege.
Once that is successfully completed, the install is performed with superuser role (i.e. sudo).
Commonly, storage of source is within your $HOME and compilation performed there.
I'd strongly recommend packaging the project for integration into your system(s) via native package management.
To answer: no, don't change the permissions of '/usr/local/src' ; just utilize your $HOME for building.

A: There is no such thing as the "correct location" it is up to the admin to decide. True, traditionally Linux admins place source files in /usr/local/src and you are free to do so. You can also place them in your $HOME, whatever you prefer.
Now, if you are compiling/installing software you are the admin. Therefore, there is no reason why you should not switch to root in order to have access to /usr/local/src. There is absolutely no reason why you should not compile as root, that is what every sysadmin I have ever known does, that is why the root user exists, to perform administrative tasks. This includes the compilation and installation of software.
So, if you are developing software, do it in your $HOME, if you are installing other people's software from source, do it as root in /usr/local/src if you so desire. Personally, I compile programs in $HOME/Setups because my $HOME is on a separate partition and that makes it easier for me to upgrade/reinstall my system. That is just a personal choice though and proper sysadmins will compile in /usr/local/src as root.


text:
Q: How do I avoid using nested foreach statements by using lambda or linq in this scenario? How do I avoid using nested foreach statements by using lambda or linq in this scenario? It's late and I cannot seem to figure out how to access the ErrorMessage property without having to revert to a nested foreach statement. What would be the equivalent method if the code was rewritten using wholly Lambda or Linq?
public static List<String> ExtractErrors(this ModelStateDictionary modelStateDictionary)
        {
            List<String> errors = new List<String>();

            var modelErrorCollection = (from modelState in modelStateDictionary.Values
                                        where modelState.Errors != null && modelState.Errors.Count > 0
                                        select modelState.Errors).ToList();

            foreach (var item in modelErrorCollection)
            {
                foreach (ModelError modelError in item)
                {
                    errors.Add(modelError.ErrorMessage);
                }
            }

            return errors;
        }

A: You'll want to use SelectMany for this
    public static List<String> ExtractErrors(this ModelStateDictionary modelStateDictionary)
    {
        var modelErrorCollection = (from modelState in modelStateDictionary.Values
                                    where modelState.Errors != null && modelState.Errors.Count > 0
                                    select modelState.Errors)
                                    .SelectMany(item=>item)
                                    .Select(modelError=>modelError.ErrorMessage)
                                    .ToList();
         return modelErrorCollection;
     }

A: Isn't it errors.Add(modelErrorCollection.SelectMany(x => x))?


text:
Q: Meaning of "with too much criticism" in this article I saw this news from tribune.com, but I am not pretty sure about the last sentence:

Gabriel, who is Chancellor Angela Merkel's deputy in a left-right coalition, warned against alienating Saudi Arabia, a crucial player in the bid to end the Syrian war, with too much criticism.

Does this mean Gabriel criticised Saudi Arabia too much and should be less caustic based on this article only?

A:
Gabriel, who is Chancellor Angela Merkel's deputy in a left-right coalition, warned against alienating Saudi Arabia, a crucial player in the bid to end the Syrian war, with too much criticism.

Gabriel said that German politicians should not criticize Saudi Arabia too much. If they do, they might provoke alienation towards Germany in Saudi political circles.
The key verb is warned - if we omit the explanatory bits in the sentence, we get this:

Gabriel warned against alienating Saudi Arabia with too much criticism.

Or, paraphrasing this:

Gabriel warned against using too much criticism towards Saudi Arabia, since that could alienate it.

Or:

Gabriel warned against criticizing Saudi Arabia too much: this could alienate it.

So, it's not Gabriel who should be less caustic. It's Gabriel's advice to be less caustic, given to German politicians in general. Or, judging from the context of the article, it's a "mitigating sentence" indicating that Gabriel intends to be cautious in her own criticism of the Saudi regime.
We can remodel the sentence to make Gabriel the recipient of this warning:

Gabriel, who is Chancellor Angela Merkel's deputy in a left-right coalition, was warned against alienating Saudi Arabia, a crucial player in the bid to end the Syrian war, with too much criticism.

"Was warned" is a passive voice construction, and it makes Gabriel the recipient of the warning.


text:
Q: Getting errors on `git push`, but the push action seems to be successful When I push to github, I get an error that says git was unable to push some refs, but I can see on remote that the push is successful.
Here are the details:
[akhann16@login006 swift_proj]$ git push
warning: push.default is unset; its implicit value is changing in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the current behavior after the default changes, use:
  git config --global push.default matching
To squelch this message and adopt the new behavior now, use:
  git config --global push.default simple
See 'git help config' and search for 'push.default' for further information.
(the 'simple' mode was introduced in Git 1.7.11. Use the similar mode
'current' instead of 'simple' if you sometimes use older versions of Git)
Counting objects: 7, done.
Delta compression using up to 24 threads.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (5/5), 1.17 KiB | 0 bytes/s, done.
Total 5 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), completed with 1 local object.
To git@github.com:khanna-lab/cadre.git
   a1563e5..2223084  ak-tinkering -> ak-tinkering
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'git@github.com:khanna-lab/cadre.git'
hint: Updates were rejected because a pushed branch tip is behind its remote
hint: counterpart. If you did not intend to push that branch, you may want to
hint: specify branches to push or set the 'push.default' configuration variable
hint: to 'simple', 'current' or 'upstream' to push only the current branch.

I see that the push is successful, but I don't understand why I get this error or what it is saying?

A: Indeed, this is because using an old git, version 1.8.3.1. I can't update git on the system I am using, so I updated the setting configuration setting:
git config --global push.default simple


text:
Q: Perpetual loading in sql server join query i have a query where i am joining 2 tables and in inner query when the table is  coming empty ,i am getting perpetual loading .Can anyone explain me why it is so?
Query--->
SELECT TRF.GroupId,
       'Brand imagery',
       ImageryId,
       'Brand' SelType,
       BCC.MasterId,
       BCC.CategoryId,
       SUM(TRF.[Weight]),
       COUNT(TRF.Respondent_Serial),
       QtrType
FROM #tmpRespFrequency TRF
JOIN (
    SELECT A.MasterId,
           A.Respondent_Serial,
           ImageryId,
           B.CategoryId
    FROM Brand_Imagery_Deepdive A
    JOIN #BrandCategoryType B ON A.MasterId=B.SelId AND B.SelType='Brand'
    JOIN #Measure M ON M.Metric='Brand imagery' AND M.MetricItemId=ImageryId
    WHERE B.CategoryId NOT IN (
        SELECT DISTINCT CategoryId FROM Brand_Imagery_DeepdiveBase
    )
) BCC ON TRF.Respondent_Serial=BCC.Respondent_Serial
GROUP BY TRF.GroupId, ImageryId, BCC.MasterId, BCC.CategoryId, QtrType;

innner query which is coming empty if running separate is: -
(SELECT A.MasterId,
        A.Respondent_Serial,
        ImageryId,
        B.CategoryId
 FROM Brand_Imagery_Deepdive A
 JOIN #BrandCategoryType B ON A.MasterId=B.SelId AND B.SelType='Brand'
 JOIN #Measure M ON M.Metric='Brand imagery' AND M.MetricItemId=ImageryId
 WHERE B.CategoryId NOT IN (
     SELECT DISTINCT CategoryId FROM Brand_Imagery_DeepdiveBase
 )
)

BCC is EMPTY in short
Kindly suggest