text:
Q: Spring Autowired object is null I have a problem with autowiring an object, it keeps getting null. I have a BookManager which I have defined in my beans. This BookManager I need to be autowired to all objects that extends my AbstractBook, but I keep getting null of the autowired object. I have googled alot and it seems that many people are making some mistakes regarding autowire but I can't find a solution for my setup. This is how it looks:
My beans:
beans = {
    bookManager BookManager
}

BookManager.groovy
class BookManager {

    void addText(text){
        println text
    }
}

AbstractBook.groovy
abstract class AbstractBook extends DefaultActor {

    @Autowired
    BookManager bookManager

    protected final void act(){
        loop{
            react{ message ->
                println message
            }
        }
    }

    abstract void method1()
}

Book1.groovy
@Component
class Book1 extends AbstractBook {

    @Override
    void method1(){
        bookManager.addText("book 1 text")
    }
}

A solution that would work is to define book1 in my beans but I'm not able to do that because there will be alot of books generated. So I was hoping it would work with adding the annotation @Component for each book but it does not work.
Does anyone know how I can make bookManager available for all books?


text:
Q: hibernate one to one on foreign key I have a main table that is D1 which has a unique id of d1Id. d1Id uniquely identifies the D1 records and is also a primary key on the table. I have table 2 which is D2 which has a d2seq as a primary key but D2 also has d1Id which is unique which has a foreign key constraint (I think) on D1. But I know for sure it's unique and the id's are the same. I am trying to retrieve d2 values when i make the D1 call using hibernate and i'm unable to get the right hbm for it as i'm getting compile time errors.
The bottom line of the issue is, I need to establish a one to one relationship between 2 tables where in the second table, the id which joins is not the primary key of the table. All the examples i've seen searching google have the case where the ID on the second table is also the primary key of the second table. Let me show you the HBM file I have right now.
<hibernate-mapping default-lazy="true"
package="com.xxx.xx.customer.dto">
<class name="D1" table="D1" dynamic-update="true">
    <id name="dString" column="DID" type="java.lang.String"
        unsaved-value="null" length="9">
        <generator class="assigned"/>
    </id>
...

<one-to-one name="d2" class="com.xxx.xx.customer.dto.D2" >
        <!-- column name="d1Id" /-->
    </one-to-one>

In my second hbm for D2, i'm stuck here
<hibernate-mapping default-lazy="true" package="com.xxx.xx.customer.dto">
<class name="D2" table="D2" dynamic-update="true">
    <id name="id" column="D2ID" type="integer">
        <generator class="native">
            <param name="sequence">D2SEQ</param>
        </generator>
    </id>

<id name="d1id" column="D1ID" type="java.lang.String"
        unsaved-value="null" length="9">
        <generator class="assigned"/>
    </id>

I obviously can't use the second id field for d1id here because 1> it's not a primary key and 2> i've already used it before. So how should my HBM files be for this operation?
Also once I have my HBMs in place, I would like to get D2 information while i query D1 through the DTOs. How can I do that?

A: Why can't you use @ManyToOne relationship? Often it provides more flexibility than @OneToOne

redpajama_set_name: RedPajamaStackExchange


text:
Q: Json result only returning 1 row For some reason my function only spits out 1 row from my json data.  How can I make this loop? I'm sure I'm missing something simple!
JSON
[
    {"id":"3","job_title":"Aircraft Technician","job_description":"","job_qualifications":null,"created_at":"2014-06-02 18:00:32","updated_at":"2014-06-02 18:00:32","industries":"","division_id":"3","industry_job_id":"3"},
    {"id":"4","job_title":"Aircraft Technician 2","job_description":"","job_qualifications":null,"created_at":"2014-06-02 18:18:57","updated_at":"2014-06-02 18:18:57","industries":"","division_id":"3","industry_job_id":"4"}
]

JQUERY
function getIndustryJobs(data_id, data_option){
    // alert("data-id:"+data_id+", data-option:"+data_option);
    $.getJSON("{{{ Config::get('app.url') }}}/data/json/"+data_id, function(data) {
        $('#roleList').empty();
        $.each(data, function(key, val){
            $('#roleList').append('<option value=' + val.id + '>' + val.job_title + '</option>');
            $('#roleList').listview('refresh');
        });

    });
}

HTML
  <select id="roleList" name="roleList" multiple="multiple"></select>

A: Quite likely, it is because you're requesting one row, as I can guess from the URL: .../data/json/"+data_id.  Which means if you request for all the rows, your code should work fine. The rest of your code looks good, except for the refresh which should be outside the loop as @AnoopJoshi correctly said:
function getIndustryJobs(data_option){
    $.getJSON("{{{ Config::get('app.url') }}}/data/json", function(data) {
        $('#roleList').empty();
        $.each(data, function(key, val){
            $('#roleList').append('<option value=' + val.id + '>' + val.job_title + '</option>');
        });
        $('#roleList').listview('refresh');

    });
}

A: Please try this ,it's work, I tired
    <script>
        $(document).ready(function () {
            var data = JSON.parse('[{"id":"3","job_title":"Aircraft Technician","job_description":"","job_qualifications":null,"created_at":"2014-06-02 18:00:32","updated_at":"2014-06-02 18:00:32","industries":"","division_id":"3","industry_job_id":"3"},{"id":"4","job_title":"Aircraft Technician 2","job_description":"","job_qualifications":null,"created_at":"2014-06-02 18:18:57","updated_at":"2014-06-02 18:18:57","industries":"","division_id":"3","industry_job_id":"4"}]');
            $(data).each(function () {
                $('#roleList').append('<option>' + this.id + this.job_title + '</option>');
            });
        });
    </script>


text:
Q: Why is str_replace() only replacing one instance of a character in a string? I have a large string variable that is assigned from a database column of type "Text" with Collation latin_swedish_ci.
Because it is in ASCII, I need to replace all non UTF-8 characters before I can put variable into my PDF generation script.
As we all know, the standards used by PDF are evil. If I use plain ASCII input it will go insane and cause a rip in space-time.
So in order to prevent anymore damage to our universe, I need help figuring out why this str_replace() function is only replacing one of a character type and ignoring any  repeats of this character
Here is my code:
$tc = str_replace (array("\n", "£", "&"), array("<br/>", "£", "&"), $tc);

Input:
Terms & Conditions: Mandatory charge of £10 for cancellations.
VAT E&EO

Output:
Terms & Conditions: Mandatory charge of £10 for cancellations.
VAT E&EO

As you can see in the output on the second line the str_replace() does not change the ampersand character.
I wonder if this is because its over two lines or something like that.
So any idea how to get the function to work as I want it to, otherwise well your going to wake up with many Micro Blackholes vanishing your bowl of cereal tomorrow.

A: It looks like what you are trying to achieve could be done using these 2 functions:
nl2br(htmlentities($tc));

The benefit being that if your $tc variables gets any more HTML entities in the future, you won't have to fiddle with your str_replace().


text:
Q: Cannot set style of string variable Method:
getTitleText(){
      let mainTitle = "";
       let getTitle = this.titleText;
       let countGetTitle = getTitle.split(" ").length;
      if(countGetTitle > 4){
          mainTitle = getTitle.replace(/(\S+\s*){1,5}/, "$&\n");
          console.log(typeof mainTitle)
          mainTitle.style.fontSize = "30px"
        }else{
          mainTitle.style.fontSize = "40px"
        }
        return mainTitle;
    },

error I found
[Vue warn]: Error in render: "TypeError: Cannot set property 'fontSize' of undefined"
found in

A: You're conflating String with HTMLElement. A String has no style property, so .style would be undefined, leading to the error you observed for fontSize. But it looks like you actually want to specify the font size for the HTML element that would contain that string.
One way to solve this is to return an object with one property for the title text, and another for the font size:
export default {
  computed: {
    getTitleText() {
      let mainTitle = "";
      let fontSize = "";
      let getTitle = this.titleText;
      let countGetTitle = getTitle.split(" ").length;
      if(countGetTitle > 4) {
        mainTitle = getTitle.replace(/(\S+\s*){1,5}/, "$&\n");
        fontSize = "30px"
      } else {
        fontSize = "40px"
      }
      return {
        text: mainTitle,
        fontSize,
      }
    },
  }
}

Then bind the result in your template:
<span :style="{ fontSize: getTitleText.fontSize }">{{ getTitleText.text }}</span>

demo


text:
Q: Using User Parameter Pre Processor for ${__UUID()} function in Jmeter doesn't work while executing the jmx script from Maven framework I am calling the ${__UUID()} function in my script to generate UUID, using User Parameter pre processor.

This ${__UUID()} works fine, and generates UUID when I execute the jmx script from Jmeter gui or Jmeter non gui/cmd.
Jmeter Log:
2020-04-14 15:24:44,173 INFO o.a.j.u.BeanShellTestElement: UUID=======>3c8114da-1657-4e99-85bd-49081be0172b
But, whenever I am trying to execute this same jmx script from my JMeter-Maven framework, it only fails in the request using this function ${__UUID()}.
Jmeter Log:
2020-04-14 15:03:05,695 INFO o.a.j.u.BeanShellTestElement: UUID=======>${__UUID()}
According to my understanding, based on the logs, its not able to generated the UUID using the function ${__UUID()}, while executing the script from JMeter-Maven framework.
Error Generated in HTML Report for the request using function ${__UUID()}:
Non HTTP response code: java.net.URISyntaxException/Non HTTP response message: Illegal character in query at index 43
Here is my pom.xml file:
<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>JMeterMavenImpletation</groupId>
<artifactId>JMeterMaven</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

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

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.apache.jmeter/ApacheJMeter_core -->
    <dependency>
        <groupId>org.apache.jmeter</groupId>
        <artifactId>ApacheJMeter_core</artifactId>
        <version>5.1.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.jmeter/ApacheJMeter_http -->
    <dependency>
        <groupId>org.apache.jmeter</groupId>
        <artifactId>ApacheJMeter_http</artifactId>
        <version>5.1.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.jmeter/ApacheJMeter_components -->
    <dependency>
        <groupId>org.apache.jmeter</groupId>
        <artifactId>ApacheJMeter_components</artifactId>
        <version>5.1.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.jmeter/ApacheJMeter_functions -->
    <dependency>
        <groupId>org.apache.jmeter</groupId>
        <artifactId>ApacheJMeter_functions</artifactId>
        <version>5.1.1</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.lazerycode.jmeter/jmeter-maven-plugin -->
    <dependency>
        <groupId>com.lazerycode.jmeter</groupId>
        <artifactId>jmeter-maven-plugin</artifactId>
        <version>2.9.0</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>com.lazerycode.jmeter</groupId>
            <artifactId>jmeter-maven-plugin</artifactId>
            <version>2.9.0</version>
            <executions>
                <!-- This goal will run the load test and generate the HTML report -->
                <execution>
                    <id>jmeter-tests</id>
                    <phase>verify</phase>
                    <goals>
                        <goal>jmeter</goal>
                    </goals>
                </execution>
                <!-- This goal runs some verification on error rate and fails the build -->
                <!-- <execution> <id>check-results</id> <phase>verify</phase> <goals>
                    <goal>results</goal> </goals> </execution> -->
            </executions>
            <configuration>
                <!-- JVM Metrics -->
                <jMeterProcessJVMSettings>
                    <arguments>
                        <argument>-XX:MaxMetaspaceSize=256m</argument>
                        <argument>-Xmx1024m</argument>
                        <argument>-Xms1024m</argument>
                        <argument>-Xprof</argument>
                        <argument>-Xfuture</argument>
                    </arguments>
                </jMeterProcessJVMSettings>
                <!-- Test Script Properties -->
                <propertiesUser>
                    <users>${users}</users>
                    <rampup>${rampup}</rampup>
                    <loop>${loop}</loop>
                </propertiesUser>
                <!-- Fetching Test Script -->
                <testFilesIncluded>
                    <jMeterTestFile>${jMeterScriptFile}</jMeterTestFile>
                </testFilesIncluded>
                <!-- Time stamp -->
                <testResultsTimestamp>true</testResultsTimestamp>
                <!-- HTML Reports -->
                <generateReports>true</generateReports>
            </configuration>
        </plugin>
        <plugin>
            <!-- https://mvnrepository.com/artifact/de.codecentric/jmeter-graph-maven-plugin -->
            <groupId>de.codecentric</groupId>
            <artifactId>jmeter-graph-maven-plugin</artifactId>
            <version>0.1.0</version>
            <configuration>
                <inputFile>${project.build.directory}/jmeter/results/20190808-Scripts_SampleScript.jtl</inputFile>
                <!-- Custom Graphs -->
                <graphs>
                    <graph>
                        <pluginType>ResponseTimesOverTime</pluginType>
                        <width>800</width>
                        <height>600</height>
                        <outputFile>${project.build.directory}/jmeter/results/ActiveThreadsOverTime.png</outputFile>
                    </graph>
                    <graph>
                        <pluginType>HitsPerSecond</pluginType>
                        <width>800</width>
                        <height>600</height>
                        <outputFile>${project.build.directory}/jmeter/results/BytesThroughputOverTime.png</outputFile>
                    </graph>
                    <graph>
                        <pluginType>TransactionsPerSecond</pluginType>
                        <width>800</width>
                        <height>600</height>
                        <outputFile>${project.build.directory}/jmeter/results/ResponseCodesPerSecond.png</outputFile>
                    </graph>
                    <graph>
                        <pluginType>TransactionsPerSecond</pluginType>
                        <width>800</width>
                        <height>600</height>
                        <outputFile>${project.build.directory}/jmeter/results/ResponseTimesDistribution.png</outputFile>
                    </graph>
                    <graph>
                        <pluginType>TransactionsPerSecond</pluginType>
                        <width>800</width>
                        <height>600</height>
                        <outputFile>${project.build.directory}/jmeter/results/ResponseTimesOverTime.png</outputFile>
                    </graph>
                    <graph>
                        <pluginType>TransactionsPerSecond</pluginType>
                        <width>800</width>
                        <height>600</height>
                        <outputFile>${project.build.directory}/jmeter/results/ResponseTimesPercentiles.png</outputFile>
                    </graph>
                    <graph>
                        <pluginType>TransactionsPerSecond</pluginType>
                        <width>800</width>
                        <height>600</height>
                        <outputFile>${project.build.directory}/jmeter/results/ThroughputVsThreads.png</outputFile>
                    </graph>
                    <graph>
                        <pluginType>TransactionsPerSecond</pluginType>
                        <width>800</width>
                        <height>600</height>
                        <outputFile>${project.build.directory}/jmeter/results/ResponseTimesVSThreads.png</outputFile>
                    </graph>
                    <graph>
                        <pluginType>TransactionsPerSecond</pluginType>
                        <width>800</width>
                        <height>600</height>
                        <outputFile>${project.build.directory}/jmeter/results/TransactionsPerSecond.png</outputFile>
                    </graph>
                </graphs>
            </configuration>
        </plugin>
    </plugins>
</build>

I would really appreciate if someone may aid me to resolve it !

A: I cannot reproduce your issue however I can see several other problems with your test:

*

*The correct syntax for __UUID() function would be:
${__UUID}

It's better to use Functions Helper Dialog if you're uncertain regarding the proper syntax, check out Apache JMeter Functions - An Introduction article for more details.

*This <dependencies> block is not necessary, JMeter Maven plugin will download the relevant version of JMeter itself

*According to JMeter Best Practices you should always be using the latest version of JMeter so consider changing the JMeter plugins version to 3.0.0

*Since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for scripting. Moreover, you should not be inlining JMeter functions or variables into the script, you should be using vars.get("sample_id") instead where vars stands for JMeterVariables class instance


text:
Q: Getting output from Google script to a html page Currently I am inserting data into my Google Script like a database and I want to now pull that information from the sheet to my HTML page.
For that I have tried to create a google sheet script, that gives out a result of a cell, that i want to get passed to my website.
this script returns the value 1
But how can i get that result from the script, to my website?
I've tried using JQuery with no success [below]
var urlToGoogleSheetCells = "https://script.google.com/macros/s/AKfycby5RzvUWSEOjerJpouxN72wpsgpsF8IWQo2AvjZUdRPcqskz28/exec";

    $http.get(urlToGoogleSheetCells)

  ....

*

*Thanks in advance :)

A: Use the Google Apps Script Execution API.

The Apps Script Execution API is a REST interface that lets a third-party application call a function defined in an Apps Script project and receive a response. This API lets you expose the full utility of Apps Script to any application, including Android and iOS apps.


text:
Q: Approaching a large machine learning problem I have massively rewritten my original question to further explain the problem.  It involves a regression problem on a dataset of about 2.5 million records.  My development has been done entirely in R.
The Problem
Description
The problem involves predicting costs of highway construction contracts.  Contracts are let in large groups statewide each year (called "lettings"), maybe once every other or third month.  Each contract is described by a series of payitems, which specify the materials, labor, and equipment required to do the work.  Each payitem is categorized by a unique code of seven digits.  The codes give a clue to payitem similarity.  For example, drainage-related items are under codes beginning with 542, and asphalt-related items begin with 406.  "Similar" payitems are typically similar in terms of the materials and equipment used.  The labor required to construct, however, may vary greatly, depending.
My goal is to predict a payitem unit price based on a history of bids going back 13 years.  Note that a bid occurs each time a contractor bids on a payitem in a contract.  Thus, if five contractors bid on a contract with 1,000 payitems, I can mine 5,000 individual bids from the data.  To date, I've mined nearly 2.5 million individual bids.
Target predictions should be consistently within 15% of the actual value.  Given that cost estimates are often inflated 10% - 15%, I felt this was a reasonable measure of success.
Predictors
To this point, the features I've selected for the problem are:

*

*Location (a regional descriptor)

*Month of letting

*Payitem quantity

*Payitem number

*Total contract value

*National Construction Cost Index (FHWA NHCCI)

*Union laborer prevailing wage for the month of the letting

*Relevant material and equipment cost indices

Obviously, material, labor, and equipment costs will drive the bid price, but there are other considerations I can't really model (noted below).
Based on my success thus far, I believe I've captured enough features to accurately model the data.  So, without identifying which contractor made which bid, there's not much more I can do in terms of useful predictors.
Preliminary Results
To this point, I've achieved around 90% success predicting the price of guardrail payitems (a data set of about 10,000 observations) and somewhat less with asphalt payitems (about 25,000 observations).  Other payitems, (like erosion control), are much harder to predict due partly to the nature of the work and materials, and the relative paucity of available data (~1,000 observations).  Thus far, I have had about 50% success.
What complicates accurate prediction varies greatly.  While I've managed to represent the costs of the payitems with a variety of relevant indices, there are myriad of other factors that can influence a particular bid, including distance the contractor and/or supplier is from the jobsite, potential "bidding wars" where contractors bid low on certain items to gain a competitive edge in bidding, or intentionally high bids because the contractor is not particularly well-suited for the work or suspects the designers did not adequately account for the scope of work.
The Solutions
Experience
Overall, one should expect strong linearity in the data, as quantity and price scale inversely.  However, there are price ranges where that assumption breaks down which may or may not be strongly related to the other features at my disposal (bids in urban vs. rural areas, seasonal price fluctuations, etc.)
My current solution has employed the following techniques:

*

*Scale and normalize all data (even category / binary values).

*Log transform features that show a strong non-uniform (but otherwise
non-Gaussian) distribution

*Remove the upper and lower 1% of outliers (validated by inspection of the data)

*Employ a chained ensemble of models
To elaborate on the 4th point, I initially tried a neural network and achieved 60%-70% success, but only after extensive optimization efforts.  After experimenting with other algorithms, I found I could get consistently higher (70% - 80%) with any one of a support vector machine, random forest, and gradient boosting machine.  Simple / geometric averages of these three models gave me another 3-7%, depending on how similar the model accuracies were.
Finally, if I took these machines and trained them again with the same hyperparameters, but appended the previous run's predictions to the original data features (creating a "chained" ensemble), I might see another 5% - 10% success increase.  Chaining an individual model in this fashion only resulted in over-training with loss on the validation set accuracy.
Next Steps
There is strong linearity in certain price ranges, and linear regression may perform quite well on some (or even most) of the data, but I have no easy way to split out the linear / non-linear segments without knowing the target price in advance.  Interestingly, (and perhaps it's intuitive), if I used linear regression as the second step in a "chained" model, (thus relying on predictions from previous non-linear models), linear regression fared much better, often performing almost as well as a non-linear model.
I've experimented with splitting the data using decision trees so I can segment it by its features.  They've proved helpful, but I don't yet have a good grasp of how effective it may be in reducing overall non-linearity.  Of course, if I could eliminate the non-linearity using decision trees and apply linear regression to the resulting datasets, I would certainly do that.
Looking at the non-linear solution I've developed, it may be over-complicated, but I don't know that it's necessarily a bad option.  To the point, I have discovered that the networks didn't need to be optimized that well to provide a similar level of success.  A poorer level of optimization only resulted in a 2% - 5% loss of success.  If there is a feasible solution here, it would have to involve finding the breakpoint where the overall accuracy depends more on the number of models in the ensemble than the degree of optimization applied to them.
These are the two primary solutions I see in approaching the problem as a whole.  What complicates implementing either of these is the volume of data (2.5 million records) and individual payitems (43,000+).  As suggested in the comments, using the payitem number as a feature may prevent similar payitems from benefiting from the patterns the model learns from other payitems.  This could prove problematic especially where some payitems are poorly represented, but are otherwise very similar to other, better represented items.
Again, I apologize for the length, but I hope it explains the problem more clearly.

A: Nice, exhaustive write-up! I want to propose an additional consideration or two. Most importantly, instead of building separate models for each payitem that you integrate the massively categorical nature of the payitems into a hierarchical modeling framework. This approach has several advantages: 1) by pooling the data, it would improve estimation for the sparsely populated payitems, 2) it would "shrink" the parameter estimates and their standard errors, and 3) would more appropriately account for the variability in the data versus building each model separately. Here's a paper that focuses on leveraging zip codes in a direct marketing modeling environment that describes a Bayesian approach to this:
http://www.people.hbs.edu/tsteenburgh/articles/Steenburgh_Ainslie_and_Engebretson_(winter_2003).pdf
But you aren't limited to a Bayesian approach. When this paper was written, hierarchical Bayesian frameworks offered significant advantages over the challenges traditional, closed-form or "frequentist" models faced in, e.g., inverting a massive cross-products matrix such as is required when evaluating ~35,000 zip codes at one time. However, that was then and this is now. Today, there are workarounds to the massive size of your data that have put "frequentist" approaches at parity with Bayesian techniques. These include so-called "divide and conquer" algorithms which, in essence, can be analogized to massive random forest-like approaches in that -- instead of just creating a thousand or so mini-trees (Breiman's original forests or ensembles) -- one builds tens of thousands of mini-models and aggregates the results on the back end. Here's a recent review paper on D&C:
http://stat.rutgers.edu/home/mxie/RCPapers/split_and_conquer_rev1_final.pdf
Of course, this method would be still be a challenge today on a single CPU or laptop as these techniques only really become an advantage on a multi-core platform.
There's plenty of literature to review regarding hierarchical models... starting with Gelman and Hill's Data Analysis Using Regression and Multilevel/Hierarchical Models. Otherwise, I'm agnostic as to the specific functional form the regression should take beyond a hierarchical one. It could be that exploring different approaches to analyzing one, two or a few of the payitems would provide direction towards answering that question.


text:
Q: Are there any data modeling exercises for Cassandra like Retwis for Redis? I'm trying to learn how to map the entities/actors/objects/things in my application for storage in Cassandra.  There was a great tutorial for Redis on modeling Twitter data and typical access patterns called Retwis [1].  I've found a couple of examples for Cassandra.
How did you start to gain an intuition for Cassandra's data model?
[1] http://retwis.antirez.com/

A: http://github.com/ericflo/twissandra is a twitter clone in the same vein as retwis, originally for 0.3 and now being updated for 0.6.  Catch erifclo in #cassandra on irc if you have questions.

A: *

*you should start with WTF is a SuperColumn to understand the data model.

*up and running with cassandra is also a very good starting tutorial and it has
example schemas for a blog and for twitter.


text:
Q: MPI_Allreduce not working as expected - Red Black SOR I'm implementing a parallel version of Red Black SOR.
The MPI_Allreduce part, where I want to get the maximum error of every process, is not working. It never changes, it gives values higher than 2.0, even with only one process. What's going on??
Here's the code, the interesting part is at the end of the sor routine.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <mpi.h>

#define M 700

int numtasks, rank, inext, iprev, ista, iend;

double unew[M + 2][M + 2] = {{ 0 }};
double solution[M + 2][M + 2] = {{ 0 }};

double uold[M + 2][M + 2] = {{ 0 }};

double bufs1[M + 2];
double bufs2[M + 2];

double bufr1[M + 2];
double bufr2[M + 2];

MPI_Request ireqs1;
MPI_Request ireqs2;

MPI_Request ireqr1;
MPI_Request ireqr2;

MPI_Status istatus;

double compute_error(double solution[][M + 2], double u[][M + 2], const int m);
int sor(double unew[][M + 2], double uold[][M + 2], double solution[][M + 2], const double omega, const double tol, const int m);
void para_range(const int n1, const int n2, const int nprocs, const int irank, int * restrict ista, int * restrict iend);
void shift(const int iflg);
inline int min(const int a, const int b);

int main(int argc, char * argv[])
{
    const int m = M;

    int ierr = MPI_Init(&argc, &argv);

    if(ierr != MPI_SUCCESS)
    {
        perror("MPI init failed. Terminating T800.\n");
        exit(1);
    }

    int i, j;

    const double begin = MPI_Wtime();

    const double pi = 4.0 * atan(1.0);

    const double h = pi / (m + 1);

    MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    for(i = 0; i < m + 2; ++i)
    {
       uold[i][M + 1] = sin(i * h);
    }

    for(i = 0; i < m + 2; ++i)
    {
    for(j = 0; j < m + 1; ++j)
        {
            uold[i][j] = j * h * uold[i][M + 1];
        }
    }

    for(i = 0; i < m + 2; ++i)
    {
        for(j = 0; j < m + 2; ++j)
        {
            solution[i][j] = sinh(j * h) * sin(i * h) / sinh(pi);
        }
    }

    para_range(0, m, numtasks, rank, &ista, &iend);

    //printf("rank %d: from %d to %d\n", rank, ista, iend);

    inext = rank + 1;
    iprev = rank - 1;

    if(inext == numtasks)
    {
        inext = MPI_PROC_NULL;
    }

    if(iprev == -1)
    {
        iprev = MPI_PROC_NULL;
    }

    const double omega = 2.0 / ( 1.0 + sin(pi / (m + 1)) );
    const double tol = 0.001;

    const int iters = sor(unew, uold, solution, omega, tol, m);

    const double end = MPI_Wtime();

    MPI_Finalize();

    if(rank == 0)
    {
        printf(" \n");
        printf(" Omega = %f\n", omega);
        printf(" It took %d iterations.\n", iters);

        printf("Total time = %f\n\n\n", end - begin);
    }

    return 0;
}

double compute_error(double solution[][M + 2], double u[][M + 2], const int m)
{
    double error = 0.0;
    int i, j;

    for(i = 1; i < m + 1; ++i)
    {
        for(j = 1; j < m + 1; ++j)
        {
            const double abs_diff = fabs(solution[i][j] - u[i][j]);

            if(error < abs_diff)
            {
                error = abs_diff;
            }
        }
    }

    return error;
}

int sor(double unew[][M + 2], double uold[][M + 2], double solution[][M + 2], const double omega, const double tol, const int m)
{
    int i, j;

    int iters = 0;
    double error = compute_error(solution, uold, m);
    double error2 = error;
    double temp;

    while(error2 > tol)
    {
        shift(0);

        for(i = 1; i < m + 1; ++i)
        {
            for(j = (i % 2) + 1; j < m + 1; j += 2)
            {
                temp = 0.25 * (uold[i][j - 1] + uold[i - 1][j]
                   + uold[i + 1][j] + uold[i][j + 1]) - uold[i][j];
                uold[i][j] += omega * temp;
            }
        }

        shift(1);

        for(i = 1; i < m + 1; ++i)
        {
            for(j = ((i + 1) % 2) + 1; j < m + 1; j += 2)
            {
                temp = 0.25 * (uold[i][j - 1] + uold[i - 1][j]
                   + uold[i + 1][j] + uold[i][j + 1]) - uold[i][j];
                uold[i][j] += omega * temp;
            }
        }

        ++iters;

        if(iters % 20 == 0)
        {
            // THIS IS NOT COOL
            error = compute_error(solution, uold, m);
            MPI_Allreduce(&error, &error2, 1, MPI_REAL, MPI_MAX, MPI_COMM_WORLD);

            //printf("%d=%f\n", rank, error2);
        }
    }

    return iters;
}

void para_range(const int n1, const int n2, const int nprocs, const int irank, int * restrict ista, int * restrict iend)
{
    const int iwork = ((n2 - n1) / nprocs) + 1;

    *ista = min(irank * iwork + n1, n2 + 1);
    *iend = min(*ista + iwork - 1, n2);
}

void shift(const int iflg)
{
    const int is1 = ((ista + iflg) % 2) + 1;
    const int is2 = ((iend + iflg) % 2) + 1;

    const int ir1 = 3 - is1;
    const int ir2 = 3 - is2;

    int i, icnt1=0, icnt2=0;

    if(rank != 0)
    {
        icnt1 = 0;

        for(i = is1; i < M; i += 2)
        {
            ++icnt1;
            bufs1[icnt1] = unew[i][ista];
        }
    }

    if (rank != numtasks - 1)
    {
        icnt2 = 0;

        for(i = is2; i < M; i += 2)
        {
            ++icnt2;
            bufs2[icnt2] = unew[i][iend];
        }
    }

    MPI_Isend(bufs1, icnt1, MPI_REAL, iprev, 1, MPI_COMM_WORLD, &ireqs1);
    MPI_Isend(bufs2, icnt2, MPI_REAL, inext, 1, MPI_COMM_WORLD, &ireqs2);

    MPI_Irecv(bufr1, M + 2, MPI_REAL, iprev, 1, MPI_COMM_WORLD, &ireqr1);
    MPI_Irecv(bufr2, M + 2, MPI_REAL, inext, 1, MPI_COMM_WORLD, &ireqr2);

    MPI_Wait(&ireqs1, &istatus);
    MPI_Wait(&ireqs2, &istatus);

    MPI_Wait(&ireqr1, &istatus);
    MPI_Wait(&ireqr2, &istatus);

    int icnt;

    if(rank != 0)
    {
        icnt = 0;

        for(i = ir1; i < M; i += 2)
        {
            ++icnt;
            unew[i][ista - 1] = bufr1[icnt];
        }
    }

    if(rank != numtasks - 1)
        {
        icnt = 0;

        for(i = ir2; i < M; i += 2)
        {
            ++icnt;
            unew[i][iend + 1] = bufr2[icnt];
        }
    }
}

inline int min(const int a, const int b)
{
    if(a > b)
    {
        return b;
    }

    return a;
}

A: MPI_REAL is for Fortran's REAL type that usually corresponds to float in C. The data you are reducing is of type double, therefore you should use MPI_DOUBLE instead. The same applies to the MPI calls in the other parts of your program.


text:
Q: Wordpress scroll down arrow to a section of page Does anyone know how to put an arrow that scrolls down to another section of the page in wordpress. This arrow will be located at the homepage header and once the user sees it they click it to scroll down to the next section of the page.
Thanks

A: It is called "anchors".
Link:
Go to footer

Section should contain

or

or any tag with this name="section_at_footer" attribute.

A: Arrow in header Should be a link:
Read more

Section should contain:

For smooth scrolling it requires javascript,
$(document).ready(function(){
$('a[href*="#"]:not([href="#"])').click(function() {
  if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
    var target = $(this.hash);
    target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
    if (target.length) {
      $('html, body').animate({
        scrollTop: target.offset().top
      }, 500);
      return false;
    }
  }
});
});


text:
Q: Vuetify.js 2 - Data tables footer does not display properly with babel-polyfill I'm using Data tables in Vuetify.js 2.0.10. The footer does not display properly in IE11 as bellow.

I read this document.
https://vuetifyjs.com/en/getting-started/quick-start#ie-11-safari-9-support
I installed babel-polyfill and @/babel/preset-env and then configured babel.config.js and vue.config.js like bellow.
package.json
{
"name": "table-test",
"version": "0.1.0",
"private": true,
...
"dependencies": {
    "babel-polyfill": "^6.26.0",
    "vue": "^2.6.10",
    "vuetify": "^2.0.10",
    ...
},
"devDependencies": {
    "@babel/preset-env": "^7.5.5",
    ...
}
}

babel.config.js
module.exports = {
presets: [
    '@vue/app',
    '@babel/preset-env'
]
}

vue.config.js
module.exports = {
    transpileDependencies: ["vuetify"]
}

main.js
import "babel-polyfill";  // polyfill
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import vuetify from './plugins/vuetify';

Vue.config.productionTip = false;

new Vue({
router,
store,
vuetify,
render: h => h(App)
}).$mount("#app");

Vue template
<template>
<v-data-table
        :headers="headers"
        :items="desserts"
        class="elevation-1"
></v-data-table>

</template>
<script>
export default {
data: () => ({
    headers: [
        ...
    ],
    desserts: [
        ...
    ]
}),
};
</script>

My question is:
1. Is there any way to resolve this problem?
2. When I open this Vuetify document page in IE11
https://vuetifyjs.com/en/components/data-tables
the footer displays properly, Why?

A: Try using the following styles as a workaround. Maybe you need to adjust the pixel sizes to your own needs.
// IE11 Data table footer fix
.v-data-footer__select {
  flex-basis: auto;

  .v-select {
    flex-basis: 50px;

    .v-select__selections {
      flex-basis: auto;
    }
  }
}

.v-list-item__content {
  flex: 1 1 auto;
  min-width: 40px;
}


text:
Q: Hook for validating and rejecting frontend image upload I am making a plugin that checks the contents of uploaded images. Right now I am testing if I am using the right hook, so I use getimagesize() to check the image (I am aware this is not the best/most thorough way to do this. This is just for testing the hook). If it's not an image, it will show the error message below.

I use the hook wp_handle_upload_prefilter and it works fine, but only at the admin dashboard (which is what the codex suggests). I used this plugin which allows users to upload from post/page to do the testing and the fake image uploaded successfully.
I've searched through Google and this site and most people suggest wp_handle_upload_prefilter or add_attachment. However, I am not sure add_attachment is the one I am looking for because according to this site an attachment is a file uploaded from the post edit screen, which is still from admin dashboard. I've tested it and the error message did show up. (ps. I see people use add_filter("add_attachment",...) but Wordpress says this is an action hook?)
I'm also thinking just go through each file in $_FILES and then do the checking, but again I don't know which hook to use with this method.
Thanks very much!

A: I found it after trying with several hooks.
Use 'init' and check if $_FILES is empty, if not, do what you want to do.
init hook


text:
Q: Magento 2 : Call Helper Without Using __construct in Own Module I have created a new module and override the

\Magento\Catalog\Block\Product\View\Description

function using preference.
In this module we create new helper located in

Custom_Hello/Helper/Data.php

Then how to call this helper in

Custom_Hello/Block/Product/View/Description.php

If we use __construct got some error.
public function __construct(\Custom\Hello\Helper\Data $helper)
    {
        $this->helper = $helper;
    }

Anyone helpme

A: You can add your custom helper in constructor, but as this method is present in the class you're extending then you'd pass the right parameters in it, not just your helper
class Description extends \Magento\Catalog\Block\Product\View\Description

You are extending \Magento\Catalog\Block\Product\View\Description so let's see constructor in this class (in 2.3 version, you can check this in your project for other version, if that's the case)
public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Framework\Registry $registry,
    array $data = []
) {
    $this->_coreRegistry = $registry;
    parent::__construct($context, $data);
}

So, in your class you'd pass that $context & $registry parameters. You can do that this way
public function __construct(
    \Custom\Hello\Helper\Data $helper,
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Framework\Registry $registry,
    array $data = []
) {
    $this->helper = $helper;
    parent::__construct($context, $registry, $data);
}

A: I got the solution. If we use following way
public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Registry $registry,
        \Custom\Hello\Helper\Data $dataHelper,
        array $data = []
    ) {
        parent::__construct($context, $registry, $data);
        $this->_dataHelper = $dataHelper;
    }

A: In Custom_Hello/Block/Product/View/Description.php File
protected $helper;

public function __construct(
        \Magento\Catalog\Block\Product\Context $context,
        \Custom\Hello\Helper\Data $helper
        array $data = []
    )
    {
        $this->helper= $heper;
        parent::__construct($context, $data);
    }

And You Can Call Your Helper Function Like this
$this->helper->yourFunctionName()

A:
You can use directly without contructor

$this->helper('CompanyName\ModuleName\Helper\Data')->yourfunctionname();


text:
Q: How can we make our Customize Getter from Qt creator? If we right click on any Data member and goto Refractor -> and click on Create Getter Setter.
It creates Getter ByDefault as get+DataMemberName. But i want to make Getter as Qt's convention,
Example :
for DataMember carName ByDefault QtCretor will create -> getCarName()
but i want -> CarName().
Can it be possible by changing some Creator Setting or some thing else..

A: After looking at /plugins/cppeditor/cppquickfixes.cpp mentioned in Dominik's answer, there is simple way:
Name you private data member in any of these ways
QString m_carName;
QString _carName; // note: using _ to start identifier is questionable (*)
QString carName_;

Then Qt Creator should generate getter carName. Note that CarName is not Qt convention, but if you do want that anyway, then use m_CarName as variable name.
(*) See What are the rules about using an underscore in a C++ identifier?

A: A very easy option would be to compile QtCreator from source and change the naming rule in file
/plugins/cppeditor/cppquickfixes.cpp. Search for class GenerateGetterSetterOperation. In the constructor the variable name m_getterName and m_setterName are defined here.
The piece of code you are looking for is:
m_getterName = m_baseName != m_variableString
        ? QString::fromLatin1("%1").arg(m_baseName)
        : QString::fromLatin1("get%1%2")
            .arg(m_baseName.left(1).toUpper()).arg(m_baseName.mid(1));
m_setterName = QString::fromLatin1("set%1%2")
        .arg(m_baseName.left(1).toUpper()).arg(m_baseName.mid(1));

You have to change the first part to something like:
 m_getterName = m_baseName != m_variableString
        ? QString::fromLatin1("%1").arg(m_baseName)
        : QString::fromLatin1("%1%2")
            .arg(m_baseName.left(1).toLower()).arg(m_baseName.mid(1).toUpper());

Honestly, i did not check for correctness.
EDIT: Hyde is absolutely right. I did not check the mechanism that i cited in-depth due to time limitations but tried it a few minutes ago and checked the source.


text:
Q: WP7 XNA + SilverLight + Touch = Wrong Coordinates? I'm using the mixed XNA/SL programming model where the Silverlight content is rendered by UIElementRenderer.  However, it appears that there is a 40 pixel offset between the screen coordinates reported by touch (GestureSample) and the actual coordinates where the contents of the page are rendering.
It appears to be space reserved for the SystemTray in Silverlight apps.
My question is: is there an API I can call to dynamically return this offset so I don't have to hard-code it?
Thanks!

A: I don't actually think there is any such offset. Since the GestureSample has accurate screen coordinates, your problem is probably with drawing the silverlight UI. Make sure that you don't have any view/projection transforms active on your SpriteBatch when you draw the uiRenderer texture.
If you were using a transform to draw your game scene, you might just want to end that SpriteBatch and start up a new one for screen UI.


text:
Q: Is J2me peer to peer networking possible? can two j2me wireless devices (cellphones)  directly communicate with each other over internet using  gprs ?
I have heard that these devices change their IPs fast and use dynamic NAT ...
Is it possible that the two device connect to each other using their  ip addresses .. Without using dedicated server in between them

A: I know only one telecom operator that allows a fixed IP to a phone: Nextel. It is based on Motorola iDEN technology. And to enable it you have to sign an specific service.


text:
Q: Activating installed Nvidia videa drivers I Have installed several video drivers from the software centre and I have installed the official driver from Nvidia.com and none of them show up in the additional drivers application. I did what this suggested but they still do not show Nvidia driver installed successfully, but not activated .
The reason I am trying to use a different driver is because when I use the nouveau or the nvidia 331 driver I can't use my nvidia card, when I use the kernal and VDPAU 340 driver I get graphical glitches.
output of lspci | grep VGA 00:02.0 VGA compatible controller: Intel Corporation 4th Gen Core Processor Integrated Graphics Controller (rev 06)
output of lspci | grep 3D 02:00.0 3D controller: NVIDIA Corporation GK107GLM [Quadro K1100M] (rev a1)
the intel card goes to the monitor port but the nvidia card is for rendering

A: To start off with, type lspci | grep VGA and take a note of your Graphic card model, just to make sure it is NVidia .
You are probably using the xorg open sourced driver right now and high resolution can create problems, as far as I'm aware.
To install the unofficial drivers, follow these steps :
Press Ctrl + Alt + F2 and login with your credentials. Now as root, run the following commands :
killall -9 lightdm (Unity)
or,
killall -9 kdm (KDE)
or,
killall -9 gdm (Gnome)
Now, type :
killall -9 Xorg
And run the following commands :
sudo apt-get --purge remove nvidia-current
sudo apt-get --purge autoremove
sudo add-apt-repository ppa:ubuntu-x-swat/x-updates
sudo apt-get update
sudo apt-get -y install nvidia-current


text:
Q: Backup2l error when backing up files that are in use. I have backup2l set-up to rsync my backup. Although I have found that if the files are in use while the backup is taking place it produces an error.
This is the email I receive:
/etc/cron.daily/zz-backup2l:
backup2l v1.5 by Gundolf Kiefer

Sun Sep 25 03:20:50 BST 2011

Running pre-backup procedure...
  writing dpkg selections to /root/.dpkg-selections.log...
 dumping databases

Removing old backups...

Preparing differential level-2 backup <all.104> based on <all.103>...
  145008 / 145008 file(s), 12432 / 12432 dir(s), 10.3GB / 10.3GB (uncompressed)
  skipping: 175 file(s), 0 dir(s), 735KB (uncompressed)

Creating archive using 'DRIVER_TAR_BZ2'...
  tar: Removing leading `/' from hard link targets
  tar: /var/vmail/vmail01/example.com/b/ba/bar/barry-2010.12.11.10.28.01/Maildir/dovecot.index.log.2: Cannot stat: No such file or directory
  tar: Exiting with failure status due to previous errors
Checking TOC of archive file (< real file, > archive entry)...
  47299d47298
  < /var/vmail/vmail01/example.com/b/ba/bar/barry-2010.12.11.10.28.01/Maildir/dovecot.index.log.2
  96928c96927
Creating check file for <all.104>...

Running post-backup procedure...

Sun Sep 25 09:26:49 BST 2011

Summary
=======

Backup       Date       Time  |  Size   | Skipped  Files+D |  New  Obs. | Err.
------------------------------------------------------------------------------
all.1        2011-09-21 02:26 |    7.3G |     198   161103 |161103     0 |    5
all.101      2011-09-22 02:25 |   51.4M |     192   161788 | 2270  1585 |    0
all.102      2011-09-23 02:25 |   46.6M |     213   162460 | 1610   938 |    0
all.103      2011-09-24 02:25 |   58.6M |     188   156809 | 2450  8101 |    0
all.104      2011-09-25 03:23 |    7.4G |     175   157440 |157440 156809 |    2

Filesystem            Size  Used Avail Use% Mounted on
/dev/vda               40G   30G  8.4G  78% /

Backup2l config
##################################################
# Configuration file for backup2l                #
##################################################

# Define the backup2l version for which the configuration file is written.
# This way, future versions can automatically warn if the syntax has changed.
FOR_VERSION=1.4

##################################################
# Volume identification

# This is the prefix for all output files;
# multiple volumes can be handled by using different configuration files
VOLNAME="all"

##################################################
# Source files

# List of directories to make backups of.
# All paths MUST be absolute and start with a '/'!
# SRCLIST=(/etc /root /home /var/mail /usr/local)
SRCLIST=(/etc /root /home /var/vmail /var/www /var/svn /usr/local /var/backups/mysql /var/backups/ldap)

# The following expression specifies the files not to be archived.
# See the find(1) man page for further info. It is discouraged to
# use anything different from conditions (e. g. actions) as it may have
# unforeseeable side effects.

# This example skips all files and directories with a path name containing
# '.nobackup' and all .o files:
#SKIPCOND=(-path "*.nobackup*" -o -name "*.o")
SKIPCOND=(-path "*.nobackup*" -o -name "*.o" -name "*~" -o -name "cache.*" -o -path "*/tmp/captchas/*")

# If you want to exclude several directories use the following expression:
# SKIPCOND=(-path '/path1' -o -path '/path1/*' -o -path '/path2' -o -path '/path2/*')

# NOTE: If you do not have anything to skip, use:
# SKIPCOND=(-false)     # "SKIPCOND=()" does not work

##################################################
# Destination

# Mount point of backup device (optional)
#BACKUP_DEV="/disk2"

# Destination directory for backups;
# it must exist and must not be the top-level of BACKUP_DEV
BACKUP_DIR="/var/backups/localhost"

##################################################
# Backup parameters

# Number of levels of differential backups (1..9)
MAX_LEVEL=2

# Maximum number of differential backups per level (1..9)
MAX_PER_LEVEL=7

# Maximum number of full backups (1..8)
#MAX_FULL=2
MAX_FULL=1

# For differential backups: number of generations to keep per level;
# old backups are removed such that at least GENERATIONS * MAX_PER_LEVEL
# recent versions are still available for the respective level
GENERATIONS=1

# If the following variable is 1, a check file is automatically generated
CREATE_CHECK_FILE=1

A: Yes, this error message is (a) intended and (b) happens to me fairly often as well.
This error is simply due to the way backup2l operates: Make a list of files to backup, backup them, then check what files are in the backup. Since the backup process takes some time, you'll often get /some/ files that are changed in the process and are consequently backup errors. You definitely want to /know/ about these files, since backup failures are often serious business[1].
So, my advice is to backup at less busy times of the day. You'll get a mail from your backup cronjob, and you should read it carefully anyway. Sometimes you'll have these errors, but they are not fatal to the backup. Just make sure it's not the same file every day.
[1] Small anecdote here: For a time, we thought backupping by having our main data partition as a loop-back mounted file on university storage was a bright idea. Just resulted in the data partition file (~1 TB) being sent to the backup server each night, which took a few hours, then being checked for changes and, having changes, being discarded. No backup was actually performed in months. Major d'oh moment, and from that day on we made sure to talk to everyone involved to make sure that backups were /actually/ made and were recoverable.


text:
Q: MYSQL Trigger: Update before insert I want to increment the order of every video by one every time a video gets inserted so that the new video takes its place
UPDATE services SET orders = orders + 1
This doesn't work, I get this error, is there an easy fix? I could fix it in PHP but I'll have to fix it in multiple places and find the buggy code, it's just one-liner code, so much easier if it works as a trigger.

A: You forget that trigger works with ONE record.
You may, of course, do something like
CREATE TRIGGER increase_orders
ON services
BEFORE INSERT
FOR EACH ROW
SET NEW.orders = ( SELECT 1 + MAX(services.orders)
                   FROM services
                   WHERE services.video_id = NEW.video_id );

But when 2 clients would insert a record with the same video_id you may obtain duplicated orders value. And you can do close to nothing with that problem while using this method.


text:
Q: How to create a personal failover laptop? This question sounds a tad vague but I'll lay it out rather clearly with some requirements:

*

*Each laptop should contain the same files in the home folder.

*User accounts should be identical.

*Identical Applications would be exceptional.

*Application Configurations must remain identical.

*RSync or something similar sounds obvious but my IP changes frequently and I want my machines to continue to synchronize minimum daily.

Really what I'm looking for is: A laptop that I can use in case my primary breaks. This would be exceptionally useful for my work and personal life, I have numerous older laptops that are by no means fancy but I could probably roll with it so long as there are as few changes as possible. Downtime is my enemy.
How can I mirror and synchronize those requirements between two laptops automatically and at least daily?
Edit: Emphasis on automation and on the fly. Other questions on AskUbuntu are suggesting backups and mirroring my disk, this would be great if DD worked on the fly over rsync maybe.

A: If you have onedrive, you can use the onedrived service for linux. I'll link it below.
Basically you need to setup one laptop how you want it and installed onedrived then configured, clone the drive to an image and restore that image to another computer.
Configure Onedrived to use your home folder as the "Onedrive" folder. Onedrived will work by keeping your files you have in your home folder backed up online. Once you bring the other laptop online, it will then download everything you had back to your new computer. Once you fix your primary laptop, it will then re-sync any updated files to that laptop.
https://github.com/abraunegg/onedrive


text:
Q: System.RankException Error in Visual Basic When Passing Array to Function I'm having some serious difficulty with this.  Anyone thing they can help me out?
Variable Declaration (Outside of any sub)
Dim notes = New String() {"A", "A#/Bb", "B", "C", "C#/Db", "D", "D#/Eb", "E", "F", "F#/Gb", "G", "G#/Ab"}

Dim boxString1 = New TextBox()  {boxSt1Pos1, boxSt1Pos2, boxSt1Pos3, boxSt1Pos4, boxSt1Pos5, boxSt1Pos6, boxSt1Pos7,
    boxSt1Pos8, boxSt1Pos9, boxSt1Pos10, boxSt1Pos11, boxSt1Pos12, boxSt1Pos13, boxSt1Pos14,
    boxSt1Pos15, boxSt1Pos16, boxSt1Pos17, boxSt1Pos18, boxSt1Pos19, boxSt1Pos20, boxSt1Pos21,
    boxSt1Pos22, boxSt1Pos23, boxSt1Pos2, boxSt1Pos25}

Function Signature (Outside of any sub)
Function populateStrings(startPos As Integer, ByRef gString As TextBox(), ByVal notes As String())

Function Call (Inside form.load sub)
Call populateStrings(3, boxString1(), notes())

The program builds fine but errors when run, stating the aforementioned error, and I can't manually define dimensions anywhere in the function signature or call.  Any help is greatly appreciated.


text:
Q: Linq Distinct() is not working Distinct() is not working. It displays all the repeating values.
I searched for a solution but just got more confused. I tried this :
var categories = db.Orders.OrderBy(c => c.Item1).ToList().Distinct();
var categories = db.Orders.Distinct().OrderBy(c => c.Item1).ToList();

Is there a quick uncomplicated way to make this work?

A: use GroupBy instead of Distinct


text:
Q: TabBar and NavBar disappears with segue. How can I pass data through NavController and/or keep NavBar and TabBar after segue? My Tabbed Bar and Navigation bar disappears whenever I use a Show Detail Segue to pass data through to another ViewController. I have managed to pass the relevant data in order to read which cell has been selected so I can insert a .txt file into a UITextField the the final ViewController. It's sort of like a dynamic textView. I would still like to be able to select different Tabs when I am in the article view (final vc). Is there any way to keep the NavBar and Tabbed View Bar in the final viewController after the segue, or is there a way to pass data through a Nav Controller. Or, sorry this will be the last one, do I use the prepare for segue and push the previous NavController (not too sure how to do this). Sorry I couldn't post more than 2 image links, hence the large amount of code. Thanks
Image 1: Layout of the Storyboard
This is from rBVC.class (My Road Block Category Class File), where I have a TableView:
class rBVC: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var rBTableView: UITableView!

    var rBLabels = ["General Info", "Drunk Driving", "Arrest", "Searches"]

    var rBIcons = [UIImage(named: "generalInfo"), UIImage(named: "drunkDriving"), UIImage(named: "arrests"), UIImage(named: "searches")]

    var valueToPass: String!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return rBIcons.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

         let rBCell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "rBCell", for: indexPath) as! rBCell
         rBCell.textLabel!.text = self.rBLabels[indexPath.row]
         rBCell.imageView!.image = self.rBIcons[indexPath.row]
         return rBCell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You selected cell #\(indexPath.row)!")
        //performSegue(withIdentifier: "rBASegue", sender: self)
        print(valueToPass)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "rBSegue"){
            /*let vcName = "rBTXT"
            let vC = storyboard?.instantiateViewController(withIdentifier: vcName)
            self.navigationController?.pushViewController(vC!, animated: true)*/
            let indexPath = self.rBTableView.indexPathForSelectedRow!
            let currentCell = self.rBTableView.cellForRow(at: indexPath) as! rBCell
            valueToPass = currentCell.textLabel?.text
            self.rBTableView.deselectRow(at: indexPath, animated: true)
            // initialize new view controller and cast it as your view controller
            let viewController = segue.destination as! rBAV
            // your new view controller should have property that will store passed value
            viewController.passedValue = valueToPass
            print("\(valueToPass)test")
        }
    }

}

Image 4: This is where I have the problem of the disappearing bar's.
class rBAV: UIViewController {

    @IBOutlet var rBTV: UITextView!
    var passedValue: String?
    var rBArticle: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        if passedValue == "General Info"{
            rBArticle = "rBGI"
        }

        if passedValue == "Drunk Driving"{
            rBArticle = "rBDD"
        }

        if passedValue == "Arrest"{
            rBArticle = "rBA"
        }

        if passedValue == "Searches"{
            rBArticle = "rBS"
        }

        // Save data to file
        let fileName = "Test"
        let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        let fileURL = DocumentDirURL.appendingPathComponent(fileName).appendingPathExtension("txt")
        //print("FilePath: \(fileURL.path)")

         /*** Read from project txt file ***/

        // File location
        let fileURLProject = Bundle.main.path(forResource: rBArticle, ofType: "txt")
        // Read from the file
        var readStringProject = ""
        do {
            readStringProject = try String(contentsOfFile: fileURLProject!, encoding: String.Encoding.utf8)
        } catch let error as NSError {
            print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
        }
        rBTV.insertText(readStringProject)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}


text:
Q: How to find the second largest element in a user-input Javascript array I'm working with arrays and I have made the code so that it prompts the user to enter an array of their choice of size. It lets them input each number one by one. I would like so that once this is done the program will then find and print the second largest number in the array but I'm not sure how to go about it.
I would highly like to avoid using infinity or splices just wanted to do something that a newbie like me can understand.
CODE:

  <form name="frm">

 Enter the array size : <input type="text" name="text1">

      <input type="button" onclick="show_prompt()" value="Submit">

      <textarea name="arrayTxt" rows="10" cols="4"></textarea>

  </form>

A: You can use a simple for loop, storing the largest and second largest elements, in O(n) time. There is no need to sort the array, which is very inefficient for larger arrays.
let largest = Number.MIN_SAFE_INTEGER, largest2 = largest;
for(const num of a){
    if(num > largest){
       largest2 = largest;
       largest = num;
    } else if(num > largest2){
       largest2 = num;
    }
}
console.log(largest2);

If you need the strictly second largest element, you can remove the duplicates from the array using Set.
a = [...new Set(a)];//add this before the loop

A: The easiest option is probably to simply sort the array and select the second element. JavaScript Arrays nowadays actually support sorting an array by passing a comparison function.
[2, 5, 3, 1, 4].sort((a, b) => b - a); // [5, 4, 3, 2, 1]

Simply speaking, if the function returns a value < 0, a is inserted before b, if it returns a value > 0 it a is insterted behind b. If it returns 0 nothing is changed. b - a means "if a > b, move it to the front", resulting in an array sorted highest to lowest. Annoyingly, if you don't pass in a comparison function, the elements are converted to strings and then sorted low to high ([1, 5, 10, 20] would be sorted [1, 10, 20, 5]).
To select the second hightest element you would simply select the second index:
a.sort((a, b) => b - a)[1];

Keep in mind, that after calling sort(), the original array will be changed as well.
A different approach would be more hands on, similar to finding the max value.
let max = 0, secondMax = 0;
for (let i = 0; i = max) {
        secondMax = max;
        max = a[i];
    } else if (a[i] > secondMax) {
        secondMax = a[i];
    }
}

This can be slightly more efficient when dealing with large arrays. But since you fill your array with user input, I would choose the first version. It is much shorter and more readable.

NOTE:
The so called "arrow notation" (a, b) => b - a is simply a shorthand for function (a, b) { return b - a; }. There is more to it, namely arrow functions inheriting this from the creation context, but this has no impact in this specific example.

A: You could try this:
var numArray = [21, 81, 3847, 218];
numArray.sort((a, b) => b - a); // [3847, 218, 81, 21]
numArray = [...new Set(numArray)]; // Removes duplicates
console.log(numArray[1]); // Returns 218

This basically sorts the array in descending order, and selects the second number via index.

A: You could just sort the array and return the second number. This should work fine:

var a = [5,3,1,6,8,3,9];
var sorted = a.sort((a, b) => b - a);
alert(a[1])

A: This is mine:
var first = 0;
var second = 0;
array.forEach(number => {
    if (number > first) {
        second = first;
        first = number;
    }
    else if (number > second) second = number;
});

I believe this is more efficient than a sort but I'm not sure. It might be a more readable solution but it's definitely more over-engineered.

A: Here's a simple way to do this without using short method. This one will also work if there's even duplicate numbers of largest integer.
function getSecondLargest(arr) {
  const largest = Math.max.apply(null, arr);
  for (let i = 0; i < arr.length; i++) {
    if (largest === arr[i]) {
      arr[i] = -Infinity;
    }
  }
  return Math.max.apply(null, arr);
}
console.log(getSecondLargest([2, 3, 4, 4, 4])); //3


text:
Q: firebase_analytics '' is an invalid event name I'm trying to log user events using firebase_analytics I followed the documentation
this my main() method
void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp(
    name: "test_app",
    options: DefaultFirebaseOptions.currentPlatform,
  );

  runApp(const MyApp());
}

This is MyApp class
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  static FirebaseAnalytics analytics = FirebaseAnalytics.instance;
  static FirebaseAnalyticsObserver observer =
      FirebaseAnalyticsObserver(analytics: analytics);

  @override
  Widget build(BuildContext context) {
    return
        ...
        navigatorObservers: <NavigatorObserver>[observer],
        routes: {
          '/': (context) => const MainScreen(),
          'product': (context) => ProductScreen(
                analytics: analytics,
                observer: observer,
              ),
        },
      ),
    );
  }
}

And this is how I log event
body: TextButton.icon(
      onPressed: () async {
        await analytics.logEvent(
          name: 'test_event',
          parameters: <String, dynamic>{
            'string': 'string',
          },
        );
      },
      icon: const Icon(Icons.analytics),
      label: const Text("Test Analytics")),

why do I end up with this error
W/FA      ( 7136): '' is an invalid event name.

A: if you haven't imported Firebase Analytics, import
import 'package:firebase_analytics/firebase_analytics.dart';

first in your main file.
If the issue still persists, run the following commands:
cd android
./gradlew clean
./gradlew build
flutter clean
flutter pub get

A: My problem was in Firebase initialization
The documentation said to initialize Firebase like this but then I did I run into error that I needed to add a name
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

so I tried to add a name as above
  await Firebase.initializeApp(
    name: "test_app",
    options: DefaultFirebaseOptions.currentPlatform,
  );

this let the app start but I got the error when I tried to log any event
so I removed options and name from Firebase initialization line
void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp();

  runApp(const MyApp());
}

and it worked fine.


text:
Q: Zsh refer to last element of current argument list and expand it Suppose I do something like:
ln a_file_with_a_long_filename.pdf ~/path/to/a/new/hardlink/a_file_with_a_long_filename_slightly_modified.pdf

Is there a way to refer to and expand a_file_with_a_long_filename.pdf if my cursor is at the end of the string ln a_file_with_a_long_filename.pdf ~/path/to/a/new/hardlink/ in zsh?
If not, what would you suggest do reduce typing work?

A: With the default Emacs bindings, it's just two keychords: ESC-2 ESC-^_ (i.e. Esc 2 Esc Ctrl+_ or Alt+2 Ctrl+Alt+_).
That's the command copy-prev-word with the numeric argument 2 (the default argument 1 would copy ~/path/to/a/new/hardlink/). If the file name contains (quoted) spaces, you would need ESC-2 ESC-x copy-prev-shell-word RET. You may want to bind this command to more convenient key, especially if your keyboard layout requires Shift for _. You can use these commands in vi mode as well, but neither is bound to a key by default.
If you get the numeric argument wrong, press Ctrl+_ to undo then try again.

A: This sounds like a fun code golf challenge. Here's one option:

*

*Run an innocuous command with the filename; enter enough of the filename to allow TAB-completion.
: a_file<TAB>

*Use !!$ to refer to the last argument of the previous command:
ln !!$ ~/path/to/a/new/hardlink/!!$

Thanks to zsh's helpful quoting, this is safe even in the face of IFS-containing filenames. You'll notice that as soon as you hit space after the first !!$, zsh expands the filename; ditto if you add a gratuitous space at the end of the command.
Number of characters required is:

*

*3 x 2 = 6 for the two !!$

*2 for the :<SPACE>
8 + plus enough for the initial tab completion.

A: In vi mode this would be <esc>0wyt $p which goes to command mode, 0 beginning of the line, w to the next word (advance to the filename) yt yank to space (to get the long filename, assuming no spaces in the filename) and then $p to put what was just yanked at the end of the line. This is a lot quicker than describing it once you memorize the vi motions.
You could also setup a bindkey to yank-put the second argument though that's pretty specific code for such a use case, here bound to control+t but that could be whatever you want.
function yank-put {
  local -a words
  words=(${(z)LBUFFER})
  if (( $#words > 1 )); then
    BUFFER+=$words[2]
    CURSOR+=${#words[2]}
  fi
}
zle -N yank-put
autoload -U yank-put compinit
compinit
set -o vi
bindkey -M viins "^t" yank-put

A: There is copy-earlier-word, you could bind it to your favorite keybinding before using it with appending these lines to ~/.zshrc:
autoload -Uz copy-earlier-word
zle -N copy-earlier-word
bindkey "^[," copy-earlier-word

So, you could use like this in the command line:
% ln a_file_with_a_long_filename.pdf ~/path/to/a/new/hardlink/<Esc-,><Esc-,>

(The first keypress of Esc-,(or Alt+,) yields "~/path/to/new/hardlink/" like copy-prev-shell-word, and the second time it replaces that newly inserted word with "a_file_with_a_long_filename.pdf").

Here is a copy of copy-earlier-word document for a reference.

This widget works like a combination of insert-last-word and copy-prev-shell-word. Repeated invocations of the widget retrieve earlier words on the relevant history line. With a numeric argument N, insert the N th word from the history line; N may be negative to count from the end of the line.
If insert-last-word has been used to retrieve the last word on a previous history line, repeated invocations will replace that word with earlier words from the same line.
Otherwise, the widget applies to words on the line currently being edited. The widget style can be set to the name of another widget that should be called to retrieve words. This widget must accept the same three arguments as insert-last-word.
-- copy-earlier-word ZLE Function, widgets, zshcontrib(1)


text:
Q: Number formatting in pivot table with Aspose.Cells I am creating a pivot table in excel sheet by aspose.cells. I want the values to be formatted as Accounting, with a symbol, a comma and 2 decimal places. Is this possible with aspose.cells? Please suggest how to do this with Aspose.Cells and c#.

A: If you need Accounting number formatting for the PivotField, you may try to use the following numeric formatting using PivotField.Number attribute instead.
pivotTable.DataFields[0].Number = 43; //You may also try it with 44 if it suits your needs.

Alternatively you may try to use the following formatting string for NumberFormat custom attribute of PivotField. You may also check in MS Excel to get your desired custom strings to try with NumberFormat property.
_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)

If you still face any confusion/issue, can you please share the sample Excel file in which you may manually set the desired number formatting for the Pivot Table fields in MS Excel, and share the file with us, so that we can test the scenario at our end.
Furthermore, can you please share the code/sample application with the template files (input, output and expected output file etc.). The files can also be shared in Aspose.Cells product support forum.

A: Please try using PivotField.NumberFormat property to specify his desired formatting, see the code segment below for reference:
//Specify the number formatting to the first data field added.
pivotTable.DataFields[0].NumberFormat = "$#,##0.00";

Moreover, we also recommend you use our latest version of Aspose.Cells for .NET 7.4.0 in which we made some more enhancements regarding PivotTables.
PS, I am working as Support developer / Technical Evangelist at Aspose.


text:
Q: node-canvas on Heroku I have a discord.js bot and it runs on Heroku.
I added canvas just now, and now the bot is failing to build.
This is the log:
-----> Installing dependencies
       Prebuild detected (node_modules already exists)
       Rebuilding any native modules

       > canvas@2.6.1 install /tmp/build_c8ad4f45_/node_modules/canvas
       > node-pre-gyp install --fallback-to-build

       sh: 1: node-pre-gyp: Permission denied
       npm ERR! code ELIFECYCLE
       npm ERR! errno 126
       npm ERR! canvas@2.6.1 install: `node-pre-gyp install --fallback-to-build`
       npm ERR! Exit status 126
       npm ERR!
       npm ERR! Failed at the canvas@2.6.1 install script.
       npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

       npm ERR! A complete log of this run can be found in:
       npm ERR!     /tmp/npmcache.uZg6i/_logs/2021-01-01T17_53_37_239Z-debug.log
-----> Build failed

       We're sorry this build is failing! You can troubleshoot common issues here:
       https://devcenter.heroku.com/articles/troubleshooting-node-deploys

       Some possible problems:

       - node_modules checked into source control
         https://devcenter.heroku.com/articles/node-best-practices#only-git-the-important-bits

       - Node version not specified in package.json
         https://devcenter.heroku.com/articles/nodejs-support#specifying-a-node-js-version

       Love,
       Heroku

 !     Push rejected, failed to compile Node.js app.
 !     Push failed

I already installed node-pre-gyp as the log suggested, and nothing changed.
Here is package.json:
{
  "dependencies": {
    "canvas": "^2.6.1",
    "discord.js": "^12.4.1",
    "dotenv": "^8.2.0",
    "firebase": "^8.1.1",
    "firebase-admin": "^9.4.1",
    "node-pre-gyp": "^0.11.0"
  }
}

Does anyone know a solution to this?


text:
Q: Getting connection error while reading data from ElasticSearch using apache Spark & Scala I gave the following code
val conf = new org.apache.spark.SparkConf()
      .setMaster("local[*]")
      .setAppName("es-example")
      .set("es.nodes", "search-2meoihmu.us-est-1.es.amazonaws.com")

val sc = new org.apache.spark.SparkContext(conf)
val resource = "index/data"
val count = sc.esRDD(resource).count()
println(count)

using,
elastic search version=1.5.2
spark version=1.5.2
Scala version=2.10.4

and given library dependency as follows,
libraryDependencies += "org.elasticsearch" % "elasticsearch-spark_2.10" % "2.1.3"

I am getting following error while running the program
Exception in thread "main" org.elasticsearch.hadoop.rest.EsHadoopNoNodesLeftException: Connection error (check network and/or proxy settings)- all nodes failed

How can I read data from elastic search using spark and Scala?

A: Please look at the option "es.nodes.wan.only". By default, the value for this key is set to "false", and when I set it to true, that exception went away. Here is the current documentation for the configuration values: https://www.elastic.co/guide/en/elasticsearch/hadoop/current/configuration.html.
val conf = new org.apache.spark.SparkConf()
 .setMaster("local[*]")
 .setAppName("es-example")
 .set("es.nodes", "search-2meoihmu.us-est-1.es.amazonaws.com")
 .set("es.nodes.wan.only", "true")

Note that the doc specifies to flip this value to true for environments like those on AWS, but this exception happened for me when attempting to point to a VM with Elasticsearch running.


text:
Q: processing css stylesheet with xml document I am new to XML (a couple of days now...)and everything is going good, however, I can't seem to get the xml processed with css style
here is my perl...
#!/usr/bin/perl -w

use strict;
use warnings;
use diagnostics;
use Text::CSV_XS;

my $csv = Text::CSV_XS->new ({ binary => 1, auto_diag => 1 });
my $ifile="elementarray.csv";
my $ofile="elementarray.xml";
open my $fh, "<", $ifile or die $ifile.": $!";
open my $out, "> ".$ofile or die "Cannot write ".$ofile.": $!";

print $out <<EOT;
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="elementarray.xsl"?>
<?xml-stylesheet href="elementarray.css" title="Default style"?>
<EMAILCOMMENTS>
EOT

# First record contains list of fieldnames
#my $fields = $csv->getline($fh);
#print @$fields;
while (my $row = $csv->getline($fh)) {

    last unless $row && @$row;

    # Encode "<" characters as "<" and "&" as "&" in all fields
    foreach (@$row) {
    s/&/&/g;
    s/</</g;
    }

    # Create hash of fields using hash slice
    my %row;
    @row{"Subject","Body","From: (Name)","From: (Address)","To: (Name)","To:(Address)","Date","Time"} = @$row;

    print $out <<EOT;
    <EMAIL>

        <ORIGNAME>$row{"From: (Name)"}</ORIGNAME>
        <ORIGADDRESS>$row{"From: (Address)"}</ORIGADDRESS>
        <DESTNAME>$row{"To: (Name)"}</DESTNAME>
        <DESTADDRESS>$row{"To: (Address)"}</DESTADDRESS>
        <SUBJECT>$row{"Subject"}</SUBJECT>

    $row{"Body"}
    <DATE id="date">$row{"Date"}</DATE>
    <TIME id="time">$row{"Time"}</TIME>
    </EMAIL>
EOT
}
print $out "</EMAILCOMMENTS>\n";
$csv->eof or $csv->error_diag;
close $fh or die $ifile.": $!";
close $out or die $ofile.": $!";

Here is my xsl...
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output indent="yes" method="html"/>
    <xsl:template match="/">

                <title>E-mail</title>

                <xsl:apply-templates/>

    </xsl:template>
    <xsl:template match="HEADER">

            <xsl:value-of select="SUBJECT"/>

        From: <xsl:call-template name="formatEmail">
                <xsl:with-param name="address" select="ORIGADDRESS"/>
              </xsl:call-template>
        To: <xsl:call-template name="formatEmail">
                <xsl:with-param name="address" select="DESTADDRESS"/>
            </xsl:call-template>
    </xsl:template>
    <xsl:template match="EMAIL">
        <xsl:apply-templates select="HEADER"/>

            <xsl:value-of select="BODY"/>

        <xsl:attribute name="id"><xsl:value-of select="date"/></xsl:attribute>
        <xsl:value-of  select="DATE"/>

        <xsl:attribute name="id"><xsl:value-of select="time"/></xsl:attribute>
        <xsl:value-of  select="TIME"/>

    </xsl:template>
    <xsl:template name="formatEmail">
        <xsl:param name="address"/>

            <xsl:attribute name="href"><xsl:value-of select="concat('mailto:',$address)"/></xsl:attribute>
            <xsl:value-of select="$address"/>

    </xsl:template>
</xsl:stylesheet>

here is my xml (1 record)...
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="elementarray.xsl"?>
<?xml-stylesheet href="elementarray.css" title="Default style"?>
<EMAILCOMMENTS>
    <EMAIL>

        <ORIGNAME>William Holt</ORIGNAME>
        <ORIGADDRESS><x@gmail.com></ORIGADDRESS>
        <DESTNAME>X</DESTNAME>
        <DESTADDRESS>bill@elementarray.com</DESTADDRESS>
        <SUBJECT>welcome to the neighborhood</SUBJECT>

    just thought i'd say hello
    <DATE id="date">07/18/2013</DATE>
    <TIME id="time">11:53</TIME>
    </EMAIL>
</EMAILCOMMENTS>

and here is css (  style for just to see if it is working, and it isn't :(  )...
DATE{background-color:red;}
TIME{background-color:green;}
#date{background-color:yellow;}
#time{background-color:blue;}
BODY{background-color:grey;}

Sorry for the length of the post but I think you need all these files...

A: Although you can indeed style XML with CSS, using the xml-stylesheet processing instruction you have included in your XML, you can't transform it with XSLT at the same time. That is to say you should only really have one stylesheet processing instruction in your XML. Either you simply style your XML with CSS (which is not really a common thing to do), or your transform it to HTML with XSLT and style the HTML output with CSS.
In the latter case, remove the <?xml-stylesheet href="elementarray.css"?> instruction from your XML document, and instead output a reference to the CSS document in your first template.
<xsl:template match="/">

            <title>E-mail</title>
            <link href="elementarray.css" type="text/css" rel="stylesheet" />

            <xsl:apply-templates/>

</xsl:template>

Now, in your CSS, I see you already have selectors for the date and time ids, so you need to ensure the relevant elements in your HTML have these ids.
At the moment, you are doing this in your XSLT

    <xsl:attribute name="id"><xsl:value-of select="date"/></xsl:attribute>
    <xsl:value-of  select="DATE"/>

But this is setting the id attribute to have the value of the date element in your XML, but such an element does not exist! I think you meaning to use the literal string here. Now, you could do this...
<xsl:attribute name="id"><xsl:value-of select="'date'"/></xsl:attribute>

But this is verbose. You can just do this:
<xsl:attribute name="id">date</xsl:attribute>

But better still, just write it out as an attribute in the normal way:

       <xsl:value-of  select="DATE"/>

And similarly for 'time'. This should ensure the two span tags get styled using your CSS in the HTML you output.


text:
Q: RequireJS effecting an embedded jquery-ui widget I have a jQuery widget that are partner is trying to embed. The problem we are getting is the partner is using requireJS and its effecting the widget.
The widget is in an anonymous function and requires jquery-ui within. After debugging we have found that jQuery UI is being removed after the noConflict call. Here is the code from the widget.
(function () {

    // Localize jQuery variable
    var jQueryWidget;

    /******** Load jQuery if not present *********/
    if (window.jQuery === undefined || window.jQuery.fn.jquery !== '3.2.1') {
        var script_tag = document.createElement('script');
        script_tag.setAttribute("type", "text/javascript");
        script_tag.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js");
        script_tag.onload = scriptLoadHandler;
        script_tag.onreadystatechange = function () { // Same thing but for IE
            if (this.readyState == 'complete' || this.readyState == 'loaded') {
                scriptLoadHandler();
            }
        };
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
    } else {
        loadJQueryUi();
    }

    function scriptLoadHandler() {
        loadJQueryUi();
    }

    function loadJQueryUi() {
    /******* Load UI *******/
        jQuery.getScript('https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js', function () {
          jQueryWidget = jQuery.noConflict(true);
          setHandlers(jQueryWidget);
        });

        /******* Load UI CSS *******/
        var css_link = jQuery("<link>", {
            rel: "stylesheet",
            type: "text/css",
            href: "https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/base/jquery-ui.css"
        });
        css_link.appendTo('head');
    }

    function setHandlers($) {
        $(document).on('focus', '#start-date, #end-date', function(){

      $('#start-date').datepicker({
        dateFormat: "M dd, yy",
        minDate: 'D',
        numberOfMonths: 1,
      });

            $('#end-date').datepicker({
                dateFormat: "M dd, yy",
                minDate:'+1D',
                numberOfMonths:1,
            });
    }
})();

Using chrome debugger we can see that when the getScript is called it correctly adds jquery-ui to the loaded version. Its straight after we call the noConflict that it restores the previous jQuery but are version no longer has jQueryUI.
Testing the widget on others sites without requireJS works correctly.
Has anyone came across this before? Unfortunately we have not worked with RequireJS before but cant see why it would effect are anonymous function.
Any help would be really appreciated.

A: The problem is that what you are trying to do is unsafe. There are two factors that, combined, work against you:

*

*Scripts are loaded asynchronously. The only thing you control is the relative order in which your widget loads jQuery and jQueryUI. However, the page in which your widget operates also load its own version of jQuery. Your code cannot coerce the order in which scripts loaded by the partner code are going to load.

*jQuery is not a well-behaved AMD module. A well-behaved AMD module calls define to gets its dependencies and it does not leak anything into the global space. Unfortunately, jQuery does leak $ and jQuery into the global space.
With these two factors combined, you are facing a race condition depending on which order the two versions of jQuery are loaded: it is generally impossible to know which version of jQuery the global symbols $ and jQuery are referring to. Consider your code:
jQuery.getScript('https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js', function () {
  jQueryWidget = jQuery.noConflict(true);
  setHandlers(jQueryWidget);
});

You cannot know whether jQuery refers the version you asked be loaded or to the version that the partner code wanted to load. The only thing .getScript guarantees is that the callback will be called after the script is loaded, but it does not prevent other scripts from loading between the script that .getScript loads and the time the callback is called. The browser is absolutely free to load the script you give to .getScript, load some other script that was requested through RequireJS, and then call your callback.
If you want your widget to be something that can be plopped into a page without having to change any of the existing code, then there's no simple fix. You cannot just change the logic you show in your question, nor can you just add RequireJS to your widget. RequireJS cannot by itself fix this. Contrarily to what the other answer suggest, the context configuration option for RequireJS is not a fix. It would be a fix if there were no scripts that try to access jQuery through the global $ or jQuery, but there are a dozens of plugins for jQuery that do just that. You cannot ensure that the partner code does not use them.
And beware of proposed fixes that seem to fix the problem. You can try a fix, and it seems to work, and you think the problem is solved but really the problem is not manifesting itself because, well, it is a race condition. Everything is fine, until one month later, another partner loads your widget and boom: their page creates just the right conditions to cause things to load in an order that screws up your code.
There is an additional complication which you may not have run into yet but is bound to happen from time to time. (Again, you are dealing with race conditions, so...) You code is loading jQuery and jQuery UI through script elements. However, they both check whether define is available, and if so, they will call define. This can cause a variety of problems depending on the order in which everything happens, but one possible issue is that if RequireJS is present before your widget loads, jQuery UI will call define from a script element and this will give rise to a mismatched anonymous define error. (There's a different issue with jQuery, which is more complicated, and not worth getting into.)
The only way I can see to get your widget to load without interference from the partner code, and without requiring the partner to change their code would be to use something like Webpack to build your code into a single bundle in which define should be forced to be falsy in your bundle so that any code that tests for the presence of define is not triggered. (See import-loader, which can be used for this.) If you load your code as a single bundle, then it can initialize itself in a synchronous manner, and you can be sure that $ and jQuery refer to the jQuery you've included in your bundle.

If you are going to follow my advice here is a nice example, that takes full advantage of Webpack, includes correct minification, and eliminates some artifacts from your code that are no longer needed with this approach (for instance the IIFE, and some of the functions you had). It is runnable locally by saving the files, running:

*

*npm install webpack jquery jquery-ui imports-loader lite-server

*./node_modules/.bin/webpack

*./node_modules/.bin/lite-server
And there's something I did not realize when I first wrote my explanation but that I noticed now. It is not necessary to call noConflict when you wrap your code with Webpack because when it is wrapped by Webpack, jQuery detects a CommonJS environment with a DOM and turns on a noGlobal flag internally which prevents leaking into the global space.
webpack.conf.js:
const webpack = require('webpack');
module.exports = {
    entry: {
        main: "./widget.js",
        "main.min": "./widget.js",
    },
    module: {
        rules: [{
            test: /widget\.js$/,
            loader: "imports-loader?define=>false",
        }],
    },
    // Check the options for this and use what suits you best.
    devtool: "source-map",
    output: {
        path: __dirname + "/build",
        filename: "[name].js",
        sourceMapFilename: "[name].map.js",
    },
    plugins: [
        new webpack.optimize.UglifyJsPlugin({
            sourceMap: true,
            include: /\.min\.js$/,
        }),
    ],
};

Your widget as widget.js:
var $ = require("jquery");
require("jquery-ui/ui/widgets/datepicker");

var css_link = $("<link>", {
    rel: "stylesheet",
    type: "text/css",
    href: "https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/base/jquery-ui.css"
});
css_link.appendTo("head");

$(document).ready(function() {
    console.log("jQuery compare (we want this false)", $ === window.$);
    console.log("jQuery version in widget",  $.fn.jquery);
    console.log("jQuery UI version in widget", $.ui.version);
    $("#end-date").datepicker();
});

index.html:
<!DOCTYPE html>

    <input id="end-date">

A:  I think problem is with jQueryWidget = jQuery.noConflict(true);
true means remove all jQuery variables from the global scope.

jQuery.noConflict( [removeAll ] )
  removeAll
  Type: Boolean
  A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself).

[noconflict][1]
One thing we can try removing the true boolean parameter, Let know if it helps.

UPDATE 2:
    Below approach should not require any partner code changes

<!DOCTYPE html>

            <title></title>

FOCUS
                <input type="text" name="" id="end-date" />

            <button id="btn" style="width: 100px; height:50px; margin:10px">click me</button>

I have modified the plugin code, so that it uses its own jquery and jquery ui version(I am making use of the requirejs here).
Also for demo I have added a sample partner script which gives alert on button click. you can see without modifying the partner code and requirejs    config, plugin can work now.
Both plugin and partner code have there independent jquery and jquery ui versions.
Hope this helps.
References: Using Multiple Versions of jQuery with Require.js
and
http://requirejs.org/docs/api.html#multiversion
UPDATE3: using webpack and imports loader
We can use webpack to bundle the plugin js code in that case plugin will have its own version of jquery, we have to change the way the plugin is being build.
Install webpack, jquery, imports loader and jquery-ui using npm and build it, below is the sample code:
main.js used imports loader to make define as false
require('imports-loader?define=>false!./app.js');

app.js which includes the plugin code and it adds the required dependencies
 (function() {

     var $ = require('jquery');
     require('jquery-ui');
     require('jquery-ui/ui/widgets/datepicker.js');

     function scriptLoadHandler() {
         loadJQueryUi();
     }

     $(document).ready(function() {
         scriptLoadHandler();
     });

     function loadJQueryUi() {
         setHandlers();
         var css_link = $("<link>", {
             rel: "stylesheet",
             type: "text/css",
             href: "https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/base/jquery-ui.css"
         });
         css_link.appendTo('head');
     }

     function setHandlers() {
         $('#end-date').on('click', function() {
             alert('JQUERY--' + $().jquery);
             alert('JQUERY UI--' + $.ui.version);
             $('#end-date').datepicker({
                 dateFormat: "M dd, yy",
                 minDate: '+1D',
                 numberOfMonths: 1,
             });
         });
     }
 })();

webpack.config.js
  var webpack = require('webpack');

  module.exports = {
  entry: "./main.js",
  output: {
  filename: "main.min.js"
     }
  };

sample.html
<!DOCTYPE html>

    <title></title>

FOCUS
        <input type="text" name="" id="end-date" />

    <button id="btn" style="width: 100px;"></button>

after doing a webpack it will generate a main.min.js file which is included in the sample.html file