text:
Q: return each item by looping it inside a method in ruby I have a method which calls another method and that method loops each item and returns individual object to first method. I am not sure how to return each item by looping it inside a second method. My pseudo code is as below.
def process_episodes
  items << get_each_episodes_details(episode_doc)
end

def get_each_episodes_details(epi_doc)
  base_data = "Some common data related to the episodes"
  episodes = get_array_of_episodes_info_from_episode_doc(epi_doc)
  #Finally return each episode details with base data
  episodes.each do |episode|
    return base_data + episode
  end
end

I was assuming that return base_data + episode would return each episode after iteration.

But it did return only one item and exited from the method block. How
  can I return multiple items so that if episodes array as 10 items,
  then I need to return each item so that items array would contain 10
  individual episode related information.

A: Your code will always return the first iterated episode and would never go to the next episodes as your returning as soon as you get in the loop.
You need some improvements in your code.
First of all, you have to return an array from the second function.
Like this
 def get_each_episodes_details(epi_doc)
   base_data = "Some common data related to the episodes"
   episodes = get_array_of_episodes_info_from_episode_doc(epi_doc)
   #Finally return each episode details with base data
   episodes.map{|episode| base_data + episode} # this will return an array => [obj1,obj2, obj3...]
 end

Now your items will be an array of array => [[obj1,obj2..], [x1,x2..]]
You can then call flatten on items to have flatten it so you don't get array of arrays. items.flatten
Hope that helps :)


text:
Q: Which of following two C programs (iterative and inductive) is more efficient for finding the nth Fibonacci number? As stated above attempting to work out which of the following two programs is most efficient for finding the nth Fibonacci number and why.
The Fibonacci numbers are numbers in the sequence: 1, 1, 2, 3, 5, 8... where each number after the first two is the sum of the preceding two numbers.
//// iteration ////
int main()
{
int n;
int t1 = 0;
int t2 = 1;
int i;
int new_term;
printf("Enter N :");
scanf("%d", &n);
if (n == 1)
    new_term = 0;
else if (n == 2)
    new_term = 1;
else
{
    for (i = 3; i <= n; i++)
    {
        new_term = t1 + t2;
        t1 = t2;
        t2 = new_term;
    }
}
printf("%dth term of the series is %d", n, new_term);
return 0;
}

//// induction ////
int fibo(int n);

int main() {
      int n;
    printf("Enter n : ");
    scanf("%d", &n);
    printf("The %dth term of Fibonacci sequence is %d", n, fibo(n));
    return 0;
}

int fibo(int n)
{
    if (n == 1) return 0;
    if (n == 2) return 1;
    return fibo(n - 1) + fibo(n - 2);
}

A: This is an algorithmic question and must be seen as one.
The iterative version will find its results in O(n) steps.
For the recursive version, as you use no memoization, each term will be computed many times.
Suppose N(n) is the number of steps to produce the nth number. You need to compute fibo(n-1) and fib0(n-2) and sum them. So you need N(n-1) + N(n-2) + 1 steps. Neglecting the last sum, it comes that N(n) is in the same order of magnitude of fibo(n) which is known to be exponential.
Optimized recursive algorithms can compute fibo(n) in O(n) steps at the cost of storing numbers in a array (they are still less efficient than the iterative way), but your naive algorithm will have terrible performance.
Recursion generally allows for very simple algorithms with very poor performances.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Required tag missing error on MarketDataRequest query I have a FIX44.MarketDataRequest query based on Trade Client example from QuickFIX-n example applications. But I can't manage to get something useful from the server with this query. I always get the error Required tag missing for this query.
Here is my code:
MDReqID mdReqID = new MDReqID("MARKETDATAID");
SubscriptionRequestType subType = new SubscriptionRequestType(SubscriptionRequestType.SNAPSHOT);
MarketDepth marketDepth = new MarketDepth(0);

QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup marketDataEntryGroup = new QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup();
marketDataEntryGroup.Set(new MDEntryType(MDEntryType.BID));

QuickFix.FIX44.MarketDataRequest.NoRelatedSymGroup symbolGroup = new QuickFix.FIX44.MarketDataRequest.NoRelatedSymGroup();
symbolGroup.Set(new Symbol("EUR/USD"));

QuickFix.FIX44.MarketDataRequest message = new QuickFix.FIX44.MarketDataRequest(mdReqID, subType, marketDepth);
message.AddGroup(marketDataEntryGroup);
message.AddGroup(symbolGroup);

Here is the generated outbound application level message (ToApp):
8=FIX.4.49=15835=V34=249=order.DEMOSUCD.12332150=DEMOSUSD52=20141223-07:02:33.22656=demo.fxgrid128=DEMOSUSD262=MARKETDATAID263=0264=0267=1269=0146=155=EUR/USD10=232

Here is the received ToAdmin message:
8=FIX.4.49=14935=334=249=demo.fxgrid52=20141223-07:02:36.51056=order.DEMOSUCD.12332157=DEMOSUSD115=DEMOSUSD45=258=Required tag missing371=265372=V373=110=136

If I understand correctly the pair 371=265 (RefTagID=MDUpdateType) after 258=Required tag missing indicates which tag is missing, .i.e. is missing MDUpdateType. But this is strange because this tag is optional for MarketDataRequest.
UPDATE
Here is my FIX config file:
[DEFAULT]
FileStorePath=store
FileLogPath=log
ConnectionType=initiator
ReconnectInterval=60
CheckLatency=N

[SESSION]
BeginString=FIX.4.4
TargetCompID=demo.fxgrid
SenderCompID=XXX
SenderSubID=YYY
StartTime=00:00:00
EndTime=00:00:00
HeartBtInt=30
SocketConnectPort=ZZZ
SocketConnectHost=X.X.X.X
DataDictionary=FIX44.xml
ResetOnLogon=Y
ResetOnLogout=Y
ResetOnDisconnect=Y
Username=AAA
Password=BBB


text:
Q: service http requests in java without using a webserver Can someone please let me know if we can use Restful web services or something similar to that to service HTTP requests without using a web server

A: All the Http requests are processed or identified by the servlet or ejb component in java.
1.We must deploy restful services server side code in webserver otherwise we cannot expose our functionality over the network
2.To access the rest resource we can use normal java program or any servlet or other.
3.Without using webserver you cannot expose your rest resource over the network at serverside.


text:
Q: lein aliases on do with nested argument throws an error I'm trying to do an :aliases on lein, the doc says I can do something like this:
:aliases {["do" ["cljsbuild" "clean"] ["cljsbuild" "once"] ["cljsbuild" "auto"]]}

it throws an error, since map need an even argument, so I added a key:
:aliases {"re-cljs" ["do" ["cljsbuild" "clean"] ["cljsbuild" "once"] ["cljsbuild" "auto"]]}

It throws, java.lang.IllegalArgumentException: No matching method found: endsWith for class clojure.lang.PersistentVector. Now I have no idea how fix this.

A: Works fine for me, but I vaguely remember a bug like this in an older version of Leiningen.
Upgrade to a newer version (Leiningen 2.2.0 is old) and this problem should be gone.


text:
Q: Is there a formal logical system which works visually? I think visually and I like logic, so I'm interested if there exists a formal system which deduces propositions visually (with directed graphs, maybe?). If so, do such systems play an important role in any area of logic, or are they just a useless curiosity?

A: It can be argued that logic itself is a strictly formalized domain and each inference step can be traced mechanically with assumed background semantic interpretation of quantifiers and the truth value of all predicates from any metalanguage, a mechanical deductive system like Fitch system or some other sequent calculus sytems (Hilbert, Gentzen) are often the official non visual tools. From computer science POV, it's just formal string manipulation rules of a certain Turing machine (like a game), so hardly there's any visual system required.
However, there's nothing wrong for you to try any graph or intuitive sketching method to help you understand and proceed for logic puzzles. A common useful such method used in advanced logic courses are called tableaux method. It'll become extremely helpful for you to prove some advanced theorems in mathematical logic in general.


text:
Q: How to encode(escaping special characters) in XSLT1.0 using Apache Software Foundation (Xalan XSLTC) Processor I am using XSLT 1.0, Apache Software Foundation (Xalan XSLTC) processor. I am not supposed to use XSLT 2.0. I have the following xml in which the value of <prvNum> has some special characters.
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <prvNum>SPECIAL#1&</prvNum>
</root>

Now I want to perform percent-encoding for the value of <prvNum>. For example the value should be changed as below after percent encoding:
SPECIAL%231%26

My output xml should looklike below:
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <prvNum>SPECIAL%231%26</prvNum>
</root>

Can anybody tell me how do that?


text:
Q: Ejecutar un método en un jButton en Java Hola quiero llamar a un método para ejecutarla en otra clase dentro un botón pero este metodo tiene los siguientes parámetros c, mod lo eh intentado así.
Este es el metodo
public void mostarCasillas(Casillas c,Usuario mod){}

Lo llamo dentro del botón pero así pero no me ejecuta nada.
private void btnMostrarCasillaActionPerformed(java.awt.event.ActionEvent evt) {
    Casillas c = new Casillas();
    Usuario m = new Usuario();
    mostarCasillas(c, m);
}

-creo que es por lo que hago una nueva instancias y entonces los datos que traen se pierden
Habrá otra manera? gracias.


text:
Q: How do you use a function to create an Object with Javascript? Im doing a course in JavaScript. Im at the "Objects and classes" chapter, and I do not know how to solve some assignements in my homework.
The first exercise is like this
function createCat(name,age){
//Create a new object with the property "name" and the value defined by the argument "name".
//Add a new property to the object with the name "age" and use the value defined by the argument"age"
//Add a methos (function) called meow that returns the string "Meow"!
}

And this is what im trying
 function createCat(name,age){
      var Cat={};
        Cat.Name=name;
        Cat.Age=age;
        Cat.meow=function(){return "Meow!"};
        return Cat;
     }

Im testing the function loading the script in an index.html file, opening that file in a browser and then testing the functions in the web Console. I run the function and there is no problem. Then, I test if the Cat object was returned by writing Cat.Name in the console, which results in an error. The same thing happens when I call the function in a line of code below and then try to access the properties of the Object. The error reads "ReferenceError: Cat is not defined". What am I doing wrong? Thanks!

A: A cleaner way to do this is to leave out the let Cat = {} part entirely. You can use the function itself to create a Cat object.
function Cat(name, age) {
    this.name = name;
    this.age = age;
    this.meow = () => console.log("Meow!");
}

let myCat = new Cat("Waldorf", 16)
let anotherCat = new Cat("Statler", 12)

myCat.meow()
console.log(anotherCat.name)

A: Your function returns Cat, but this is only a name in function scope. In order to use that name out of the function, you need to do this:

function createCat(name, age) {
        var cat = {};
        cat.Name = name;
        cat.Age = age;
        cat.meow = () => "Meow!";
        return cat;
}

let Cat = createCat("mist", 16);

console.log(Cat)

A: You get this error because Cat is only defined within the scope of your function. To define Cat globally, use window.Cat instead of var Cat:

function createCat(name, age) {
  window.Cat = {};
  Cat.Name = name;
  Cat.Age = age;
  Cat.meow = function() {
    return "Meow!"
  };
  return Cat;
}

console.log(Cat.Name);

A: If you want to get your Cat when you type on the console Cat.name you have to declare it globally like so:
function createCat(name, age) {
  return {
    name: name,
    age: age,
    meow: function() {
      return "Meow!"
    },
  };
}

window.Cat = createCat('name', 2);
Then you can access your Cat globally.
You could also assign the Cat to a variable on the browser console and access it through Cat.name like so:
const Cat = createCat('name', 2);


text:
Q: errors in hadoop 3.0.0-alpha1 compilation on kubuntu 12.04 I've had problems to compile the 3.0.0-alpha1 Hadoop version on kubuntu 12.04 (64 bits).
Apparently, this version requires a HADOOP-8887 patch is applied.
After preparing the installation with all dependencies on a machine,
according to BUILD.txt and apply the patch, the error that would correct by this patch, still remains, as shown in the log file.
All information is welcome to help resolve the issue.
command for compiling:
mvn clean package -Pdist -Dtar -Dmaven.javadoc.skip=true -DskipTests -fail-at-end -Pnative

log file tail:
    [INFO] ------------------------------------------------------------------------

    [INFO] Reactor Summary:

    [INFO]

    [INFO] Apache Hadoop Main ................................ SUCCESS [0.601s]

    [INFO] Apache Hadoop Build Tools ......................... SUCCESS [0.365s]

    [INFO] Apache Hadoop Project POM ......................... SUCCESS [0.584s]

    [INFO] Apache Hadoop Annotations ......................... SUCCESS [0.793s]

    [INFO] Apache Hadoop Assemblies .......................... SUCCESS [0.100s]

    [INFO] Apache Hadoop Project Dist POM .................... SUCCESS [1.017s]

    [INFO] Apache Hadoop Maven Plugins ....................... SUCCESS [1.050s]

    [INFO] Apache Hadoop MiniKDC ............................. SUCCESS [0.407s]

    [INFO] Apache Hadoop Auth ................................ SUCCESS [0.978s]

    [INFO] Apache Hadoop Auth Examples ....................... SUCCESS [0.697s]

    [INFO] Apache Hadoop Common .............................. SUCCESS [23.360s]

    [INFO] Apache Hadoop NFS ................................. SUCCESS [0.600s]

    [INFO] Apache Hadoop KMS ................................. SUCCESS [4.903s]

    [INFO] Apache Hadoop Common Project ...................... SUCCESS [0.024s]

    [INFO] Apache Hadoop HDFS Client ......................... SUCCESS [11.244s]

    [INFO] Apache Hadoop HDFS ................................ SUCCESS [17.609s]

    [INFO] Apache Hadoop HDFS Native Client .................. SUCCESS [2.746s]

    [INFO] Apache Hadoop HttpFS .............................. SUCCESS [12.556s]

    [INFO] Apache Hadoop HDFS BookKeeper Journal ............. SUCCESS [0.564s]

    [INFO] Apache Hadoop HDFS-NFS ............................ SUCCESS [0.758s]

    [INFO] Apache Hadoop HDFS Project ........................ SUCCESS [0.021s]

    [INFO] Apache Hadoop YARN ................................ SUCCESS [0.021s]

    [INFO] Apache Hadoop YARN API ............................ SUCCESS [3.985s]

    [INFO] Apache Hadoop YARN Common ......................... SUCCESS [3.795s]

    [INFO] Apache Hadoop YARN Server ......................... SUCCESS [0.056s]

    [INFO] Apache Hadoop YARN Server Common .................. SUCCESS [1.618s]

    [INFO] Apache Hadoop YARN NodeManager .................... SUCCESS [4.077s]

    [INFO] Apache Hadoop YARN Web Proxy ...................... SUCCESS [0.401s]

    [INFO] Apache Hadoop YARN ApplicationHistoryService ...... SUCCESS [0.847s]

    [INFO] Apache Hadoop YARN Timeline Service ............... SUCCESS [1.369s]

    [INFO] Apache Hadoop YARN ResourceManager ................ SUCCESS [5.544s]

    [INFO] Apache Hadoop YARN Server Tests ................... SUCCESS [0.749s]

    [INFO] Apache Hadoop YARN Client ......................... SUCCESS [1.743s]

    [INFO] Apache Hadoop YARN SharedCacheManager ............. SUCCESS [0.449s]

    [INFO] Apache Hadoop YARN Timeline Plugin Storage ........ SUCCESS [0.512s]

    [INFO] Apache Hadoop YARN Timeline Service HBase tests ... SUCCESS [1.503s]

    [INFO] Apache Hadoop YARN Applications ................... SUCCESS [0.017s]

    [INFO] Apache Hadoop YARN DistributedShell ............... SUCCESS [0.500s]

    [INFO] Apache Hadoop YARN Unmanaged Am Launcher .......... SUCCESS [0.338s]

    [INFO] Apache Hadoop YARN Site ........................... SUCCESS [0.018s]

    [INFO] Apache Hadoop YARN Registry ....................... SUCCESS [0.844s]

    [INFO] Apache Hadoop YARN Project ........................ SUCCESS [8.001s]

    [INFO] Apache Hadoop MapReduce Client .................... SUCCESS [0.061s]

    [INFO] Apache Hadoop MapReduce Core ...................... SUCCESS [2.869s]

    [INFO] Apache Hadoop MapReduce Common .................... SUCCESS [1.362s]

    [INFO] Apache Hadoop MapReduce Shuffle ................... SUCCESS [0.390s]

    [INFO] Apache Hadoop MapReduce App ....................... SUCCESS [1.791s]

    [INFO] Apache Hadoop MapReduce HistoryServer ............. SUCCESS [0.848s]

    [INFO] Apache Hadoop MapReduce JobClient ................. SUCCESS [2.293s]

    [INFO] Apache Hadoop MapReduce HistoryServer Plugins ..... SUCCESS [0.214s]

    [INFO] Apache Hadoop MapReduce NativeTask ................ FAILURE [9.687s]

    [INFO] Apache Hadoop MapReduce Examples .................. SUCCESS [0.666s]

    [INFO] Apache Hadoop MapReduce ........................... FAILURE [0.515s]

    [INFO] Apache Hadoop MapReduce Streaming ................. SUCCESS [0.657s]

    [INFO] Apache Hadoop Distributed Copy .................... SUCCESS [2.721s]

    [INFO] Apache Hadoop Archives ............................ SUCCESS [0.972s]

    [INFO] Apache Hadoop Archive Logs ........................ SUCCESS [0.393s]

    [INFO] Apache Hadoop Rumen ............................... SUCCESS [0.554s]

    [INFO] Apache Hadoop Gridmix ............................. SUCCESS [0.620s]

    [INFO] Apache Hadoop Data Join ........................... SUCCESS [0.264s]

    [INFO] Apache Hadoop Extras .............................. SUCCESS [0.304s]

    [INFO] Apache Hadoop Pipes ............................... SUCCESS [2.345s]

    [INFO] Apache Hadoop OpenStack support ................... SUCCESS [0.336s]

    [INFO] Apache Hadoop Amazon Web Services support ......... SUCCESS [0.645s]

    [INFO] Apache Hadoop Azure support ....................... SUCCESS [0.622s]

    [INFO] Apache Hadoop Client .............................. SUCCESS [3.436s]

    [INFO] Apache Hadoop Mini-Cluster ........................ SUCCESS [0.432s]

    [INFO] Apache Hadoop Scheduler Load Simulator ............ SUCCESS [1.044s]

    [INFO] Apache Hadoop Azure Data Lake support ............. SUCCESS [0.674s]

    [INFO] Apache Hadoop Tools Dist .......................... SUCCESS [4.542s]

    [INFO] Apache Hadoop Kafka Library support ............... SUCCESS [0.188s]

    [INFO] Apache Hadoop Tools ............................... SUCCESS [0.015s]

    [INFO] Apache Hadoop Distribution ........................ SUCCESS [18.374s]

    [INFO] ------------------------------------------------------------------------

    [INFO] BUILD FAILURE

    [INFO] ------------------------------------------------------------------------

    [INFO] Total time: 2:58.223s

    [INFO] Finished at: Tue Nov 01 17:10:11 BRST 2016

    [INFO] Final Memory: 250M/629M

    [INFO] ------------------------------------------------------------------------

      [ERROR] Failed to execute goal org.apache.hadoop:hadoop-maven-plugins:3.0.0-alpha1:cmake-compile (cmake-compile) on project hadoop-ma

        preduce-client-nativetask: make failed with error code 2 -> [Help 1]

        org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.hadoop:hadoop-maven-plugins:3.0.0-alpha1:cm
        ake-compile (cmake-compile) on project hadoop-mapreduce-client-nativetask: make failed with error code 2
      at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217)

      at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)

      at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)

      at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)

      at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)

      at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)

      at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)

      at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)

      at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)

      at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)

      at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)

      at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)

      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

      at java.lang.reflect.Method.invoke(Method.java:498)

      at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)

      at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)

      at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)

      at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)

Caused by: org.apache.maven.plugin.MojoExecutionException: make failed with error code 2

    at org.apache.hadoop.maven.plugin.cmakebuilder.CompileMojo.runMake(CompileMojo.java:229)

    at org.apache.hadoop.maven.plugin.cmakebuilder.CompileMojo.execute(CompileMojo.java:96)

    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)

    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)

        ... 19 more

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-antrun-plugin:1.7:run (dist) on project hadoop-mapreduce: An Ant BuildE
xception has occured: exec returned: 1

[ERROR] around Ant part ...<exec failonerror="true" dir="/home/hadoop/mnt/hadoop-3.0.0-alpha1-src/hadoop-mapreduce-project/target" ex
ecutable="bash">... @ 10:125 in /home/hadoop/mnt/hadoop-3.0.0-alpha1-src/hadoop-mapreduce-project/target/antrun/build-main.xml

[ERROR] -> [Help 1]

org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-antrun-plugin:1.7:run (
dist) on project hadoop-mapreduce: An Ant BuildException has occured: exec returned: 1
around Ant part ...<exec failonerror="true" dir="/home/hadoop/mnt/hadoop-3.0.0-alpha1-src/hadoop-mapreduce-project/target" executable
="bash">... @ 10:125 in /home/hadoop/mnt/hadoop-3.0.0-alpha1-src/hadoop-mapreduce-project/target/antrun/build-main.xml

    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217)

    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)

    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)

    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)

    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)

    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)

    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)

    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)

    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)

    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)

    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)

        at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)

        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

        at java.lang.reflect.Method.invoke(Method.java:498)

        at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)

        at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)

        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)

        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)

Caused by: org.apache.maven.plugin.MojoExecutionException: An Ant BuildException has occured: exec returned: 1
around Ant part ...<exec failonerror="true" dir="/home/hadoop/mnt/hadoop-3.0.0-alpha1-src/hadoop-mapreduce-project/target" executable
="bash">... @ 10:125 in /home/hadoop/mnt/hadoop-3.0.0-alpha1-src/hadoop-mapreduce-project/target/antrun/build-main.xml

    at org.apache.maven.plugin.antrun.AntRunMojo.execute(AntRunMojo.java:355)

        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)

        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
        ... 19 more

Caused by: /home/hadoop/mnt/hadoop-3.0.0-alpha1-src/hadoop-mapreduce-project/target/antrun/build-main.xml:10: exec returned: 1

    at org.apache.tools.ant.taskdefs.ExecTask.runExecute(ExecTask.java:646)

        at org.apache.tools.ant.taskdefs.ExecTask.runExec(ExecTask.java:672)

        at org.apache.tools.ant.taskdefs.ExecTask.execute(ExecTask.java:498)

        at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)

        at sun.reflect.GeneratedMethodAccessor23.invoke(Unknown Source)

        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

        at java.lang.reflect.Method.invoke(Method.java:498)

        at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)

        at org.apache.tools.ant.Task.perform(Task.java:348)

        at org.apache.tools.ant.Target.execute(Target.java:390)

        at org.apache.tools.ant.Target.performTasks(Target.java:411)

        at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)

        at org.apache.tools.ant.Project.executeTarget(Project.java:1368)

        at org.apache.maven.plugin.antrun.AntRunMojo.execute(AntRunMojo.java:327)

        ... 21 more

[ERROR]

[ERROR] Re-run Maven using the -X switch to enable full debug logging.

[ERROR]

[ERROR] For more information about the errors and possible solutions, please read the following articles:

[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

[ERROR]

[ERROR] After correcting the problems, you can resume the build with the command

[ERROR]   mvn <goals> -rf :hadoop-mapreduce-client-nativetask


text:
Q: cannot find symbol com.google.android.gms.games.snapshot I'm trying to implement "SaveGame" with Google Play Services and I have the following error:
error: cannot find symbol
import com.google.android.gms.games.snapshot;
                                    ^
symbol:   class snapshot
location: package com.google.android.gms.games

Anyone knows what can cause this?
Thanks!

A: I just found the issue.
It looks the issue was caused by having dependencies to gms in two modules, the module that was reporting the error was 8.4.0, but some other module had a dependency to 6.x.
Now I've changed everything to 8.4.0 and it compiles correctly.
Also the correct import is:
com.google.android.gms.games.snapshot.* since there is no class snapshot.

A: I think you have not yet imported the Google Play Services in your application. Kindly double check it.
For Eclipse:

Eclipse -> import -> existing android code -> browse -> navigate to
   google-play-services_lib FOLDER
   (android-sdk/extras/google/google_play_services/libproject).
then, on your project, control click -> properties -> android ->
   libraries, add -> select the project you just imported -> ok

For Android Studio
build.gradle - app level
dependencies {
    compile 'com.google.android.gms:play-services:8.4.0'
}

For more inquiries, check this link.


text:
Q: Add individual user to sudoers file using SSSD in Ubuntu? I've set up SSSD on one of our Linux VMs and added an AD group to the sudoers file. That works fine. The issue I'm having is I have another user who is not in the group that needs sudo access.
I added %firstname.lastname ALL=(ALL:ALL) ALL to the bottom of the sudoers file but when he trys he gets an error saying he's not in the file.
Any ideas?

A: The command to add a user to sudoers is:
sudo adduser <username> sudo

You need to run this command from a user who already has sudo privileges.
Otherwise, you need to run the command adduser <username> sudo as the root user.


text:
Q: Call a node.js function inside an html file This is most likely a repeated question.
The closest I got to an answer was here: execute a Nodejs script from an html page?
Yet, I still can't understand.
So here's the situation:
I have an express server setup with the following files:

*

*Express App

server.js
  index.html

and right now I want the html folder to have a button, that calls a function set in the node.js file.
Tell me if more information is needed, thanks!
EDIT:
Im remaking the question to be more clear.
I am using an express server to present a website, that present a button saying " Power Off", I want this button to be able to execute an action on my server computer, that action being a terminal command to power it off.
I wanted to know how could I make said button, written in HTML, hosted on the server but presented to the client, to interact with the server.js file hosted on the server, which would have a function set to execute said command.
thanks!

A: I'm not an expert with Node, but I think what's happening here is blurring the lines between server and client. Even though both use JavaScript, there's a distinction. NodeJS could easily be replaced with Ruby, PHP, Java, whatever-backend-language-you-like, and this distinction would apply in the same way it does when you use JavaScript on the server. There's no differerence.
Server-side code executes on the server. Client side code executes on the client (the browser). If you need to call a NodeJS function (assuming it has to interact with the other server side code such as databases etc) then you can send a request, either via AJAX or standard HTTP, to the a route on the server and call that function within the route.
On the other hand, if the function is generic enough and doesn't involve any specific Node code then you can simply add a script tag with your JavaScript file to the index.html page.

A: You need to understand a little better how the client/server architecture of a web page works and where code actually runs and how the client and server communicate with one another.
You can't call a function directly on your node.js server from an HTML file.  The HTML file is in the client's browser.  The node server is your web server, far away from the client's browser on different computers.  Though it may seem like your HTML is on your node.js server because it's in a directory on that server, that's only where it is stored.  When the browser requests that page, your node.js server sends the HTML to the client's browser and it is rendered back in the client browser and that's where the Javascript in that page runs (in the client's browser, far away from your node.js server).  This is a client-server architecture.  The HTML page is running on the client.  The node.js server is on your server - different computers.
If you want to communicate with the node.js server from the web page, then you use Javascript in the HTML page to make an Ajax call from the Javascript in the web page to the node.js server (An Ajax call is an http request).  You then configure a route in the node.js server for that specific Ajax call and you can then write code in node.js to do whatever you want to happen when that Ajax call is received.  It can carry out some operation on the server, it can retrieve data and return it to the client, etc...  You can optionally send data with the Ajax call (either as query parameters for a GET request or as body data for a POST request) and then the server can optionally return data back to you (often as JSON, but it can be any format you like).

A: There is a difference between server and client. You cannot just call a function on a server from a client directly, there is more to just that. If you wanted to, you could do it by routing a path to wherever and making an HTTP request to that path, or even, using other protocols like WebSocket if you need to communicate both ways.


text:
Q: Probability - Show inequality $P(A \cap B) \ge P(A) + P(B)-1$ My task is to show that:
$$P(A \cap B) \ge P(A) + P(B)-1$$
The rule inclusion-exclusion is:
$$P(A\cup B) = P(A) + P(B) - P(A \cap B)$$
If I rewrite this rule, I get
$$P(A\cap B) = -P(A \cup B) + P(A) + P(B)$$
Am I on the right track, and if so, how do I proceed?

A: Yes you are on the right track. Now, you should that any probability is $\le 1$.
So $P(A\cup B)\le 1\implies -P(A\cup B)\ge -1$.
Hence your answer.

A: Yes, you are completely on the right track. Now, if you get easily confused by the direction of inequalities you could also write
$$
P(A\cup B) = P(A) + P(B) - P(A \cap B)
$$
since in $(\Omega,P,\mathcal{F})$ we have
$$
\forall A\in\mathcal{F}: 1\geq P(A)
$$
as
$$
1\geq P(A\cup B) = P(A) + P(B) - P(A \cap B)
$$
so
$$
1\geq P(A) + P(B) - P(A \cap B)\Leftrightarrow P(A \cap B)\geq P(A) + P(B)-1
$$


text:
Q: Selenium Webdriver with Python: Firefox Profile Handling I have created a new firefox profile, that I want to use for the automated tests. When calling firefox manually with this profile then I see the menu bar and the bookmarks toolbar.
But when using this profile within my code I still get no menubar and no bookmarks toolbar
myprofile = webdriver.FirefoxProfile('C:/Users/xxxxx/Documents/1tm2mblc.WebDriver_Profile')
driver = webdriver.Firefox(executable_path="C:\\Program Files (x86)\\eclipse\\geckodriver.exe", firefox_profile=myprofile)

So the behaviour is exactly the same as if I don't specify any profile at all.
If I put a typo in the profile path then I get an error message, so the profile seems not to be ignored...
Geckodriver log: https://www.dropbox.com/s/awg3kv2x1lqetpo/geckodriver.log?dl=0
Logfile with DEBUG Trace Level contains the following lines:
02/02/2018 12:50:44 PM POST http://127.0.0.1:55237/session {"capabilities": {"firstMatch": [{}], "alwaysMatch": {"browserName": "firefox", "acceptInsecureCerts": true, "moz:firefoxOptions": {"profile": "UEsDBBQAAAAIADBGQUygpt2X......"
02/02/2018 12:51:15 PM Finished Request {'value': {'sessionId': 'ebdcc867-62c8-4c8c-900b-ba272fd15345', 'capabilities': {'acceptInsecureCerts': True, 'browserName': 'firefox', 'browserVersion': '58.0.1', 'moz:accessibilityChecks': False, 'moz:headless': False, 'moz:processID': 5316, 'moz:profile': 'C:\\Users\\herololi\\AppData\\Local\\Temp\\rust_mozprofile.8xCt6R02aSkK', 'moz:webdriverClick': True, 'pageLoadStrategy': 'normal', 'platformName': 'windows_nt', 'platformVersion': '6.1', 'rotatable': False, 'timeouts': {'implicit': 0, 'pageLoad': 300000, 'script': 30000}}}}
02/02/2018 12:51:15 PM POST http://127.0.0.1:55237/session/ebdcc867-62c8-4c8c-900b-ba272fd15345/url {"url": "http://only-testing-blog.blogspot.in/2014/05/login.html"}
02/02/2018 12:51:25 PM Finished Request {'value': {}}
02/02/2018 12:51:25 PM POST http://127.0.0.1:55237/session/ebdcc867-62c8-4c8c-900b-ba272fd15345/timeouts {"implicit": 20000}
02/02/2018 12:51:25 PM Finished Request {'value': {}}
02/02/2018 12:51:30 PM DELETE http://127.0.0.1:55237/session/ebdcc867-62c8-4c8c-900b-ba272fd15345/window {}
02/02/2018 12:51:32 PM Finished Request {'value': []}

Please note that I have truncated the first line, as the profile entry is incredibly long and makes the file (with only 8 lines) 224 MB big...
Any advice? Thanks
Python 3.6.4
Selenium Webdriver 3.8.1


text:
Q: How to get the order in which the options were selected in an angular select? I am working with a form in Angular, using Angular Material. I need to get the order in which the options were selected in a select.
https://material.angular.io/components/select/overview#multiple-selection
I was testing with selectionChange but I did not find anything concerning the order in which the elements have been selected.

A: I'm not sure which is the best option but you can send the event to the .ts file and with some JS make up logic to see which was chosen in which order first. #advice
Also it would help if you post some of your code to point you in the right direction.


text:
Q: Move files to new folderif string matches I'm trying to go through a number of folders and check their contents.
If one or more of the files inside matches any of the strings in a given list, I would like to move those files to a new folder. I already have the new folder.

A: #!/bin/bash

find /path/to/sourcedir -type f | grep "string1\|string2\|string3" | while read f
do
  mv "$f" /path/to/destination
done

If you have many strings you can skip  "string1\|string2\|string3" and
use  grep --file=file_of_patterns.txt where file_of_patterns.txt is a textfile containing the strings you want to match (one per line)


text:
Q: CFArgument is causing the function to return ERROR 415 I am trying to create a REST web service in CF11 and I am getting an error that I don't really understand where it comes from.
Step 1
I created a function which it returns the results of a query - Works fine
Step 2
Added a few CFArguments and the function returns 415 Unsupported Media Type
Step 3
Removed the cfarguments and the function works again.....
Anyone with a recommendation please?
This is the component
<cfcomponent restpath="student" rest="true">
    <cffunction name="dbTest" access="remote" output="false" returntype="query"  httpmethod="get" restpath="dbTest">

        <cfargument name="addSFSurveys" type="numeric" required="No" default="0">
        <cfargument name="showRatings" type="numeric" required="No" default="5">
        <cfargument name="siteID" type="numeric" required="No" default="0">
        <cfargument name="pageID" type="numeric" required="No" default="0">
        <cfargument name="includeDoctor" type="numeric" required="No" default="1">
        <cfargument name="topReviews" type="string" required="No" default="">
        <cfargument name="testimonialID" type="string" required="No" default="">
        <cfargument name="procedureID" type="string" required="No" default="">
        <cfargument name="detailedScore" type="string" required="No" default="">
        <cfargument name="minScore" type="string" required="No" default="">
        <cfargument name="maxScore" type="string" required="No" default="">

        <cfquery name="testimonials" datasource="dpsigweb2">
                select distinct top 10 cast(t.testimonial as varchar(max)) as testimonial, t.contactid, t.doctorid,
                c.first as first, left(c.last,1) as last, c.city, c.state, d.practiceNameDisplay, t.featured, t.owneridfk , cd.city as docCity, cd.state as docState, cd.zip as docZip,
                '' as sorter, t.testimonialID , cast(t.title as varchar(max)) as title ,cast(st.finalscore as  decimal(10,1)) as finalscore, CAST(se.procedureID AS varchar(25)) COLLATE Latin1_General_BIN as procedureID,
                st.dateComplete as surveyDate, se.revenue as cost, se.locationName, consultloc = (select top 1 se2.locationname from survey.dbo.survey_events se2 join survey.dbo.surveys s on se2.surveytypeidfk = s.id
                where c.contactid = se2.contactidfk and se2.locationname is not null and isnull(s.surveytypecatidfk,0) <> 1 order by se.eventdate desc)
                from testimonials t
                join contact c on t.contactid = c.contactid
                join doctor d on t.doctorid = d.doctorID
                join contact cd on cd.contactID = d.contactID
                left join testimonial_sites ts on ts.testimonialID = t.TestimonialID
                left join survey_tracking st on st.owneridfk= t.owneridfk
                left join survey.dbo.survey_events se on se.id= st.surveyEventID
                where t.owneridfk != ''
                and ts.siteID= '9'
                order by surveyDate desc
          </cfquery>

        <cfreturn testimonials>
    </cffunction>
</cfcomponent>

The Result

A: You should add a restArgSource to the <cfargument> so that it can figure out where to get the variables from
see https://wikidocs.adobe.com/wiki/display/coldfusionen/cfargument
Hope that gives you a bit of a guide


text:
Q: Click button without ID using VBA I want to download historic data from NASDAQ using VBA. I have managed to change the "FromDate" to the proper range but I haven't managed to get the code to hit the "Search" button (as it has no ID) which extracts the data. Please help me out.
MY VBA:
Sub OMX_data()

Dim URL As String
Dim ie As InternetExplorer

Set ie = New InternetExplorer
ie.Visible = True

ie.navigate ("http://www.nasdaqomxnordic.com/indexes/historical_prices?Instrument=DK0060368991")

Do
DoEvents
Loop Until ie.readyState = 4

ie.document.all("FromDate").Value = "2018-01-01"

End Sub

THE HTML

Search

A: You can get search button element by class using getElementsByClassName and can trig it by Click method, doSearch is the name of search button in this form.
The last two line is the solution of your question.
Sub OMX_data()
    Dim URL As String
    Dim ie As InternetExplorer

    Set ie = New InternetExplorer
    ie.Visible = True

    ie.navigate ("http://www.nasdaqomxnordic.com/indexes/historical_prices?Instrument=DK0060368991")

    Do
        DoEvents
    Loop Until ie.readyState = 4

    ie.Document.all("FromDate").Value = "2018-01-01"

    Set search_button = ie.Document.getElementsByClassName("doSearch")
    search_button(0).Click
End Sub

You can use HTML DOM to import data to Excel,
Below is example to import data to Excel
Sub OMX_data()
    Dim URL As String
    Dim ie As InternetExplorer

    Set ie = New InternetExplorer
    ie.Visible = True

    ie.Navigate ("http://www.nasdaqomxnordic.com/indexes/historical_prices?Instrument=DK0060368991")

    Do
        DoEvents
    Loop Until ie.ReadyState = 4

    ie.Document.all("FromDate").Value = "2018-01-01"

    Set search_button = ie.Document.getElementsByClassName("doSearch")
    search_button(0).Click

    ' Wait for filter apply
    Application.Wait (Now + TimeValue("0:00:05"))

    ' Use HTML DOM
    Set result = ie.Document.getElementById("historicalOutput").getElementsByTagName("tbody")(0).getElementsByTagName("tr")

    i = 0   ' for row
    For Each r In result
        j = 0   ' for column
        For Each c In r.Children
            Range("A1").Offset(i, j).Value = c.innertext
            j = j + 1
            DoEvents
        Next
        i = i + 1
    Next

    MsgBox "Import finish"
End Sub


text:
Q: How should Models an ViewModels interact? How does the interaction between Model and ViewModels should be?
Supposing I've a class named Customer with Id and Email properties, and another one CustomerModel with the very same properties.
This is the scenario:
I load a view based on that CustomerModel, this view has a form. As form is submitted, the CustomerModel is passed upon to the Action, let's say, Save. In the Save action should I create an instance of Customer and populate it property by property?
Example below:
ActionResult Save(CustomerModel cm)
{
   //validation goes here

   Customer c = new Customer();
   c.Id = cm.Id;
   c.Email = cm.Email;

   context.Entry<Customer>(c).State = System.Data.EntityState.Modified;
   context.SaveChanges();

   //continue
  }

Given I read in an earlier post that I should avoid use model class for both purposes, data and view model, I ask:
Is that correct way to implement it?

A:
How does the interaction between Model and ViewModels should be?

The view models describe data to the view. It is for presentation logic and providing data to the view. The models are for describing data from your data source such as sql or a file.
Example of stuff in your view models:
public class CustomerViewModel
{
    public long Id { get; set; }
    public bool IsFoundingMember { get { return Id < 1000; } }
    public string Name { get; set; }
    public bool IsABaggins { get { return !string.IsNullOrWhiteSpace(Name) ? Name.EndsWith("Baggins") : false; } }
}

Example of stuff in your models
public class Customer
{
    public long? Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public DateTime? DateOfBirth { get; set; }
}

I would try grouping the logic into functions for maintainability.
Say:
ActionResult Save(CustomerModel cm)
{
   if(!ValidateCustomerModel(cm))
   {
        //Deal with invalid data
   }

   UpdateCustomer(cm);

   //continue
}

public bool ValidateCustomerModel(CustomerModel model)
{
    //Do stuff
    return true;
}

public void UpdateCustomer(CustomerModel model)
{
   Customer c = new Customer();
   c.Id = cm.Id;
   c.Email = cm.Email;

   context.Entry<Customer>(c).State = System.Data.EntityState.Modified;
   context.SaveChanges();
}

After you have all of your CRUD logic separated out you could make some classes for that logic and look into Unity, Ninject, or plain old constructor injection.
e.g. Constructor Injection
public class MyController : Controller
{
    private readonly ICustomerDL _customerDL;
    public MyController(ICustomerDL customerDL)
    {
        _customerDL = customerDL;
    }

    //Load your implementation into the controller through the constructor
    public MyController() : this(new CustomerDL()) {}

    ActionResult Save(CustomerModel cm)
    {
       if(!ValidateCustomerModel(cm))
       {
            //Deal with invalid data
       }

       _customerDL.UpdateCustomer(cm);

       //continue
    }

    public bool ValidateCustomerModel(CustomerModel model)
    {
        //Do stuff
        return true;
    }
}

public interface ICustomerDL
{
    void UpdateCustomer(CustomerModel model);
}

public class CustomerDL : ICustomerDL
{
    public void UpdateCustomer(CustomerModel model)
    {
       Customer c = new Customer();
       c.Id = cm.Id;
       c.Email = cm.Email;

       context.Entry<Customer>(c).State = System.Data.EntityState.Modified;
       context.SaveChanges();
    }
}

The benefit is all of your logic will be clean and structured which will make Unit Testing and code maintenance a breeze.


text:
Q: Why multiplying 1.0 to 5 gave output 5 and not 5.0? cout<<5*1.0<<endl;
cout<<(float)5<<endl;

In both cases I got 5 as an answer and not 5.0. Please help...

A: You need to specify the format and precision for floatingPoint output, such as:
std::cout << std::fixed << std::setprecision(1) << 5*1.0;

LIVE
From [The.C++.Programming.Language.Special.Edition] 21.4.3 FloatingPoint Output [io.out.float]:

Floatingpoint output is controlled by a format and a precision:
– The
general format lets the implementation choose a format that presents a
value in the style that best preserves the value in the space
available. The precision specifies the maximum number of digits. It
corresponds to printf()'s %g (§21.8).
– The scientific format presents
a value with one digit before a decimal point and an exponent. The
precision specifies the maximum number of digits after the decimal
point. It corresponds to printf()'s %e .
– The fixed format presents a
value as an integer part followed by a decimal point and a fractional
part. The precision specifies the maximum number of digits after the
decimal point. It corresponds to printf()'s %f .


text:
Q: Drupal 7. In 'node.tpl.php' how would I limit and offset the results? Apologies, novice Drupal question warning:
Aim: to split my outputted list of custom field images up so I can use them differently.
ie. In my node.tpl.php use the first 3 (most recent node) images in a slider. Then list the rest (offsetting the first three) just as plain images.
But I can't find how to limit my results. In my node template I can style all my images up using something like this:
<a href="<?php $nodeurl = url('node/'. $node->nid); echo $nodeurl; ?>"
 <img src="<?php print render (file_create_url($node->field_featured_image['und'][0]['uri'])); ?>" alt="<?php echo $title; ?>" />

But how do I limit the result? I guess this would work to ignore the first 3 results:
<?php foreach($node->field_featured_image as $k=>$v){
  if ($k < 3) continue;
  print render (file_create_url($node->field_featured_image['und'][0]['uri']));
 }
?>

But not in node.tpl as node.tpl appears to be a loop so the above code gets looped and the array key never gets past 0.
I think :/
Am I way off here with a basic misunderstanding of the templates?
Any pointers appreciated. Desperately trying to stick with drupal but finding it tough.

A: I might be mislead by what you're trying to accomplish, but you probably don't need to be hacking into node.tpl.php just yet.
If you aren't using Views, start with that.
If you're trying to build a slider, use Views Rotator.
If you want something that's ready to be dropped in, use Enterprise Rotator. (basically Views Rotator and a Banner Slide content type built out already).
You can offset the images by using the pager options to either show a certain number, and offset the number of images queued up.
Or if you want to just use specific images, use Nodequeue. Make a simple queue, add the nodes that contain the images you want, then in your View create a relationship (marked as required) to the nodequeue.


text:
Q: @AuthenticationPrincipal not up to date after permission change I have a controller which is called by an ajax call when a button is pressed in a modal dialog.
@PostMapping(path = "/{year}/{week}/{scheduleId}/publish/ajax")
@PreAuthorize(MA_CMA_CHEF_PUBLISH_CONDITION)
public String publishSchedule(Model model, @PathVariable Long locationId,
    @PathVariable Integer year,
    @PathVariable Integer week,
    @PathVariable Long scheduleId,
    @RequestBody SchedulePostInfo scheduleInfo,
    @AuthenticationPrincipal ApplicationUser appUser) {
    return super.publishSchedule(model, scheduleId, scheduleInfo, appUser);
}

I am trying to test that the authorization works, and do the following:
Make sure the user has the necessary permissions.
Open the modal dialog, and do not click the publish button immediately.
Then, in the permissions tool, as an admin in a separate browser, remove the publish permission and save in order to pull the permission from the user.
Now, in the modal dialog, press "publish".
This works without any error(but it should not) and debug output show the "publish" permission is still set in the application user context (created from the principal).
My first question is, is this due to the principal not being up to date?
My second question is, can it be fixed?


text:
Q: NGINX reverse proxy with Rewrites to replace TMG2010 I curently have a Forefront TMG2010 doing reverse proxy to several internal web servers. Since it was really easy in TMG I have done lots of host and virtual directory mappings/rewrites.
Now I ened to acheive the same in NGINX.
e.g.,
apphost.domain.com/ needs to map internally to server1/apppath/
apphost.domain.com/test/ needs to map internally to server2/apppath/
apphost.domain.com/dev/ needs to map internally to server3/apppath/
in each case the internal /apppath/ needs to be invisible to the client. This is to achieve the same as the external to internal path mapping in TMG.
What I have done so far is;
server {

    listen  80;

    server_name  host.server.com;

    location /test/ {
    proxy_set_header    Host    $host;
    rewrite ^(.*)$ /app/$1 break;
        proxy_pass  http://10.0.0.2;
    }

    location / {
    proxy_set_header    Host    $host;
    rewrite ^(.*)$ /app/$1 break;
    proxy_pass  http://10.0.0.1;
        }

But only the / seems to work, the /test/ doesnt.
Help!

A: So you want to map /test/foo to http://10.0.0.2/app/foo. The simplest solution is:
location /test/ {
  proxy_set_header    Host    $host;
  proxy_pass  http://10.0.0.2/app/;
}

According to the documentation the /test/ element will be replaced by /app/ as it passes upstream.


text:
Q: Python HTTP server, can't use images What I've done:
I've created a small HTTP server python, using no modules but socket. It manages to start, load HTML and then send it out,
so you can see the HTML file in your browser.
What I'm using:
I'm using Python 3.5.1, I'm also using Socket.
The problem:
Images do not show on the web browser.
Here is the code I have put together:
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

HOST = ''
PORT = 8888

asked_url = []

s.bind((HOST, PORT))

s.listen(1)

while True:
    conn, addr = s.accept()

    request = conn.recv(1024)

    html_file = open("page.html", 'rb')
    try:
        http_response = html_file.read()
        conn.sendall(http_response)
        conn.sendall(b'
PyWeb
')
    except:
        print("Couldn't send any data! Passing...")
        pass
    conn.close()

Here is also the HTML code for the page, However it doesn't seem to be the problem:

  My awesome server is currently !

What the HTML code does:
Shows text and an image.
If you need more detail just ask.

A: Where is test.png located? Looks like your HTML is having an issue finding the file. I ran your code locally and was able to see an image when I changed to image tag to source an image from a url.
I checked chrome dev tools first and noticed the image tag rendered fine.
I changed the image tag to (random image from google image search):
`<img src="http://emojipedia-us.s3.amazonaws.com/cache/f8/69/f869f6512b0d7187f4e475fc9aa7f250.png" alt="Test Image">`

And it showed up fine.

A: The issue is that no matter what the request you get to your HTTP server you are sending the content of page.html as response. This is because you hard coded this line in your server.
html_file = open("page.html", 'rb')

In your page.html you have an image that means browser (or any client that you use) will send a call to your server asking for image's source (content of test.png) but instead of reading the image's source you are again serving page.html's content. That is why the image appears broken.
To fix this you need to look at the resource that is requested and open that file and send the content as response from server.  Take a look at what you have in request variable in your server code to get an idea of how you can get the name of the resource requested.
You might also want to send out the proper content-type header to let the client know how it has to handle the response.


text:
Q: What location is most appropriate to download update to Asset file? Sorry for the noob question. I am still pretty new to Android development.
I am currently working on an Android app that was designed to pull some images from a zip file sitting in the Assets directory. The original goal, it seems, was to have the app check a server to see if the zip had been updated, and then download the new zip in the case that it had.
The problem is that the Assets directory, if I understand correctly, is read only.
The thing is- I still need to be able to follow their original design of checking the server for an update to this file and downloading the new one. Since the file is hefty in size, simply downloading it to memory every time isn't really feasible. So, with that said, I need somewhere static to download it to so that I can tell the app at start up to look there first, and if that is empty then use the backups in Assets.
Is the root folder of the app the best place to download this file, which will remain indefinitely, possibly be replaced often and be read from on every run? Or is that against standard design procedures?
Thanks!

A: like you sad, asset folder is read only. You can't save anything there programmatically.
If you want save some data you  have to create folder of your app on mobile storage. For example data/yourApkName then save some file there.
String content = "hello world";
File file;
FileOutputStream outputStream;
try {
    file = new File(Environment.getExternalStorageDirectory(), "youtApkName");

    outputStream = new FileOutputStream(file);
    outputStream.write(content.getBytes());
    outputStream.close();
} catch (IOException e) {
    e.printStackTrace();
}

You also can create cache/temporary files.

Saving cache files
To open a File that represents the external storage directory where
  you should save cache files, call getExternalCacheDir(). If the user
  uninstalls your application, these files will be automatically
  deleted.
Similar to ContextCompat.getExternalFilesDirs(), mentioned above, you
  can also access a cache directory on a secondary external storage (if
  available) by calling ContextCompat.getExternalCacheDirs().
Tip: To preserve file space and maintain your app's performance, it's
  important that you carefully manage your cache files and remove those
  that aren't needed anymore throughout your app's lifecycle.

If you want sane files on storage you have to add this to your manifest
<manifest ...>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
                     android:maxSdkVersion="18" />
    ...
</manifest>

If you are looking after method to download files you have to look here.


text:
Q: Docker can not install yarn packages I am trying to transform my NodeJs app into a Docker container, but during the "yarn" command, the container is having errors while installing the dependencies. I already removed unnecessary dependencies and cleaned node cache, but it still having this error.
There's the error:
 => ERROR [4/5] RUN yarn                                                                       21.3s
------
 > [4/5] RUN yarn:
#0 0.772 yarn install v1.22.19
#0 0.887 [1/4] Resolving packages...
#0 1.074 [2/4] Fetching packages...
#0 6.223 error An unexpected error occurred: "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.15.2.tgz: getaddrinfo EAI_AGAIN registry.yarnpkg.com".
#0 6.223 info If you think this is a bug, please open a bug report with the information provided in "/usr/app/yarn-error.log".
#0 6.223 info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
------
failed to solve: executor failed running [/bin/sh -c yarn]: exit code: 1

I tried removing unnecessary dependencies and cleaning the node cache, also deleted the node_modules folder and re-installed the project in my machine, and it worked just fine, while Docker was having this errors.
Dockerfile
FROM node:16-alpine

WORKDIR /usr/app
COPY package.json yarn.lock ./

RUN yarn

COPY . .

EXPOSE 3000
CMD ["yarn", "start"]

docker-compose.yml
version: '1'

services:
  app:
    container_name: nodejs-backend
    build: .
    ports:
      - "3000:3000"
    command: yarn start

.dockerignore
node_modules

I am also starting the container with this command: docker-compose up


text:
Q: Is there a way to use VBA to change the language in VBA generated worksheets? I was assigned a project at work to develop a Macro that would automatically take financial data from an Excel table and generate credit notes and invoices for customers. I have the Macro developed already it is working the way it should, but the issue I am running into is with the language that is used for each invoice.
When generating credit notes, the Macro is taking the the invoices month of issue from the financial data table and displaying then as them as the months where credit was issued to the customer. i.e., a customer is requesting a partial refund on transactions from a period of time (say Feb.2019 - Apr. 2019) it will be displayed as:
February 2019 (02-19)     -20.20
March 2019 (03-19)        -32.03
April 2019 (04-19)        -24.21

The problem is that my primary working language is English, but my company works in several European marketplaces and the invoices and credit notes have to be displayed in the language of the market where the customer is located.
So if an Italian customer requests an invoice, the months displayed must be listed as
Febbraio 2019 (02-19)     -20.20
Marzo 2019 (03-19)        -32.03
Aprile 2019 (04-19)       -24.21

However, when running the Macro it still displays the issuing months in English when it should be displayed in the language of the market. The entirety of all invoices and credit notes created with this Macro are generated in the correct language, but since the Macro is taking the issuing months from the data table it automatically displays them in English.
Is the any way to ensure that it displays the issuing months in the required language?
I already know that the language settings can be changed for the entire workbook, but I still run into the same problem as I would have to manually change the issuing language each time I run the Macro to ensure the issuing month is correct?

A: To format a date in another regional setting you need to change the number format of the date for the desired range of cells. Eg. format the cell pressing Ctrl+1 to get the following dialog, and choose the regional setting ("Gebietsschema") for the country you desire.

Image 1: Change the regional setting for the date (sorry for the German screenshot).
Alternatively use the Range.NumberFormat property to format the cell with VBA:
.NumberFormat = "[$-it-IT]d mmmm yyyy;@"

Note that these both work if your dates are real date values but don't work if your dates are text. If they are text you need to change them into real dates.


text:
Q: Jupyter Notebook runs import statements, then hangs My Jupyter Notebook will no long "Run All Above". It runs the first cell (import statements), seemingly without an error, then won't run anything after that, even when they are simple function definitions. If I reverse the order, it will run everything up to and including the import statements, but nothing after. If I run the cells one-by-one, they work fine, so that leads me to believe I have some problem with the way Jupyter is handling one or more of my imports. I also cannot interrupt the kernel; the un-run cells still show as busy. I have to restart the kernel to run it again.
Here is the About information from Jupyter:
The version of the notebook server is 4.1.0 and is running on:
Python 2.7.13 |Anaconda custom (64-bit)| (default, Dec 19 2016, 13:29:36) [MSC v.1500 64 bit (AMD64)]

Current Kernel Information:

Python 2.7.13 |Anaconda custom (64-bit)| (default, May 11 2017, 13:17:26) [MSC v.1500 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

IPython 4.0.3 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.
%guiref   -> A brief reference about the graphical user interface.

Here are my import statements:
import os
import pandas as pd
import numpy as np
import math
import datetime
import seaborn as sns
import matplotlib.pyplot as plt
from jinja2 import Environment, FileSystemLoader
import pdfkit

# %matplotlib inline

And a generic function that doesn't run if I run the imports first, but will run if I run it before the imports.
def load_data(file_path):
    """Function that does something"""
    pass

I've tried commenting out the imports one-by-one but nothing changed. It also runs fine on my MacBook. Any ideas?


text:
Q: Is there a way to convert a List to a PagedData while the backing paging source data doesn't use room db
*

*I do have a paged data source that returns a PagedData<T> data that is displayed with the  pagedAdapter after initial load from SQLite. After some server transactions,I receive a list
of List<T> and after transforming and caching it need to display it.

*I know this would be easy with Room db but that's off the table for now.How do I update the initial paged list and create a new pagedList and then push it to the adapter.

*Tried using a map transformation on the new server list to PagingDataObject but it's not possible as far as I know. list.map { item -> {PagingData<item>}

A: If you want you can implement your own pagingSource, it's not necessary to use Room.
The first half of paging3 codelab shows you exactly how you can achive that. Create your pager like this :
Pager(
      config = PagingConfig(
        pageSize = 10,
        enablePlaceholders = false
     ),
      pagingSourceFactory = { MyPaginSource() }
).flow

and implement MyPaginSource like this :
class MyPaginSource() : PagingSource<Int, MyItem>() {

override suspend fun load(params: LoadParams<Int>): LoadResult<Int, MyItem> {
    if(params.key == null){
        //load initial list from where ever you want, and create your own key
        //to load next page of data
        val firstPage = //todo
        val nextKey  = //todo
        return LoadResult.Page(
                data = firstPage ,
                prevKey = null,
                nextKey = nextKey
        )
    } else{
        //load the other pages based on your key, for example from server
        val newPage = //todo
        val nextKey  = //todo if you need to continue loading
        return LoadResult.Page(
                data = newPage ,
                prevKey = null,
                nextKey = nextKey
        )
    }
}
}


text:
Q: How can i specify an area of code to instrument it by pintool? There are four levels of granularity in Pin: routine, instruction and image, trace.
Can i specify an limits/area to start and stop inserting instrumentation code.
may by like directive like ( # start instrumentation , # end instrumentation )
or some thing like that,
An example:
for( int i=0; i< x; i++)
       {
         #startInstrumentation
         for( ....;.....;.....)
           {
             // some code
             // function call, conditions , loops, ....
           }
         #endInstrumentation
       }

 Is there are any way to do this ?

A: You can use trace-based instrumentation to do what you want. At the beginning of each trace, check its start address and if it is not in range of interest, avoid adding analysis functions and return immediately from the routine.
It's possible that a trace will begin outside a region of interest but end inside it, or the other way around. If this can happen, you will need to perform more fine grained choice about what to instrument. I would check if this is a real concern before investing an effort.
If you're interested in instrumenting specific routines or images, consider using filter.cpp from InstLib in the kit. An example for use can be found in InstLibExamples.
Now, as for how to target these regions of interest, you have several options. If you have no control over the target binary, you can specify the region in a command line parameter, as a pair of offsets into the image of interest.
If you have control of the binary, you can insert two symbols, that specify the start and end of the rgion of interest, and then iterate over image symbols using the SYM interface.

A: My solution would be:
1) Insert Region Of Interest (ROI) begin and end functions in code
2) Set a flag after ROI begin is executed and unset it before ROI end is executed
3) Return immediately from instrumenting calls if the flat is unset
Here you have an example where I have modified the memory reference trace to trace only a ROI.
#include <stdio.h>
#include "pin.H"
#include <string>

const CHAR * ROI_BEGIN = "__parsec_roi_begin";
const CHAR * ROI_END = "__parsec_roi_end";

FILE * trace;
bool isROI = false;

// Print a memory read record
VOID RecordMemRead(VOID * ip, VOID * addr, CHAR * rtn)
{
    // Return if not in ROI
    if(!isROI)
    {
        return;
    }

    // Log memory access in CSV
    fprintf(trace,"%p,R,%p,%s\n", ip, addr, rtn);
}

// Print a memory write record
VOID RecordMemWrite(VOID * ip, VOID * addr, CHAR * rtn)
{
    // Return if not in ROI
    if(!isROI)
    {
        return;
    }

    // Log memory access in CSV
    fprintf(trace,"%p,W,%p,%s\n", ip, addr, rtn);
}

// Set ROI flag
VOID StartROI()
{
    isROI = true;
}

// Set ROI flag
VOID StopROI()
{
    isROI = false;
}

// Is called for every instruction and instruments reads and writes
VOID Instruction(INS ins, VOID *v)
{
    // Instruments memory accesses using a predicated call, i.e.
    // the instrumentation is called iff the instruction will actually be executed.
    //
    // On the IA-32 and Intel(R) 64 architectures conditional moves and REP
    // prefixed instructions appear as predicated instructions in Pin.
    UINT32 memOperands = INS_MemoryOperandCount(ins);

    // Iterate over each memory operand of the instruction.
    for (UINT32 memOp = 0; memOp < memOperands; memOp++)
    {
        // Get routine name if valid
        const CHAR * name = "invalid";
        if(RTN_Valid(INS_Rtn(ins)))
        {
            name = RTN_Name(INS_Rtn(ins)).c_str();
        }

        if (INS_MemoryOperandIsRead(ins, memOp))
        {
            INS_InsertPredicatedCall(
                ins, IPOINT_BEFORE, (AFUNPTR)RecordMemRead,
                IARG_INST_PTR,
                IARG_MEMORYOP_EA, memOp,
                IARG_ADDRINT, name,
                IARG_END);
        }
        // Note that in some architectures a single memory operand can be
        // both read and written (for instance incl (%eax) on IA-32)
        // In that case we instrument it once for read and once for write.
        if (INS_MemoryOperandIsWritten(ins, memOp))
        {
            INS_InsertPredicatedCall(
                ins, IPOINT_BEFORE, (AFUNPTR)RecordMemWrite,
                IARG_INST_PTR,
                IARG_MEMORYOP_EA, memOp,
                IARG_ADDRINT, name,
                IARG_END);
        }
    }
}

// Pin calls this function every time a new rtn is executed
VOID Routine(RTN rtn, VOID *v)
{
    // Get routine name
    const CHAR * name = RTN_Name(rtn).c_str();

    if(strcmp(name,ROI_BEGIN) == 0) {
        // Start tracing after ROI begin exec
        RTN_Open(rtn);
        RTN_InsertCall(rtn, IPOINT_AFTER, (AFUNPTR)StartROI, IARG_END);
        RTN_Close(rtn);
    } else if (strcmp(name,ROI_END) == 0) {
        // Stop tracing before ROI end exec
        RTN_Open(rtn);
        RTN_InsertCall(rtn, IPOINT_BEFORE, (AFUNPTR)StopROI, IARG_END);
        RTN_Close(rtn);
    }
}

// Pin calls this function at the end
VOID Fini(INT32 code, VOID *v)
{
    fclose(trace);
}

/* ===================================================================== */
/* Print Help Message                                                    */
/* ===================================================================== */

INT32 Usage()
{
    PIN_ERROR( "This Pintool prints a trace of memory addresses\n"
              + KNOB_BASE::StringKnobSummary() + "\n");
    return -1;
}

/* ===================================================================== */
/* Main                                                                  */
/* ===================================================================== */

int main(int argc, char *argv[])
{
    // Initialize symbol table code, needed for rtn instrumentation
    PIN_InitSymbols();

    // Usage
    if (PIN_Init(argc, argv)) return Usage();

    // Open trace file and write header
    trace = fopen("roitrace.csv", "w");
    fprintf(trace,"pc,rw,addr,rtn\n");

    // Add instrument functions
    RTN_AddInstrumentFunction(Routine, 0);
    INS_AddInstrumentFunction(Instruction, 0);
    PIN_AddFiniFunction(Fini, 0);

    // Never returns
    PIN_StartProgram();

    return 0;
}


text:
Q: PhoneGap notification.alert Won't Show the Marker Position I'm trying to show to the user the location of a marker using PhoneGap's navigator.notification.alert like this:
google.maps.event.addListener(marker, "click", function() {
    navigator.notification.alert(
        marker.position,
        "Marker Position",
        "Done"
    );
});

But this when the popup comes the title is there, but the body text won't. What am I doing wrong?

A: I made it to work by converting the position to a String using .toString(), like this:
google.maps.event.addListener(marker, "click", function() {
    var location = marker.position;

    navigator.notification.alert(
        location.toString(),
        "Marker Position",
        "Done"
    );
});


text:
Q: Get value from cell containing array formula I have XSSFWorkbook and I've put array formulas in two column and I want to copy the values from these columns and paste onto other columns.
Formula looks like this:
{=IFERROR(INDEX(Sheet2!$A$2:$C$13,MATCH(1,(Sheet2!$A$2:$A$13=$A2)*(Sheet2!$C$2:$C$13=$D2),0),2),"FAIL")}

I have placed the formula (by running a loop on multiple cells) like this (sheet is XSSFSheet):
String formula = "AboveFormulaWithIterativeCell"  // (without {} and =)
String range = "XFC" + i;  // i is iterative row number
sheet.setArrayFormula(formula, CellRangeAddress.valueOf(range));

And then evaluated the formulas like this (wb is XSSFWorkbook):
XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);

Everything is working fine till this point. Formulas are displaying valid result.
Now if I run a loop on these cells and read the value like this (c is Cell):
String cellValue = c.getStringCellValue();

It always returning "FAIL", like it is returning the result after evaluating the formula as non-array formula.
So I've tried same thing with this formula:
{=IF(TRUE,TRUE,FALSE)}

And surprisingly it is returning me TRUE.
So, my question is how this formula is returning correct result and not my main formula.

A: So Apache Poi is still not supporting the manipulating table formulas (Array formulas).

Not yet supported   Manipulating table formulas (In Excel, formulas
  that look like "{=...}" as opposed to "=...")

See here for more details.
So I had to convert my array formula to non-array formula.
Note:
You can still use array formulas, if you just want to display the result.
But you can not get the value from cell which contains array formula.


text:
Q: Evaluate a formula stored in a cell Is it possible to store an expression in a cell and then refer to it/evaluate it within other cells?
I've found myself repeatedly using complex expressions in cell formulas, e.g., the sub-expression OFFSET ( $A$2, 0, 0, ROW() -1,  1 ) to refer to a cell in a row and all rows above it is nested within many other expressions.  As the expressions in cells get lengthier and more complex, it becomes harder to correctly write and debug them.  I'd like to put subexpressions in their own cells and then evaluate them in the main cells, to make things easier to read (like macros in C).
Is this possible?

A: You can get a sort of macro facility working. Try this:
Insert a separate sheet, make the table name unique to the spreadsheet (I use "Macros"), and ensure the table has one header row and one header column. Then label the column A header "Name" and column B header "macro". This sets you up with a shorthand, self-documenting naming system. To add a macro, pick a name for it, put the name in column A and the code in column B and then call it. If your table, row, and column names are set up properly, then $macro $myMacroName will do it.
Example: you have three checkboxes in known locations (say $A$1, $A$2, and $A$3) and you need to repeatedly check to see if any one checkbox is checked and then perform specific code different for each checkbox. The following in columns A and B of any row in your Macros table will accomplish the goal.
    anyBoxChecked  =IFERROR(CHOOSE(MATCH(TRUE,$A$1:$A$3,0),1,2,3),0)
    runCheckbox    =INDIRECT("$macro $runCheckbox"&$macro $anyBoxChecked)
    runCheckbox0   ="ERROR"
    runCheckbox1   =specific code for checkbox $A$1
    runCheckbox2   =specific code for checkbox $A$2
    runCheckbox3   =specific code for checkbox $A$3

Note the macro statement must always be row and column preserved (i.e. with $s).
This is a complex example (I kind of went to town on it) with macros including macros and indirect macro calls.
But by using $macro $anyBoxChecked<>0 you have a boolean representing if any of the three boxes is checked and by using $macro $runCheckbox you can run checkbox specific code automatically and get an error message if none of the boxes is checked.
Now the bad news: these macros do not accept any parameters and you cannot use any function that is location dependent. So the example you asked for help on, OFFSET($A$2,0,0,ROW()-1,1), can't be one of these macros because ROW() will return the row number of the macro, not the row number of the cell where you called the macro from.
But take heart; I was in exactly the predicament that you were in and using this system in conjunction with some judicious code analysis allowed me to reduce my code footprint substantially and document the remaining code a lot better. It also seems to improve performance.
Another note: you can have the macro rows in any order and add, delete, or move them around as much as you like. Numbers automagically just takes care of the row changes so you don't have to change any macro calls.
Have fun!
(by the way, I am running Numbers 6.0 (6194) on Mojave 10.14.4.


text:
Q: Meaning of *(volatile unsigned int *) 0x00 = 0x00; What is the meaning of the following line of code?
*(volatile unsigned int *) 0x00 = 0x00;

It is used in Assert definition:
void Assert()
{
    // (some other code above)

    *(volatile unsigned int *) 0x00 = 0x00;

    return;
}

A: I can guess it is trying to cause the program to crash with a segmentation fault or something similar.
Whoever wrote the code was thinking "I hope the compiler does not optimize this crash away, so let's put a volatile in front of the pointer dereference".
But all the code is doing is causing undefined behavior that is not guaranteed to crash.
An std::terminate() is a much better option if you want your program to terminate then that UB Assert()
Also note that an assert should be given a condition, and then if the condition is false the assert should trigger some failure code.  Ot is not meant to be an "exit this program" function. See linked comment

A: Cast 0x00 to pointer to volatile unsigned int and then dereference it with operator* and write to that address 0x00. Which is undefined behavior and on most systems will cause crash.


text:
Q: Estimate normal distribution variance from two observations A simple question (not a homework question, although it seems to be):
Assume that $X \sim N(\mu, \sigma^2)$, $\mu$ is known (say $\mu = 150$) and $\sigma$ is not known. If $x_1$, $x_2$ are 2 observations of $X$ what can be said about the distribution of the standard deviation $\sigma$?

A: If you have a normal population where $\mu$ is known and $\sigma^2$ is not, an unbiased estimate of $\sigma^2$ based on a random sample $X_1, X_2, \dots X_n$ of size $n$ from the population is
$$ V = \frac 1n \sum_{i=1}^n(X_i - \mu)^2.$$
Furthermore, $nV/\sigma^2 \sim \mathsf{Chisq}(\nu = n),$ so that
$$P(L \le nV/\sigma^2 \le U) = P(nV/U \le \sigma^2 \le nV/L) = 0.95,$$ for values $L$ and $U,$
which cut probability .025 from the lower and upper tails of $\mathsf{Chisq}(\nu = n),$
respectively. Thus a 95% confidence interval for $\sigma^2$ is of the form
$(nV/U, nV/L).$ A 95% confidence interval for $\sigma$ can be found by taking square roots of the endpoints of the CI for $\sigma^2.$
Example: Take a sample of size $n=2$ from $\mathsf{Norm}(\mu=50, \sigma=3),$ assuming
$\mu = 50$ to be known, and using the sample to estimate $\sigma^2,$ and thence to estimate $\sigma.$ (Computations in R.)
set.seed(1234)
x = rnorm(2, 50, 3)
v = (1/2)*sum((x-50)^2);  v
[1] 6.902886              # estimate V of 9

With only $n=2$ observations, we cannot expect a precise estimate of $\sigma^2 = 3^2 =9.$
A 95% CI for $\sigma^2$ is $(1.871, 272.65).$
2*v/qchisq(c(.975,.025), 2)
[1]   1.871269 272.649441

Taking square roots of endpoints, we get a 95% CI for $\sigma.$
sqrt(2*v/qchisq(c(.975,.025), 2))
[1]  1.367943 16.512100    # CI contains the population SD = 3.

Notes: (1) All of the above is somewhat different from the situation where $\mu$ is
also unknown and estimated by $\bar X.$ This is the situation in your Wikipedia link.
(2) We have $E(V) = \sigma^2,$ so the estimator $V$ is unbiased for $\sigma^2,$ but
$E(\sqrt{V}) \ne \sigma,$ exactly.
One can follow a procedure similar to the
one in your link to find an unbiased estimator $c\sqrt{V}$ with $E(c\sqrt{V}) = \sigma.$
Because you are interested in $n = 2$ it may be of interest to use simulation to approximate $c = \sqrt{\pi/2}$ in that particular case. Below we obtain $c\approx 1.253.$ (Perhaps see Rayleigh distribution.)
set.seed(2020)
v = replicate(10^6, (1/2)*sum(rnorm(2))^2)
1/mean(sqrt(v))
[1] 1.252772     # unbiasing constant

set.seed(612)
v = replicate(10^6, (1/2)*sum(rnorm(2, 50, 3)-50)^2)
mean(1.253*sqrt(v))
[1] 2.997461     # aprx E(SD) = 3

For an analytic derivation of $c$ you can use the integral $\int_0^\infty wf_W(w)\, dw,$ involving the density function of $W=\sqrt{V}.$ Except for the constant, the integrand is a gamma density. Factor out a constant so that the integrand is a gamma density (hence the integral is $1.)$ The constant you factored out is the answer.


text:
Q: Re-format excel data using groupby and add blank lines to dataframe in python I have a long excel file of 60 minute count rainfall for the course of a year. I am looking to read-in the excel file, aggregate the rainfall values for total daily rainfall (group.by works well), and then put these values into a new dataframe where each day of the year is a separate line with 0 if there was no rain that day and the Value of total daily rainfall if it did rain. I've outlined the steps I'd take and my attempt at the code below. I am open to other suggestions if what I've attempted to code is crap. The first lines of the excel file look like this:
60 Minute Counts, []
Time Stamp  Latitude    Longitude   Value ()
Dec 27 2015 01:30:00 AM 0.297   36.900  0.25
Dec 25 2015 01:00:00 PM 0.297   36.900  0.51
Dec 25 2015 10:30:00 AM 0.297   36.900  0.25
Dec 25 2015 07:30:00 AM 0.297   36.900  0.25
Dec 25 2015 05:00:00 AM 0.297   36.900  0.25
Dec 25 2015 04:30:00 AM 0.297   36.900  0.25
Dec 17 2015 02:30:00 AM 0.297   36.900  0.25
Dec 16 2015 02:30:00 PM 0.297   36.900  0.25
Dec 16 2015 02:00:00 PM 0.297   36.900  0.76
Dec 16 2015 12:30:00 PM 0.297   36.900  0.25
Dec 16 2015 12:00:00 PM 0.297   36.900  0.76
Dec 16 2015 11:30:00 AM 0.297   36.900  5.08
Dec 16 2015 11:00:00 AM 0.297   36.900  0.51
Dec 15 2015 03:30:00 PM 0.297   36.900  0.25

I then need to read in the excel file, which I've played around with:
from openpyxl import load_workbook

wb = load_workbook(filename = 'filename.xlsx')
sheet_ranges = wb['60 minute counts']

But I'm not sure how to read in lines 3+ for the actual values.
After defining the dataframe df0 for the Time Stamp and Value () columns, then I need to convert the Time Stamp into a format like YYYY-MM-DD, which could use the code:
import pandas as pd
df0["time"] = pd.to_datetime(df0["time"])
df0["day"] = df0['time'].map(lambda x: x.day)
df0["month"] = df0['time'].map(lambda x: x.month)
df0["year"] = df0['time'].map(lambda x: x.year)

Then I need to combine the 60 minute count rainfall to be total daily rainfall, by:
df1 = df0.groupby(['Value ()', 'day', 'month', 'year'], as_index=False).sum()

And ultimately I need to make the dataframe that has a row for each day of the year and then the total daily rainfall. It would look like this:
Date    Value
2015-12-31  0
2015-12-30  0
2015-12-29  0
2015-12-28  0
2015-12-27  0.25
2015-12-26  0
2015-12-25  1.52
2015-12-24  0
2015-12-23  0
2015-12-22  0
2015-12-21  0
2015-12-20  0
2015-12-19  0
2015-12-18  0
2015-12-17  0.25
2015-12-16  7.62

... and so on
Let me know if it's helpful to post the entire file and I can add a dropbox link.

A: It seems you need resample:
df0.index = pd.to_datetime(df0["Time Stamp"])

df1 = df0.resample('D')['Value ()'].sum().fillna(0).reset_index()
print (df1)
   Time Stamp  Value ()
0  2015-12-15      0.25
1  2015-12-16      7.61
2  2015-12-17      0.25
3  2015-12-18      0.00
4  2015-12-19      0.00
5  2015-12-20      0.00
6  2015-12-21      0.00
7  2015-12-22      0.00
8  2015-12-23      0.00
9  2015-12-24      0.00
10 2015-12-25      1.51
11 2015-12-26      0.00
12 2015-12-27      0.25

Or groupby with Grouper:
df0.index = pd.to_datetime(df0["Time Stamp"])

df1 = df0.groupby(pd.Grouper(freq='D'))['Value ()'].sum().fillna(0).reset_index()
print (df1)
   Time Stamp  Value ()
0  2015-12-15      0.25
1  2015-12-16      7.61
2  2015-12-17      0.25
3  2015-12-18      0.00
4  2015-12-19      0.00
5  2015-12-20      0.00
6  2015-12-21      0.00
7  2015-12-22      0.00
8  2015-12-23      0.00
9  2015-12-24      0.00
10 2015-12-25      1.51
11 2015-12-26      0.00
12 2015-12-27      0.25

And if necessary add sort_index:
df1 = df0.resample('D')['Value ()'].sum().sort_index(ascending=False).fillna(0).reset_index()
print (df1)
   Time Stamp  Value ()
0  2015-12-27      0.25
1  2015-12-26      0.00
2  2015-12-25      1.51
3  2015-12-24      0.00
4  2015-12-23      0.00
5  2015-12-22      0.00
6  2015-12-21      0.00
7  2015-12-20      0.00
8  2015-12-19      0.00
9  2015-12-18      0.00
10 2015-12-17      0.25
11 2015-12-16      7.61
12 2015-12-15      0.25

df1 = df0.groupby(pd.Grouper(freq='D'))['Value ()'].sum()
         .sort_index(ascending=False).fillna(0).reset_index()
print (df1)
   Time Stamp  Value ()
0  2015-12-27      0.25
1  2015-12-26      0.00
2  2015-12-25      1.51
3  2015-12-24      0.00
4  2015-12-23      0.00
5  2015-12-22      0.00
6  2015-12-21      0.00
7  2015-12-20      0.00
8  2015-12-19      0.00
9  2015-12-18      0.00
10 2015-12-17      0.25
11 2015-12-16      7.61
12 2015-12-15      0.25


text:
Q: What is a way to incorporate XML attributes in an array with xpath-like accessor syntax? My favorite XML feature by far is the attribute syntax because it can let you do things like:
<order>
   <sku o="1234">
       <warehouse o="PDX">
           <qty>2</qty>
       </warehouse>
       <warehouse o="ATX">
           <qty>4</qty>
       </warehouse>
   </sku>
   <sku o="2345">
       <warehouse o="PHX">
           <qty>5</qty>
       </warehouse>
       <warehouse o="LAX">
           <qty>5</qty>
       </warehouse>
   </sku>
</order>

Then you can do this nice xpath syntax to get right at a specific quantity without doing any annoying for-each loops:
//sku[@o='1234']/warehouse[@o='ATX']/qty
But I've been trying to map this exact type of syntax without using xpath, for example, just using PHP arrays or such. No luck.
Problem is, this breaks down when you try to have more than two keys (i.e. more than the ordinal key and semantic key), because then in a foreach loop you'll iterated through the item an extra time for each extra key, unless you implement some really annoying logic.
Does anyone have an idea how you could do this in PHP without using xpath or foreach loops, but somehow do it with syntax like:
$order['sku'=>'1234']['warehouse'=>'PDX']['qty']
??
The closest I could figure is something like this, although this feels very hack-ish:
function addToHashMap($array, $key, $value) {
    array_unshift($array,$value);
    $link = &$array[0];
    $array[$key] = &$link;
    return $array;
}

$order = array();
$order['skus'] = array();
$skus = &$order['skus'];

print_r($order);
print_r($skus);

$skus = addToHashMap($skus,'1234',array('qty'=>'1'));

$skus['1234']['qty'] += 1;

print_r($order);

foreach($skus as $key => $item) {
   if($key < count($skus)/2) continue;
   echo("qty: ".$item['qty']);
}

Which returns:
Array
(
    [skus] => Array
        (
        )

)
Array
(
)
Array
(
    [skus] => Array
        (
            [0] => Array
                (
                    [qty] => 2
                )

            [1234] => Array
                (
                    [qty] => 2
                )

        )

)
qty: 2


text:
Q: HTTP Status 404?
AppConfig
package com.example.configuration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example.SpringTest")
public class AppConfig {

    }

AppConfigInitialisation.java ##
    package com.example.configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class AppConfigInitialization  extends AbstractAnnotationConfigDispatcherServletInitializer {
     @Override
        protected Class<?>[] getRootConfigClasses() {
            return new Class[] { AppConfig.class };
        }

        @Override
        protected Class<?>[] getServletConfigClasses() {
            return null;
        }

        @Override
        protected String[] getServletMappings() {
            return new String[] { "/*" };
        }
}

User.java
package com.example.controller;
import com.example.model.*;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
     @RequestMapping("/")
        public String welcome() {//Welcome page, non-rest
            return "Welcome to RestTemplate Example.";
        }

        @RequestMapping("/hello/{player}")
        public User user(@PathVariable String player) {//REST Endpoint.

            User msg = new User(player, "Hello " + player);
            return msg;

        }

}

UserController.java
    package com.example.controller;
import com.example.model.*;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
     @RequestMapping("/")
        public String welcome() {//Welcome page, non-rest
            return "Welcome to RestTemplate Example.";
        }

        @RequestMapping("/hello/{player}")
        public User user(@PathVariable String player) {//REST Endpoint.

            User msg = new User(player, "Hello " + player);
            return msg;

        }

}

pom.xml
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example</groupId>
  <artifactId>SpringTest</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>SpringTest</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <springframework.version>4.3.0.RELEASE</springframework.version>
        <jackson.library>2.7.5</jackson.library>
  </properties>

  <dependencies>

     <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.library}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>${jackson.library}</version>
        </dependency>
  </dependencies>
</project>

I getting "description The requested resource is not available.". i am trying to run it on tomcat v8.0 server. Even when i download the project spring projects from the sites and import them as a maven project , i get the same issue. Help me out

A: you may need to add @RequestMapping("/") at the type level ( on top of UserController).

A: You are giving the component scan base package as "com.example.SpringTest". But the UserController is in com.example.controller


text:
Q: Copy data into postgres from Redshift using Node.js Is there an efficient way to copy a table from redshift to postgres using nodejs, couldn't find any concrete examples

A: There does not seem to be any utility pre-written. the process that you must adopt (set up) for anything more than just a few rows is:

*

*Push data to S3

*Use AWS Copy command (using SDK) to copy from S3 to Redshift

*Transform data in Redshift (optional)


text:
Q: Dynamic progress bar on form submit in extjs 3.3 I am submiting the form from in the extjs 3.3. the back end process will run nearly half an hour after form submit. I need to display the progress information to the user. The message will be return from server. I need to display the server message in the progress bar until the process completed.
My current code
Ext.getCmp('columnDetailInfoId').getForm().submit({
    url     : 'callAPIs',
    timeout : 2000000,
    waitMsg : 'In-Progress...',
    params  : {selectedAppRowNo: Ext.encode(selectedAppRowNo)},

    success : function(){
        Ext.MessageBox.show({
            title  : 'Info',
            msg    : 'process completed.',
            buttons: Ext.MessageBox.OK,
            icon   : Ext.MessageBox.INFO,
            animEl : 'mb9',
            width  : 400
        });
    },

    failure : function(form,action){
        var message = action.result.message;

        Ext.MessageBox.show({
            title  : 'Error',
            msg    : 'process Failed. Error Message:'+message,
            buttons: Ext.MessageBox.OK,
            icon   : Ext.MessageBox.ERROR,
            animEl : 'mb9',
            width  : 500
        });
     }
});

I need to display the progress bar instead of wait message. Share your idea or code to implement this scenario.


text:
Q: Dropdown menu causing text to look ugly on bootstrap navbar I would like to know why my text on Bootstrap's navbar turns very thin when ever I click on a dropdown menu inside the navbar, then goes back to normal after i close the menu (click elsewhere). If you click on Stackoverflow's message box on the top navbar of this site, you will notice that the text stays the same, that's what I'm looking to do in my site. I've seen many sites that have this issue so I know it's nothing new but I can't figure it out or have tried searching but couldn't find anything that could help me.
This is a good example of a site that has the same problem I have:
https://bootsnipp.com
Notice that when you click on any submenu how all the text on that bar turns very thin. It only happens on dropdown menus, if you click on the search bar it stays the same.


text:
Q: Image zoom not working in slick slider I'm using slick slider in my page and I need to zoom image on hovering image. So for this Im using a zoom jquery plugin and it's working in normal image but not working in slick slider. here is my code

Krishna is always my source of inspiration.

js
and I added "lightzoom.js" this
  $(document).ready(function () {
     $('img.light-zoom').lightzoom({
        zoomPower   : 2,    //Default
        glassSize   : 180,  //Default
    });
});

A: This worked for me

.slick-slider{
    touch-action: auto!important;
}

A: I found an answer here: https://github.com/kenwheeler/slick/issues/2505
It works with this "Remove these lines in slick.scss:
-ms-touch-action: pan-y; touch-action: pan-y;"
I've removed form slick.css

A: You can override the slick slider (v. 1.4) with the css rule .slick-slider { touch-action: inherit; }