text:
Q: Haskell split user input I want to take first three elements from user input in Haskell, but I got error message.
Thank you for the help
 getCmd cmd = do
    putStrLn take 3 cmd

 main = do
    putStrLn "please type something"
    name <- getLine
    if name /= "QUIT" then do
        getCmd(name)
        main
    else
        return()

A: Your definition of getCmd should be:
getCmd cmd = do
    putStrLn (take 3 cmd)

function application is left-associative so your definition is parsed as
(((putStrLn take) 3) cmd)

so you need to add the brackets so putStrLn is applied to the result of applying take.
Haskell also defines the $ infix operator which has a lower precedence than function application so it is commonly used instead of using brackets. Your use of do is also redundant so you can define getCmd as
getCmd cmd = putStrLn $ take 3 cmd

or even
getCmd = putStrLn . take 3


text:
Q: How to connect SOAP server and JSON client through Spring Integration? Good day. I am new to spring integration. I wrote a simple SOAP server, and I need to connect a client that communicates through JSON and a server that communicates via SOAP, but I've got confused in the technology that this framework provides. As I understand it there are JsonToObjectTransformer and ObjectToMapTransformer transformers. As I understand it is necessary to transform the data before transmitting it to the controller. Is it possible to do this with the help of transformers, or I can use other technologies in the spring integration. And can this be done only with the help of DSL?
Controller:
@Endpoint
public class CityEndpoint {
    private static final String NAMESPACE_URI = "http://weather.com/senchenko";
    private CityRepository cityRepository;

    @Autowired
    public CityEndpoint(CityRepository cityRepository) {
        this.cityRepository = cityRepository;
    }

    @PayloadRoot(namespace = NAMESPACE_URI, localPart = "getCityRequest")
    @ResponsePayload
    public GetCityResponse getCityResponse(@RequestPayload GetCityRequest request){
        GetCityResponse response = new GetCityResponse();
        response.setCity(cityRepository.findCity(request.getName()));
        return response;
    }
}

Config:
@EnableWs
@Configuration
public class WebServiceConfig extends WsConfigurerAdapter {
    @Bean
    public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
        MessageDispatcherServlet servlet = new MessageDispatcherServlet();
        servlet.setApplicationContext(applicationContext);
        servlet.setTransformWsdlLocations(true);
        return new ServletRegistrationBean(servlet, "/ws/*");
    }

    @Bean(name = "city")
    public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema citySchema) {
        DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
        wsdl11Definition.setPortTypeName("CityPort");
        wsdl11Definition.setLocationUri("/ws");
        wsdl11Definition.setTargetNamespace("http://weather.com/senchenko");
        wsdl11Definition.setSchema(citySchema);
        return wsdl11Definition;
    }

    @Bean
    public XsdSchema citySchema() {
        return new SimpleXsdSchema(new ClassPathResource("xsd/weather.xsd"));
    }

    @Bean
    @Transformer()
    JsonToObjectTransformer jsonToObjectTransformer() {
        return new JsonToObjectTransformer();
    }

    @Bean
    @Transformer()
    ObjectToMapTransformer objectToMapTransformer(){
        return new ObjectToMapTransformer();
    }
}

Addition
I solved the problem with redirection to SOAP, but still do not know the best way to convert JSON into an SOAP Envelope and back.
@Bean
    public IntegrationFlow httpProxyFlow() {
        return IntegrationFlows
                .from(Http.inboundGateway("/service"))
                .transform(t -> TEST_ENVOLOPE)
                .enrichHeaders(h -> h.header("Content-Type", "text/xml; charset=utf-8"))
                .handle(Http.outboundGateway("http://localhost:8080/ws")
                        .expectedResponseType(String.class))
                .transform(t -> TEST_RESPONSE)
                .get();
    }

A: Your question isn't clear or you are not fully familiar with technologies you need to work.
The SOAP is fully about XML messages exchange. On the server side you have a specific MessageDispatcherServlet which converts an incoming HTTP request to the SOAP envelop fully in XML. There is just nothing about JSON at all.
Your CityEndpoint.getCityResponse() is triggered by the Spring WS Framework when an incoming SOAP request is unmarshalled from the XML into the domain model via JaxB according your XSD definition and generated model. There is just nothing about Spring Integration at all.
Your JsonToObjectTransformer and ObjectToMapTransformer just don't make any sense in this scenario. They are not involved in the SOAP request process.
Sorry to disappoint you in my answer, but it even not clear by your question how that JSON client is going to call SOAP service when JSON and XML are fully different and not compatible protocols.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Como verificar e pegar o valor 0 ou 1 de uma string e guardar aquele numero para aquela coluna? Tenho que guardar o número 0 em uma variável desc e 1 na variável asc, caso um desses valores sejam encontrados na string.
Como eu faço isso?
package testes;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Ordenar {

public static void main(String[] args) {

      String desc = null;
      String asc = null;
      String coluna = null;
      List list = new ArrayList();
      String sampleString = "jrp_jasper.jrp_jas_nome|0;jrp_jasper.jrp_jas_sobrenome|1";

      String[] items = sampleString.split(";");
     // List<String> itemList = Arrays.asList(items);
      for(int i = 0; i < items.length; i++){

         if(sampleString.charAt(i) == '0'){
             desc = "0";
             System.out.println(desc);
         }else{
             asc = "1";
             System.out.println(asc);
         }

         coluna = items[i].replaceAll("[|01]", "");
         Map map = new HashMap();
         map.put(coluna, asc);
         list.add(coluna);

         // ....

A: Troque a validação do seu if, usando contains sobre um item do vetor de strings items:
if(items[i].contains("0")){
    desc = "0";
    System.out.println(desc);
}else if((items[i].contains("1"))){
    asc = "1";
    System.out.println(asc);
}


text:
Q: Generate Complex Pyspark table involving Array, Pivot I have a table in the following format
+-------+--------+
|Column1|Column2 |
+-------+--------+
|[A, 1] |X       |
|[A, 1] |Y       |
|[B, 2] |Y       |
|[B, 2] |Z       |
|[C, 1] |X       |
|[C, 1] |Z       |
+-------+--------+

I need a table with the following result:
+-------+-------+-------+-------+
|       |[A, 1] |[B, 2] |[C, 1] |
+-------+-------+-------+-------+
|[A, 1] |[X, Y] |[Y]    |[X]    |
|[B, 2] |[Y]    |[Y, Z] |[Z]    |
|[C, 1] |[X]    |[Z]    |[X, Z] |
+-------+-------+-------+-------+

Or even better will be a result like this:
+-------+-------+-------+-------+
|       |[A, 1] |[B, 2] |[C, 1] |
+-------+-------+-------+-------+
|[A, 1] |2      |1      |1      |
|[B, 2] |1      |2      |1      |
|[C, 1] |1      |1      |2      |
+-------+-------+-------+-------+

A: This will be expensive, especially for large data, but you can do join + pivot:
from pyspark.sql.functions import count

df.alias("l").join(df.alias("r"), on="Column2")\
    .select("l.Column1", "r.Column1")\
    .groupBy("l.Column1")\
    .pivot("r.Column1")\
    .agg(count("r.Column1"))\
    .show()
#+-------+------+------+------+
#|Column1|[A, 1]|[B, 2]|[C, 1]|
#+-------+------+------+------+
#| [A, 1]|     2|     1|     1|
#| [B, 2]|     1|     2|     1|
#| [C, 1]|     1|     1|     2|
#+-------+------+------+------+


text:
Q: Calculation of alarm level for a signal detection in Poisson distributed noise I am trying out my luck with the first post here...
Well, to start off I have a problem, and I am not really sure about the solution. I hope that someone might chime in with suggestions..
We have an ionizing radiation detector. It is sampling the radiation induced counts each second. The counts in the detector are Poisson distributed. Then, a source might pass the detector giving rise to the number of counts in the detector for some time. We want to have a threshold for counts in the detector, which when passed would indicate that there is a source nearby. The question is whether we are correctly estimating the threshold for a certain detection criteria set for a given number of false alarms.
For example, given, that the total survey time is one hour there are 3600 individual measurements in total. We want to set the threshold of detection to 1 false alarm per hour or 1 in every 3600 measurements. Due to the fact, that the counts in the detector are Poisson distributed around the mean of $\lambda_\text{bkg}$, we can estimate the threshold level $N_\text{alarm}$ using Poisson CDF for a probability of $P_\text{alarm}=1-\frac{1}{3600}$.
To do that, I am using qpois(lambda,p) function in R. As far as I understand it should yield correct alarm level.
Testing the results using a number of simulated one-hour measurements yields average probability of any number of alarms of around 25% for a given one-hour survey. For a number of alarms greater than one, the probability is around 3%.
Is this correct? Or maybe I missing something?


text:
Q: Minify RequireJS modules that were loaded afterwards I'm building up a medium sized Single Page WebApp on the basis of RequireJS and a .NET Backend, which handles the Ajax "page changes" for me.
Each time a page is loaded for the first time, a module controller (JS) loads the corresponding JS-Module.
I'm working in SublimeText 2 and have built up a configuration that compiles and minifies my JS on save into one single file. The configuration is saved in a require.config call.
This works fine for all the dependencies that are trackable by RequireJS. However I'd like to improve the build process to also minify modules (best would be folders) that are not directly required and be saved separately in another folder.
Here is my RequireJS Config:
require.config({
    appDir: ''
,   paths: {
        'jquery': [
            '//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min'
        ,   'lib/jquery'
        ]
    ,   'underscore': [
            '//raw.github.com/documentcloud/underscore/master/underscore-min'
        ,   'lib/underscore'
        ]
    ,   'modernizr': 'lib/modernizr'
    ,   'jquery-ui': 'lib/jquery-ui'
    }
,   shim: {
        'jquery-ui': { deps: ['jquery'] }
    ,   'lib/jquery-tablesorter': { deps: ['jquery'], exports: 'jQuery.fn.tablesorter' }
    ,   'underscore': { exports: '_' }
    }
,   exclude: ['jquery', 'jquery-ui', 'underscore']
,   name: 'main'
,   out: '../min/main.js'
,   optimize: 'none'
});

require(['jquery', 'modules/ModuleController', 'jquery-ui', 'util/Log'],
    function($, Controller) {
        // jQuery was extended by jqueryUI
        // window.log is now accessible

        $(function(){
            Controller.setup({
                objGlobal: window.RecruitingApp
            });
        })
});

My folder structure looks like this:
/AppRoot
    /dev
        /lib
        /modules
        /util
        build.js
        main.js
    /min
        /lib
        /* here i'd like to have a generated modules folder with the minified modules */
        main.js

The Module Loader looks like this:
define(['jquery', 'underscore'], function($, _) {
    var i = {
    };

    var o = {
        objGlobal: null
    };

    var objModules = {};

    var setup = function(options) {
        o = $.extend(o, options);

        o.objGlobal.moduleListener = function(module) {
            require(['modules/'+module+''], function(Module){
                if(objModules.module && _.isFunction(objModules.module.destroy)) {
                    objModules.module.destroy();
                }

                o.objGlobal.currentModule = module;
                objModules.module = Module;
                Module.setup();
            });
        };

        o.objGlobal.moduleListener(o.objGlobal.currentModule);
    }

    // method interface
    i.setup = setup;

    return i;
});

Is it possible to change the RequireJS Config File to automatically minify every file in a folder and save them in a corresponding folder?

A: As I understood, you are already using require.js optimization tool "r.js".
r.js has two ways of optimizing your code, first way is when you want to optimize single module and it's dependencies into single js file, and second approach is to optimize whole project/multiple modules.
You can achieve that by using "modules" option in you r.js build config. Take a look here.


text:
Q: What is the optimal way to handle this type of exceptions? This is a sample block from my code.
...
try {
    race.setDate(new Date(dateFormat.parse(entry[5]).getTime()));
    race.setTime(Time.valueOf(entry[6]));
    race.setFp1Date(new Date(dateFormat.parse(entry[8]).getTime()));
    race.setFp1Time(Time.valueOf(entry[9]));
    race.setFp2Date(new Date(dateFormat.parse(entry[10]).getTime()));
    race.setFp2Time(Time.valueOf(entry[11]));
    race.setFp3Date(new Date(dateFormat.parse(entry[12]).getTime()));
    race.setFp3Time(Time.valueOf(entry[13]));
    race.setQualiDate(new Date(dateFormat.parse(entry[14]).getTime()));
    race.setQualiTime(Time.valueOf(entry[15]));
    race.setSprintDate(new Date(dateFormat.parse(entry[16]).getTime()));
    race.setSprintTime(Time.valueOf(entry[17]));
} catch (ParseException e) {
    throw new RuntimeException(e);
}
...

Here every line in the try block can throw exception. According to my requirement if entry[i] is unparsable then the setter should set the value as null rather than throwing the exception. Putting every line in a try-and-catch block doesn't seem an optimal solution.
How can I optimally handle this situation rather than checking the value of entry[i] in every line?

A: Write a function which will catch a ParseException and return null:
    static <T> T parseOrNull(Supplier<T> parser) {
        try {
            return parser.get();
        } catch (ParseException e) {
            return null;
        }
    }

Then call it in each of your lines:
...
            race.setDate(parseOrNull(()  -> new Date(dateFormat.parse(entry[5]).getTime())));
...

A: You can introduce new interface
interface Parser<T> {
    T parse(String value) throws ParseException;
}

then create helper function
    private static <T> void safeSet(Consumer<T> c, Parser<T> parser, String value){
        try {
            c.accept( parser.parse(value));
        } catch (ParseException e) {
            // log parse error
        }
    }

and use it in a following way:
       safeSet( race::setDate, x-> new Date(dateFormat.parse(x).getTime()), entry[5]);

Additional bonus you can reuse parsers:
       Parser<Date> dateParser = x -> new Date(dateFormat.parse(x).getTime());
       safeSet(race::setDate, dateParser, entry[5]);
       safeSet(race::setFp1Date, dateParser, entry[8]);


text:
Q: Force Compass to use .sass syntax? Is there a way to force Compass to use the Sass syntax instead of SCSS?

A: For new projects, run:
compass create path/to/project --syntax sass
to generate .sass files using Sass syntax inside the sass folder. The --syntax option and others are listed when you run compass --help.
For existing projects, add the following to your Compass config.rb:
preferred_syntax = :sass
That's covered in the Compass configuration reference. And you'll want to run your existing SCSS files through sass-convert to generate new ones which use Sass syntax.


text:
Q: Modifying nth li in a list using jquery I'm trying something very basic, but I just can't figure out why this won't work.
I can get information on the object using [i] but I can't change data this way?
    // Make all the li's invisible
$('div#rotator ul li').css({opacity: 0.0});

// Calculate a random number between 1 and 3
var randnr = Math.floor((1-4)*Math.random()) + 4;

for(var i = 0; i < $('#rotator ul li').length; i++) {

            // Make the i element appear
    $('#rotator ul li')[i].css({opacity: 1.0});
}

A: jQuery objects are array-like objects that can be used as an array of raw DOM elements.
Therefore, $(...)[i] gets the i'th raw DOM element, not a jQuery object containing it.
To get a jQuery object containing the i'th element, call the .eq() method, like this:
$('#rotator ul li').eq(i).css({opacity: 1.0});

You can also use the :eq selector:
$('#rotator ul li:eq(i)').css({opacity: 1.0});

However, you don't need a loop at all; you can hide all of the elements at once:
$('div#rotator ul li').css({opacity: 1.0});

A: You are getting this problem because when you use array indices you get a DOM element and css() is a method on a jQuery object. So you can do:
$($("#rotator ul li")[i]).css("opacity", 1.0);

Of course that's awkward so you can use eq():
$("#rotator ul li").eq(i).css("opacity", 1.0);

But you're doing that change in all elements in the set so a simpler solution than a loop is to simply do:
$("#rotator ul li").css("opacity", 1.0);

That will apply the CSS to all elements in the jQuery object.


text:
Q: return a list from a complex string I start with haskell.
I was wondering if I can convert a string to a list of different element's type like that : "1*30%4" -> ['1', '*', '30', '%', '4'] without Parsec
I have already found answers but none really help me...
like map (:[]) "1*30%4"with GHCI
or with the help of intersperse.
but I do not know how to keep the right formats, I can not, for example, have numbers or float/double in my list because everything is cut one by one : "1*30%4" -> ['1', '*', '3', '0', '%', '4'] or "1*30.4%4" -> ['1', '*', '3', '0', '.', '4', '%', '4']
Someone can help me ?

A: As some users have pointed out, your returning type is [String] instead of [Char]. You can easily achieve this by the following:
import Data.Char
import Data.List

expresionToList :: String -> [String]
expresionToList = groupBy readAsNumber
  where readAsNumber c d = pred c && pred d
        pred x = isDigit x || x == '.'

*

*pred function returns True when its input is a digit or a dot, False otherwise

*readAsNumber takes two returns True if both are a digit or a dot

*finally you group your string by readAsNumber


text:
Q: Change appearance of links with plotly/dash I'm working with Dash to build a dashboard. Consider the following code:
def get_index():
    index = html.Div([
        dcc.Link('Page 1', href='/page-1'),
        html.Br(),
        dcc.Link('Page 2', href='/page-2')
    ], style = {'display':'inline-block','columnCount': 2})
    return index

This gives me the following output in my app:

Question: How do I remove the bar below the links and change the font and color?
Thanks!

A: You can customize the links by adding style as a named argument, e.g.
dcc.Link('Page 1', href='/page-1',
         style={'font-family': 'Times New Roman, Times, serif', 'font-weight': 'bold'})

The style argument is just regular CSS.
Adding external CSS to your Dash app is preferable in my opinion because you can separate code logic and layout.


text:
Q: file modified by opening I am using MMA version 11.3.0. There are some notebooks that, right after being opened, change to modified. That is, their name in the title bar has an asterisk appended and, when I try to close it, it shows the "Save changes" dialog. As far as I can tell, there is no dynamic content.
Is there a way to prevent that behavior? I want to open a notebook and be able to close it immediately without having to save it.


text:
Q: Is the Sum and Absolute Difference of two positive Integers Unique? Question:
Is the combination of Sum and Absolute Difference of 2 positive integers unique to that combination of integers?
Assume $X$ and $Y$ are positive integers AND $X \neq Y$.
I think that we all agree that: $X + Y = Y + X$ AND $|X - Y| = |Y - X|$
However I don't think there is any other positive integers ($A$ and $B$, $A \neq B$) where $A + B = X + Y$ AND $|A - B| = |X - Y|$ AND ($A \neq X$ OR $A \neq Y$) AND ($B \neq X$ OR $B \neq Y$) )
Background
Over on the DBA Stack Exchange there is a question asking for ensuring the uniqueness of a relationship.  In the specific implementation it is really a comparison of 2 positive integers that represent objects in a relationship.
Lets say for example that we are modeling that Kirk and Victoria are friends.  If Kirk = 1 and Victoria = 2 in this table, then I need on instance of either [1,2] or [2,1] but I don't need both.  (Since it can be inferred that if Kirk is friends with Victoria, that Victoria is also friends with Kirk)
Another avenue for testing I was attempting is to use some basic arithmetic to create a summary of the 2 integers (which computers can calculate and compare quickly).  I ran a test of all combinations of positive integers from 1 - 10,000 and logged the Sum, Product and Absolute Difference of the 2 integers.
It appeared from my testing that the Combination of Sum and Absolute Difference was unique for the combination.  EX: The Sum and Absolute Difference of [1,2] and [2,1] were the same, but was not shared with any other pair of [x,y] and [y,x].
In my head this makes sense, because you can make changes to the two integers in question to create the same Sum or Absolute Difference but that would change the value for the other attribute.  EX: [2,5] as a Sum of 7 and an Absolute Difference of 3.  [1,6] has the same Sum but a different Absolute Difference, and [3,6] has the same Absolute Difference but a different Sum.
I am assuming I am not the first person to see this relationship and this has either been proven to be true or this has been proven to be false, and I either did not find the cases where it is false or my comparison methods were wrong.

A: Welcome to Mathematics Stack Exchange.
Assume without loss of generality that $X\ge Y$, so $|X-Y|=X-Y$.
(If not, switch $X$ and $Y$.)
If $X+Y=S$ and $X-Y=D$, then $X=\dfrac{S+D}2$ and $Y=\dfrac{S-D}2$,
so $X$ and $Y$ are indeed uniquely determined by $S$ and $D$.

A: Let us solve $s=x+y,d=|x-y|$ for $x,y$. We eliminate $y$ and get
$$d=|2x-s|$$ or $$2x-s=\pm d.$$
So
$$x=\frac{s+d}2,y=\frac{s-d}2$$ or$$x=\frac{s-d}2,y=\frac{s+d}2.$$
This shows that there are exactly two solutions.

Let us play the same game with sum and product: $s=x+y,p=xy$.
Multiplying by $x$,
$$sx=x^2+xy$$ or
$$x^2-sx+p=0.$$
By solving the quadratic equation,
$$x=\frac{s\pm\sqrt{s^2-4p}}2,y=\frac{s\mp\sqrt{s^2-4p}}2.$$

In both cases, the two solutions are deduced from each other by exchanging $x$ and $y$. This is due to the symmetry of the equations (commutativity).


text:
Q: find webelement that contains unknown span text I have this html snippet here.

This is what I want to achieve, after a user input a value, use the input value to check which PagePostsSectionPaglet contains it, find the PagePostsSectionPaglet and find the className("_5sem") that is in the same PagePostsSectionPaglet
get a list of text from webelement

//compare a list of text in PagePostsSectionPaglet with unknown user input
if text in PagePostsSectionPaglet = input year
{
    find PagePostsSectionPaglet that contains text that is same with input year
    go through same PagePostsSectionPaglet and find className="_5sem">
    {
       find UFIPagerLink  //inside class="_5sem"
       find UFIPagerIcon  //inside class="_5sem"
    }
}

Problem how to findwebelements PagePostsSectionPagelet that consists user input "text" instead of specific value?
tried different ways but all have this SyntaxError: The expression is not a legal expression.
List <WebElement> PagePostsSectionPagelet = elm.findElements(By.xpath("//*[starts-with(@id, 'PagePostsSectionPagelet')]//contains('"+elm.getText()+"')"));

List <WebElement> PagePostsSectionPagelet = elm.findElements(By.xpath("//*[starts-with(@id, 'PagePostsSectionPagelet')]//span[elm.getText()]"));

my codes
    //tried to print the list of texts in AllPagePostsSectionPagelet but only returns the first value
    List <WebElement> AllPagePostsSectionPagelet= dr.findElements(By.xpath("//*[starts-with(@id, 'PagePostsSectionPagelet')]//span[@class='_5em9 lfloat _ohe _50f4 _50f7']"));

    for (WebElement elm : AllPagePostsSectionPagelet){
        if(year.equals(elm.getText())){  //year is the user input value
            //get weblement that contains the text
            List <WebElement> PagePostsSectionPagelet = elm.findElements(By.xpath("//*[starts-with(@id, 'PagePostsSectionPagelet')]//elm.getText()")); //this is the issue
            System.out.println(PagePostsSectionPagelet);
            for (WebElement elment : PagePostsSectionPagelet){
                List<WebElement> comments = elment.findElements(By.className("_5sem")); //find web element

                //iterate through the comments
                for (WebElement comment : comments) {

                       //find web elements by their respective class name
                       List<WebElement> commentsbutton = comment.findElements(By.className("UFIPagerLink"));
                       List<WebElement> repliesbutton = comment.findElements(By.className("UFIPagerIcon"));
                }
            }
        //return;
        }
    }

A: This is what I understood from your question (Please correct me if I'm wrong), you are trying to search for a specific div tag which satisfies 2 conditions:

*

*has an id="PagePostsSectionPagelet"

*and within that tag there should be a span tag which matches the value entered by the user (eg: 2014)

Now, within that div tag, you want to fetch another div tag with class="_5sem".
If what I've explained matches with what you are trying to achieve, then the xpath given below should work for the HTML source you've provided above.
"//span[text()='2014']/ancestor::div[contains(@id, 'PagePostsSectionPagelet')]//div[@class='_5sem']"

The Java code which you've provided can be reduced to:
//year is the user input value
String xp = "//span[text()='" + year + "']/ancestor::div[contains(@id, 'PagePostsSectionPagelet')]//div[@class='_5sem']";

WebElement comment = driver.findElement(By.xpath(xp));
// Add code to fetch 'UFIPagerLink' and 'UFIPagerIcon'
// which should be inside the div tag with class="_5sem"


text:
Q: SQL for a generated table with column 1 a sequence of numbers and column 2 a running sum What would be the SQL (standard, or any major variant) to produce a table like the following?
1   1   -- 1
2   3   -- 2+1
3   6   -- 3+2+1
4   10  -- 4+3+2+1
5   15  -- 5+4+3+2+1
6   21  -- 6+5+4+3+2+1

... ...
The second column is the sum of the numbers in the first.
I couldn't get past this:
select rownum from all_objects  where rownum <= 10;

Which produces column 1 (PL/SQL)
Tried to think on the following lines but clearly it is wrong, even syntactically:
select rownum, count(t2.rownum)
 from
 (select sum(rownum) from all_objects  where rownum <= 10) t2,
 all_objects
 where rownum <= 10;

A: It is simple math:
select rownum, rownum * (rownum + 1) / 2
from all_objects
where rownum <= 10;

A: You don't need to hit the all_objects view; you could use a hierarchical query:
select level as position, sum(level) over (order by level) as running_sum
from dual
connect by level <= 10;

  POSITION RUNNING_SUM
---------- -----------
         1           1
         2           3
         3           6
         4          10
         5          15
         6          21
         7          28
         8          36
         9          45
        10          55

or using @forpas' arithmetic-series method:
select level as position, level * (level + 1) / 2  as running_sum
from dual
connect by level <= 10;

  POSITION RUNNING_SUM
---------- -----------
         1           1
         2           3
         3           6
         4          10
         5          15
         6          21
         7          28
         8          36
         9          45
        10          55

Or recursive subquery factoring (11gR2+):
with rcte (position, running_sum) as (
  select 1, 1 from dual
  union all
  select position + 1, running_sum + position + 1
  from rcte
  where position < 10
)
select * from rcte
order by position;

  POSITION RUNNING_SUM
---------- -----------
         1           1
         2           3
         3           6
         4          10
         5          15
         6          21
         7          28
         8          36
         9          45
        10          55

A: You are looking for a cumulative sum:
select rownum, sum(rownum) over (order by rownum)
from all_objects
where rownum <= 10;

I wasn't sure this would actually work on rownum, but it does.


text:
Q: How to use increment to count something over a certain price I have a hw question that asks me to count the number of soups over $2 if somebody was to enter them in. My professor hinted that I should use incrementing to count the number of soups over $2. My code for PHP is below. I am very new to PHP and my professor is very poor at giving examples, instruction, and being a teacher. Any help will be great!
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
 <title>Cafe</title>

 <?php
$monday = $_POST['monday'];
$tuesday = $_POST['tuesday'];
$wednesday = $_POST['wednesday'];
$thursday = $_POST['thursday'];
$friday = $_POST['friday'];
$monday_item = $_POST['monday_item'];
$tuesday_item = $_POST['tuesday_item'];
$wednesday_item = $_POST['wednesday_item'];
$thursday_item = $_POST['thursday_item'];
$friday_item = $_POST['friday_item'];
$m_price = $_POST['m_price'];
$t_price = $_POST['t_price'];
$w_price = $_POST['w_price'];
$th_price = $_POST['th_price'];
$f_price = $_POST['f_price'];
$total = ($m_price + $t_price + $w_price + $th_price + $f_price);

if( empty ($_POST['tuesday']))
{print '
 You did not complete all of the required fields
';
$okay = FALSE;
}

if ( !is_numeric ($_POST['th_price']))
{print '
 That is not a number
';
$okay = FALSE;
}

if ($_POST['m_price'] > 10)
{print '
 That is too Much!!!
';
}

if($total > 10):
echo "total is greater than 10";
elseif($total == $b): // Note the combination of the words.
echo "total equals 10";
else:
echo "total is less than 10";
endif;

if ($_POST['m_price'] > 2)
{print }

print
"
";
print "

                     $monday
                     $monday_item
                     $m_price

                         $tuesday
                         $tuesday_item
                         $t_price

                         $wednesday
                         $wednesday_item
                         $w_price

                         $thursday
                         $thursday_item
                         $th_price

                         $friday
                         $friday_item
                         $f_price

";
        print   "
";

    print "
 Your total price of soups is $total
";

    ?>

A: *

*Start creating a variable with number 0. like $nrsoups = 0;

*Increase that value (variable $nrsoups) with one when price is larger
then two for a certain day

*Nr of soups over 2 dollars = $nrsoups
Something like:
$nrsoups = 0;
if ($_POST['m_price'] > 2) $nrsoups++;
if ($_POST['t_price'] > 2) $nrsoups++;

etc...


text:
Q: How to include the query filter in URL (cloudSearch) I am trying to retrieve data from cloudSearch, searching for the word "Person" and adding the following filter:
(prefix field=claimedgalleryid '')

The problem is that I don't know how to create the URL using that exact filter.
Could someone give me a suggestion or some link to Amazon documentation related to this topic?
What I've tried and didn't work:
...search?q=Gallerist&size=10&start=0&fq=(prefix%20field=claimedgalleryid%20%27%27)
...search?q=Gallerist&size=10&start=0&filter=(prefix%20field=claimedgalleryid%20%27%27)

A: You were close with your first attempt--it looks like you forgot to URI encode the = sign as %3D. Try this instead:
&fq=(prefix+field%3Dclaimedgalleryid+'')
I highly recommend using the "test search" feature to work out the kinks in your query syntax.  You can see the results right there, and then use the "View Raw: JSON" link to copy the full request URL and see how characters get escaped and such.


text:
Q: pandas: subtracting two columns and saving result as an absolute I have the code where I have a csv file opened in pandas and a new one I'm creating. There's a row I need to create "two last lines commented out" of an absolute value of subtracting two rows. I've tried a number of ideas in my head all bring an error.
import pandas as pd
import numpy as np

df = pd.read_csv(filename_read)
ids = df['id']

oosDF = pd.DataFrame()
oosDF['id'] = ids
oosDF['pred'] = pred
oosDF['y'] = df['target']
#oosDF['diff'] = oosdF['pred'] - oosDF['y']
#oosDF['diff'] = oosDF.abs()

A: I think you need for new DataFrame by subset (columns names in double []) and then get abs value of difference of columns:
oosDF = df[['id','pred', 'target']].replace(columns={'target':'y'})
oosDF['diff'] = (oosDF['pred'] - oosDF['y']).abs()

A: In your first commented line, you have oosdF instead of oosDF.
In your second commented line, you're setting the column to be abs() applied to the whole dataframe. That should be oosDF['diff'].abs()
Hope this helps!


text:
Q: is the common practice in python to put __init__ in the beginning of class definition? I wonder whether the recommended practice is to put init in the beginning of class definition or to put interface functions first:
class examp1:
    def ifmethod1(self):
         pass
    def ifmethod2(self):
         pass
    def __init__(self):
         pass

VS.
class examp1:
    def __init__(self):
         pass
    def ifmethod1(self):
         pass
    def ifmethod2(self):
         pass

A: A lot of people put it first, but every one can have their own opinion and you'll find arguments for both.
To me, being first is simply useful because it's helpful to know __init__ quickly.
In an effort to help coders of other languages grasp Python quickly, ibiblio.org says "__init__ is analogous to a constructor". In that spirit, it would often be put first — constructors in other languages are almost always listed first.
In one example, the Google style guide for Python, it is always listed first.


text:
Q: square root of a number with recursion #include<iostream>
#include<cmath>
using namespace std;
int e=0.001;
double yk(int k,double x){
    if(k==0) return 1;
    return 0.5*(yk(k-1,x) + x/yk(k-1,x));
}

double square(double x,int k)
{
    if(fabs(yk(k,x)*yk(k,x) - x)<e) return yk;
    return square(x,k+1);
}
int main()
{
    cout<<yk(5,2);
    return 0;
}

I need to calculate the square root of a number with Newton's formula which calculates y[k] till fabs(y[k] * y[k] -x)>e (a small number like 0.0001);
So if sqrt (2)= 1.41421356237 and e=0.0001 my function must back 1.4142 .
..This is the program I wrote.. I know that it is buggy, so i will be very thankful if sb help me :)))

A: The variable e should be float or double.
The error you get is not because of the fabs function, it is because you are trying to return a pointer to the yk function, but square returns a double
#include <iostream>
#include <cmath>

using namespace std;
double e=0.001;
double yk(int k,double x){
    if(k==0) return 1;
    return 0.5*(yk(k-1,x) + x/yk(k-1,x));
}

double square(double x,int k)
{
    double res = yk(k, x);
    if (fabs(res*res - x) < e) return res;
    return square(x,k+1);
}

int main()
{
    cout << yk(5,2); // Actually you don't call square....
    // it works even if you do square(2, 5), this way you get the root of two
    // doing at least 5 iterations, and if it is not enough (error > e) the
    // computer goes on until it gets an error < e
    return 0;
}


text:
Q: How to route to a page with the same name I am using this statement to route to a page
<Route path={`${match.url}/about`}
  component={asyncComponent(() => import('./routes/about'))}/>
<Route>

But I have many pages (about, location, ....)
How can I route to the page without specifying every page?

A: You need to specify all the routes if you want them to be available on different routes.
You can create a separate file routes.js which will have all the routes for the application. Then import this in App.js.


text:
Q: Bootstrap Navbar on same line I am currently trying to create a custom header of a website. It looks like the following:

Thereby, I am using Bootstrap3 and Django CMS. It looks almost like I want it to, however, the menu should be on the same line as the bottom square. How can I achieve this? The code is the following:

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                    {% show_menu 0 100 100 100 %}

Bonus: How can I achieve the blue bar on the right to come closer to the middle square?

A: So there are a few ways you could modify this (for example, you don't need the first or last col-xs-1 in the first row -- you can just have the square inside a col-xs-10 col-xs-push-1).
But changing as little of your original code as possible, this should work:

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                Toggle navigation

            </button>

                {% show_menu 0 100 100 100 %}

That will put the menu items and the square on different columns in the same row, so they should be side by side.
Hope that helps!


text:
Q: How to replicate a SAS merge I have two tables, t1 and t2:
t1
  person | visit | code1 | type1
       1       1      50      50
       1       1      50      50
       1       2      75      50

t2
  person | visit | code2 | type2
       1       1      50      50
       1       1      50      50
       1       1      50      50

When SAS runs the following code:
   DATA t3;
     MERGE t1 t2;
     BY person visit;

   RUN;

It generates the following dataset:
       person | visit | code1 | type1 | code2 | type2
            1       1      50      50      50      50
            1       1      50      50      50      50
            1       1      50      50      50      50
            1       2      75      50

I want to replicate this process in SQL, and my idea was to use a full-outer-join. This works unless there are duplicate rows. When we have duplicate rows like in the above example, a full outer join produces the following table:
       person | visit | code1 | type1 | code2 | type2
            1       1      50      50      50      50
            1       1      50      50      50      50
            1       1      50      50      50      50
            1       1      50      50      50      50
            1       1      50      50      50      50
            1       1      50      50      50      50
            1       2      75      50

I'm wondering how I would get the SQl table to match the SAS table.

A: Gordon's answer is close; but it misses one point.  Here's its output:
person  visit   code1   type1   seqnum  person  visit   code2   type2   seqnum
1       1       1       1       1       1       1       1       1       1
1       1       2       2       2       1       1       2       2       2
NULL    NULL    NULL    NULL    NULL    1       1       3       3       3
1       2       1       3       1       NULL    NULL    NULL    NULL    NULL

The third row's nulls are incorrect, while the fourth's are correct.
As far as I know, in SQL there's not a really good way to do this other than splitting things up into a few queries.  I think there are five possibilities:

*

*Matching person/visit, Matching seqnums

*Matching person/visit, Left has more seqnums

*Matching person/visit, Right has more seqnums

*Left has unmatched person/visit

*Right has unmatched person/visit

I think the last two might be workable into one query, but I think the second and third have to be separate queries.  You can union everything together, of course.
So here's an example, using some temporary tables that are a little more well suited to see what's going on.  Note that the third row is now filled in for code1 and type1, even though those are 'extra'.  I've only added three of the five criteria - the three you had in your initial example - but the other two aren't too hard.
Note that this is an example of something far faster in SAS - because SAS has a row-wise concept, ie, it's capable of going one row at a time.  SQL tends to take a lot longer at these, with large tables, unless it's possible to partition things very neatly and have very good indexes - and even then I've never seen a SQL DBA do anywhere near as well as SAS at some of these types of problems.  That's something you'll have to accept of course - SQL has its own advantages, one of which being probably price...
Here's my example code.  I'm sure it's not terribly elegant, hopefully one of the SQL folk can improve it.  This is written to work in SQL Server (using table variables), same thing should work with some changes (to use temporary tables) in other variants, assuming they implement windowing.  (SAS of course can't do this particular thing - as even FedSQL implements ANSI 1999, not ANSI 2008.)  This is based on Gordon's initial query, then modified with the additional bits at the end.  Anyone who wants to improve this please feel free to edit and/or copy to a new/existing answer any bit you wish.
declare @t1 table (person INT, visit INT, code1 INT, type1 INT);
declare @t2 table (person INT, visit INT, code2 INT, type2 INT);

insert into @t1 values (1,1,1,1)
insert into @t1 values (1,1,2,2)
insert into @t1 values (1,2,1,3)

insert into @t2 values (1,1,1,1)
insert into @t2 values (1,1,2,2)
insert into @t2 values (1,1,3,3)

select coalesce(t1.person, t2.person) as person, coalesce(t1.visit, t2.visit) as visit,
                t1.code1, t1.type1, t2.code2, t2.type2
from (select *,
             row_number() over (partition by person, visit order by type1) as seqnum
      from @t1
     ) t1 inner join
     (select *,
             row_number() over (partition by person, visit order by type2) as seqnum
      from @t2
     ) t2
     on t1.person = t2.person and t1.visit = t2.visit and
        t1.seqnum = t2.seqnum
 union all

select coalesce(t1.person, t2.person) as person, coalesce(t1.visit, t2.visit) as visit,
                t1.code1, t1.type1, t2.code2, t2.type2
from (
      (select person, visit, MAX(seqnum) as max_rownum from (
        select person, visit,
             row_number() over (partition by person, visit order by type1) as seqnum
      from @t1) t1_f
      group by person, visit
     ) t1_m inner join
     (select *, row_number() over (partition by person, visit order by type1) as seqnum
       from @t1
      ) t1
        on t1.person=t1_m.person and t1.visit=t1_m.visit
        and t1.seqnum=t1_m.max_rownum
        inner join
     (select *,
             row_number() over (partition by person, visit order by type2) as seqnum
      from @t2
     ) t2
     on t1.person = t2.person and t1.visit = t2.visit and
        t1.seqnum < t2.seqnum
     )
 union all
 select t1.person, t1.visit, t1.code1, t1.type1, t2.code2, t2.type2
     from @t1 t1 left join @t2 t2
    on t2.person=t1.person and t2.visit=t1.visit
    where t2.code2 is null

A: You can replicate a SAS merge by adding a row_number() to each table:
select t1.*, t2.*
from (select t1.*,
             row_number() over (partition by person, visit order by ??) as seqnum
      from t1
     ) t1 full outer join
     (select t2.*,
             row_number() over (partition by person, visit order by ??) as seqnum
      from t2
     ) t2
     on t1.person = t2.person and t1.visit = t2.visit and
        t1.seqnum = t2.seqnum;

Notes:

*

*The ?? means to put in the column(s) used for ordering.  SAS datasets have an intrinsic order.  SQL tables do not, so the ordering needs to be specified.

*You should list the columns explicitly (instead of using t1.*, t2.* in the outer query).  I think SAS only includes person and visit once in the resulting dataset.

EDIT:
Note:  the above produces separate values for the key columns.  This is easy enough to fix:
select coalesce(t1.person, t2.person) as person,
       coalesce(t1.key, t2.key) as key,
       t1.code1, t1.type1, t2.code2, t2.type2
from (select t1.*,
             row_number() over (partition by person, visit order by ??) as seqnum
      from t1
     ) t1 full outer join
     (select t2.*,
             row_number() over (partition by person, visit order by ??) as seqnum
      from t2
     ) t2
     on t1.person = t2.person and t1.visit = t2.visit and
        t1.seqnum = t2.seqnum;

That fixes the columns issue.  You can fix the copying issue by using first_value()/last_value() or by using a more complicated join condition:
select coalesce(t1.person, t2.person) as person,
       coalesce(t1.visit, t2.visit) as visit,
       t1.code1, t1.type1, t2.code2, t2.type2
from (select t1.*,
             count(*) over (partition by person, visit) as cnt,
             row_number() over (partition by person, visit order by ??) as seqnum
      from t1
     ) t1 full outer join
     (select t2.*,
             count(*) over (partition by person, visit) as cnt,
             row_number() over (partition by person, visit order by ??) as seqnum
      from t2
     ) t2
     on t1.person = t2.person and t1.visit = t2.visit and
        (t1.seqnum = t2.seqnum or
        (t1.cnt > t2.cnt and t1.seqnum > t2.seqnum and t2.seqnum = t2.cnt) or
        (t2.cnt > t1.cnt and t2.seqnum > t1.seqnum and t1.seqnum = t1.cnt)

This implements the "keep the last row" logic in a single join.  Probably for performance reasons, you would want to put this into separate left joins on the original logic.


text:
Q: Debug assertion failed: Subscript out of range with std::vector I'm trying to fix this problem which seems like I am accessing at an out of range index, but VS fails to stop where the error occurred leaving me confused about what's causing this.
The Error:

Debug Assertion Failed! Program: .... File: c:\program files\microsoft visual studio 10.0\vc\include\vector Line: 1440 Expression: String subscript out of range

What the program does:
There are two threads:
Thread 1:
The first thread looks (amongst other things) for changes in the current window using GetForegroundWindow(), the check happens not on a loop but when a WH_MOUSE_LL event is triggered. The data is split into structs of fixed size so that it can be sent to a server over tcp. The first thread and records the data (Window Title) into an std::list in the current struct.
if(change_in_window)
{
    GetWindowTextW(hActWin,wTitle,256);
    std::wstring title(wTitle);
    current_struct->titles.push_back(title);
}

Thread 2:
The second thread is called looks for structs not send yet, and it puts their content into char buffers so that they can be sent over tcp. While I do not know exactly where the error is, looking from the type of error it was to do either with a string or a list, and this is the only code from my whole application using lists/strings (rest are conventional arrays). Also commenting the if block as mentioned in the code comments stops the error from happening.
  BOOL SendStruct(DATABLOCK data_block,bool sycn)
    {
    [..]

                int _size = 0;
// Important note, when this if block is commented the error ceases to exist, so it has something to do with the following block
                if(!data_block.titles.empty()) //check if std::list is empty
                {

                    for (std::list<std::wstring>::iterator itr  = data_block.titles.begin(); itr != data_block.titles.end() ; itr++) {
                        _size += (((*itr).size()+1) * 2);
                    } //calculate size required. Note the +1 is for an extra character between every title
                    wchar_t* wnd_wbuffer = new wchar_t[_size/2](); //allocate space
                    int _last = 0;
    //loop through every string and every char of a string and write them down
                    for (std::list<std::wstring>::iterator itr = data_block.titles.begin(); itr != data_block.titles.end(); itr++)
                    {
                        for(unsigned int i = 0; i <= (itr->size()-1); i++)
                        {

                            wnd_wbuffer[i+_last] = (*itr)[i] ;
                        }
                        wnd_wbuffer[_last+itr->size()] = 0x00A6; // separator
                        _last += itr->size()+1;
                    }

                    unsigned char* wnd_buffer = new unsigned char[_size];
                    wnd_buffer = (unsigned char*)wnd_wbuffer;
                    h_io->header_w_size = _size;
                    h_io->header_io_wnd = 1;
                    Connect(mode,*header,conn,buffer_in_bytes,wnd_buffer,_size);
                    delete wnd_wbuffer;
                }
                else
            [..]
                return true;
            }

My attempt at thread synchronization:
There is a pointer to the first data_block created (db_main)
pointer to the current data_block  (db_cur)
//datablock format
    typedef struct _DATABLOCK
        {
            [..]
            int logs[512];
            std::list<std::wstring> titles;
            bool bPrsd; // has this datablock been sent true/false
            bool bFull; // is logs[512] full true/false
            [..]
            struct _DATABLOCK *next;
        } DATABLOCK;

//This is what thread 1 does when it needs to register a mouse press and it is called like this:
    if(change_in_window)
    {
        GetWindowTextW(hActWin,wTitle,256);
        std::wstring title(wTitle);
        current_struct->titles.push_back(title);
    }
    RegisterMousePress(args);
    [..]
//pseudo-code to simplify things , although original function does the exact same thing.
    RegisterMousePress()
        {
            if(it_is_full)
            {
                db_cur->bFull= true;
                if(does db_main exist)
                {
                    db_main = new DATABLOCK;
                    db_main = db_cur;
                    db_main->next = NULL;
                }
                else
                {
                    db_cur->next = new DATABLOCK;
                    db_cur = db_cur->next;
                    db_cur->next = NULL;

                }
                SetEvent(eProcessed); //tell thread 2 there is at least one datablock ready
            }
            else
            {
            write_to_it();
            }
        }
//this is actual code and entry point of thread 2 and my attempy at synchronization
    DWORD WINAPI InitQueueThread(void* Param)
    {
        DWORD rc;
        DATABLOCK* k;
        SockWClient writer;
        k = db_main;
        while(true)
        {
            rc=WaitForSingleObject(eProcessed,INFINITE);
            if (rc== WAIT_OBJECT_0)
            {
                do
                {
                    if(k->bPrsd)
                    {
                        continue;
                    }
                    else
                    {
                        if(!k)
                        {break;}
                        k->bPrsd = TRUE;
    #ifdef DEBUG_NET
                        SendStruct(...);
    #endif

                    }
                    if(k->next == NULL || k->next->bPrsd ==TRUE || !(k->next->bFull))
                    {
                        ResetEvent(eProcessed);
                        break;
                    }

                } while (k = k->next); // next element after each loop
            }
        }
        return 1;

    }

Details:
Now something makes me believe that the error is not in there, because the substring error is very rare. I have been only able to reproduce it with 100% chance when pressing Mouse_Down+Wnd+Tab to scroll through windows and keeping it pressed for some time (while it certainly happened on other cases as well). I avoid posting the whole code because it's a bit large and confusion is unavoidable. If the error is not here I will edit the post and add more code.
Thanks in advance

A: There does not appear to be any thread synchronization here. If one thread reads from the structure while the other writes, it might be read during initialization, with a non-empty list containing an empty string (or something invalid, in between).
If there isn't a mutex or semaphore outside the posted function, that is likely the problem.
All the size calculations appear to be valid for Windows, although I didn't attempt to run it… and <= … -1 instead of < in  i <= (itr->size()-1) and 2 instead of sizeof (wchar_t) in  new wchar_t[_size/2](); are a bit odd.

A: The problem with your code is that while thread 2 correctly waits for the data and thread 1 correctly notifies about them, thread 2 doesn't prevent thread 1 from doing anything with them under its hands while it still process the data. The typical device used to solve such problem is the monitor pattern.
It consist of one mutex (used to protect the data, held anytime you access them) and a condition variable (=Event in Windows terms), which will convey the information about new data to the consumer.
The producer would normally obtain the mutex, produce the data, release the mutex, then fire the event.
The consumer is more tricky - it has to obtain the mutex, check if new data hasn't become available, then wait for the Event using the SignalObjectAndWait function that temporarily releases the mutex, then process newly acquired data, then release the mutex.


text:
Q: Linux Libertine Bold Math I'm using Linux Libertine everywhere in my document. However, I cannot figure out how to get bold math \mathbf to display as bold text. This answer seemed related to this problem, but trying that (replacing Minion Pro with Linux Libertine O) in my case gives me the following error (for every X:Y:Z):

Symbol font `Latin:m:n' not defined.

How can I get bold math symbols in my document?
MWE:
\documentclass{minimal}
\usepackage{amsthm}
\usepackage[libertine]{newtxmath}
\usepackage{mathspec, libertine, lipsum}
\setmathsfont[ItalicFont={LinLibertine_RI.otf}]{LinLibertine_R.otf}
\setmathrm{LinLibertine_R.otf}
\setboldmathrm{LinLibertine_RB.otf}
\setmathsf{LinBiolinum_RB.otf}

\begin{document}
\lipsum[1]

\begin{equation}
    \hat{Q}_i=\int_0^\infty \mathcal{G}^2(\mathbf{x}) \mathbf{\Sigma}^{-1}(x^2) f_i(x)dx
\end{equation}

\end{document}

A: I don't get the error you claim, but some things go wrong, I believe because of how libertine interacts with mathspec.
One has to specify the classes for which Libertine is wanted, though, and this triggers the error about insufficient mathgroups. This can be cured with the method outlined in http://tex.stackexchange.com/a/100428/4427
This version works, by directly calling the fonts by name.
\documentclass{article}

\usepackage{etoolbox}
\makeatletter
%% http://tex.stackexchange.com/questions/100426/
%% http://tex.stackexchange.com/a/100428/
\def\new@mathgroup{\alloc@8\mathgroup\mathchardef\@cclvi}
\patchcmd{\document@select@group}{\sixt@@n}{\@cclvi}{}{}
\patchcmd{\select@group}{\sixt@@n}{\@cclvi}{}{}
\makeatother

\usepackage{amsthm}
\usepackage[libertine]{newtxmath}
\usepackage{mathspec,lipsum}
\setmainfont{Linux Libertine O}
\setmathsfont(Digits,Latin,Greek){Linux Libertine O}
\setmathrm{Linux Libertine O}
\setboldmathrm{Linux Libertine O}
\setmathsf{Linux Biolinum O}

\begin{document}
\lipsum[2]

\begin{gather}
\hat{Q}_i=\int_0^\infty \mathcal{G}^2(\mathbf{x})
  \mathbf{\Sigma}^{-1}(x^2) f_i(x)\,dx=\mathsf{X} \\
\hat{Q}_i=\int_0^\infty \mathcal{G}^2(\mathbf{x})
  \mathbf{\Sigma}^{-1}("x^2) f_i(x)\,dx=\mathsf{X}
\end{gather}

\end{document}

I added a line to your formula, showing how " is necessary as explained in the mathspec manual.


text:
Q: how to find out when a method from an object is called in java I have two classes, e.g. A and B.
An instance of A creates an instance of class B. How can A become aware when an specific function from object B is called?
Object A needs to become aware whenever an specific function from object B is executed, but without changing the source code of class B. This should be done at run-time.
I guess it can be done by InvocationHandler in java, but not sure and don't know how to do it.

A: what about a decorator of B that notifies A ?
http://en.wikipedia.org/wiki/Decorator_pattern

A: Basically, you have to decorate B so that decordatedB.someMethod() first notifies a and then calls d.someMethod().
If B is an interface, it is quite easy, you do something like
final B b = new BImpl();
final B decoratedB = new B() {
  public void someMethod () {
    a.someMethodOfBisCalled();
    b.someMethod();
  }
};

If B is a class then you could use Proxy (very rough sketch):
InvocationHandler bInvocationHandler = new BInvocationHandler() {
    public Object invoke(Object proxy, Method method, Object[] args) {
       // Check this is someMethod
       // a.someMethodOfBIsCalled();
       // b.someMethod();
    }
};

B decoratedB = (B) Proxy.newProxyInstance(B.class.getClassLoader(),
    new Class[] { Foo.class }, bInvocationHandler );

There are other ways like mentioned AOP, then code instrumentation etc. etc. but I think you are well served with the above.


text:
Q: How do I make a contain method in Notion look for two conditions? I have a Date field in Notion. It's setup is like this: December 7, 2022.
I have made a formula that looks for the month and then adds up expenses from that month. this is the formula:
contains(format(prop("Date")), "December") ? prop("Expenses") : 0

The problem is that I also need it to search for the year, but ignore the day. Is that possible at all?
Kind of like this, but it's not working:
contains(format(prop("Date")), "December" and "2022") ? prop("Expenses") : 0


text:
Q: Global constant in Angular depending on build configuration I am currently trying to migrate an AngularJS 1.6 application, completely build in components, to Angular 12. So far everything works, but I am having one big problem cause of our project structure:
The project is a multi-client portal with several different "profiles" for each client (different assets, API-Urls etc.), Backend is Java, Frontend AngularJS/Angular Hybrid (now). Depending on the frontend build configuation via Angular-CLI I build the frontend for the corresponding client.
My problem now is: In the AngularJS-Application we were adding AngularJS-constants to the AngularJS-App
(function () {
'use strict';

function constant() {
    return {
        CUSTOMER_NAME : 'client name',
        // and many more...
    };
}

angular
    .module('our.module')
    .constant('CLIENT_CONSTANTS', constant());
})();

depending on the build-configuration (all scripts have been added to the index.html cause we werent using webpack before), e.g.
<script src="${clientName}"></script>

Where ${clientName} was the placeholder for the client, which was replaced by gulp during build. This isnt possible anymore with Angular, as Angular does the injection of the script-Tags via Angular-CLI. It seems that it isn't possible to pass variables from the Angular-CLI to the code, which would exactly be what I need :-( So I am wondering how I can add global constants depending on the Angular-CLI-Build configuration! Any ideas? I tried adding the constants-file to the configurations' script-Block, to no avail. (
I refactored the clients-file to TypeScript:
export const PROFILE_CONSTANTS = {
    CUSTOMER_NAME : 'client name',
    // and many more
}

I also tried to dynamically import the file via ES6-import, which also isn't possible. I'm running out of ideas now.

A: You probably want to use Angular configurations (previously known as Angular environments).
Heres an example setup to get you started:
https://dev.to/mikgross/set-up-multiple-environments-in-angular-376c
Note that this has changed a fair bit over the course of time so make sure you are applying a solution that relates to Angular 12.
The only thing the above article misses out is how to access the variables for a given configuration. Basically you import from environment/environment.ts and the Angular server or build will serve up the correct environment file based on the fileReplacements you specify in angular.json
Note that in the example given, they are creating different configurations for different servers, but you can equally apply this to creating different configurations for different clients.


text:
Q: Comparing Items In List using loops & conditional statements I'm trying to loop through a list and compare the items against what a person has entered and then make a decision. Any ideas where my logic is going wrong?
user = input("Enter your password: ")
passwords = ["pa$$w0rd", "password123", "scr1pt1ng", "F0r3n51c5",    "123456"];

for n in passwords:
    if n == user:
        print("Found", n)
        break
    else:
        print(user, "Not Found")

A: You need to read more about the difference between python2 and python3.
In your code you use python3 style:print(something), because python2 style should be print "something"; input vs raw_input
So your version is Python3
I dont use python2, but it should be like:
user = raw_input("Enter your password: ")  # input changed to raw_input
passwords = ["pa$$w0rd", "password123", "scr1pt1ng", "F0r3n51c5",    "123456"];

for n in passwords:
    if n == user:
        print "Found", n
        break
    else:
        print user, "Not Found"


text:
Q: Get 5 random images from custom post type galleries I have a custom post type called "project" and within this post type is 10 posts (projects), each post contains a few images/gallery.
I have a sidebar and I want the sidebar to generate 3 random images pulled from the galleries of the custom post type "project".
I have this code but it doesn't seem to work correctly.

        <?php
            $loop = new WP_Query(array(
                'post_type' => 'project',
                'posts_per_page' => 0,
                'orderby'=>'rand',
            ));
        ?>
        <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

            <?php $images = get_field('gallery'); ?>
            <?php shuffle ($images); ?>
            <?php if ($images): ?>
                <?php foreach (array_slice($images, 0, 3) as $image ): ?>

                <li style="background-image: url(<?php echo $image['url']; ?>);">

                <?php endforeach; ?>
            <?php endif; ?>

        <?php endwhile; ?>


text:
Q: Cakephp 3.6 Search Get find I've been trying to use this code to retrive data from a table
but it doesnt seem to work as expected. What am I doing wrong?
default.ctp

    <input type="text" class="form-control" placeholder="Search for...">

      <button class="btn btn-default" type="button">Go!</button>

 <?= $this->Form->create("",['type'=>'get']) ?>
 <?= $this->Form->control('search', ['default'=>$this->request->query('search')]); ?>
 <?= $this->Form->end() ?>``

UsersController.php
public function index()
{
    $search = $this->request->query('search');
    if(!empty($search)){
        $this->paginate = [
            'conditions' =>['Users LIKE '=>'%'.$search. '%']

        ];
    }

How to insert the form search inside the button?

A: Fixed change made
$search = $this->request->query('search');
    if(!empty($search)){
        $this->paginate = [
            'conditions' =>['Users.full_name LIKE '=>'%'.$search. '%']

        ];
    }else{

    $this->paginate = array(
        'limit' => 4 );
      [
        'contain' => ['Users', 'SourceProspects', 'Status']
    ];
  }
    $prospects = $this->paginate($this->Users);

    $this->set(compact('prospects'));
    $this->set('title', 'Manage Prospect');
    $this->set('user_session', $this->request->session()->read('Auth.User'));
}

As for the button

                    <?= $this->Form->create("",['type'=>'get']) ?>
                    <?= $this->Form->control('search', ['default'=>$this->request->getQuery('search'),'class'=>'form-control','placeholder'=>'Search For Name'
                  ]); ?>
                    <button class="btn btn-default ">Go!</button>
                    <?= $this->Form->end() ?>


text:
Q: Codenameone FloatingHint issue Tried using the Codename One FloatingHint class but on running the application i get an java.lang.IllegalArgumentException: Component is already contained in Container. This was my implementation
Form f = new Form(new BoxLayout(BoxLayout.Y_AXIS));
TextField hintTest= new TextField(11);
hintTest.setHint("The hint");
new FloatingHint(hintTest);
addComponent(hintTest);

A: Managed to get it working with
    TextField hintTest= new TextField(11);
    hintTest.setHint("The Hint");
    FloatingHint x = new FloatingHint(uname);
    addComponent(x);


text:
Q: How to create rotated rectangular or polygonal ROI/mask? Let's say i have the following image:

And my region of interest looks like this:

And i want to have the following result:

How can i achieve this knowing that the ROI is denoted by four points:
 Point pt1(129,9);
 Point pt2(284,108);
 Point pt3(223,205);
 Point pt4(67,106);

A: The idea is to use fillPoly() to fill all the pixels inside the rotated-rectangle/polygon to 0, 255 otherwise:
Mat mask = cv::Mat(img.size(), CV_8UC1, Scalar(255));     // suppose img is your image Mat

vector<vector<Point>> pts = { { pt1, pt2, pt3, pt4 } };
fillPoly(mask, pts, Scalar(0));                           // <- do it here


text:
Q: Details to Lie derivative of Christoffel symbols I have a question to an answer given here: Lie derivative of the Christoffel symbol (I would commment there but don't have the necessary reputation yet.)
The question is how to find the expression
$$
  \mathcal{L}_\xi \Gamma^\mu {}_{\nu\lambda} = \xi^\sigma R^\mu {}_{\lambda\sigma\nu}
      + \nabla_\nu \nabla_\lambda \xi^\mu.\qquad\text{(1)}
$$
in local coordinates for the Lie derivative of the Christoffel symbols.
In the cited answer, the proof is done in a coordinate-free way, however, not all steps are entirely clear to me. There, it is shown that, assuming that the connection is a $(1, 2)$-tensor,
$$ (\mathcal{L}_{\xi}\nabla)(X,Y) \stackrel{?}{=} \mathcal{L}_{\xi}(\nabla_X Y) - \nabla_{\mathcal{L}_{\xi} X} Y - \nabla_X (\mathcal{L}_{\xi} Y) = R^{\nabla}(\xi, X) Y + (\nabla^2 \xi)(X,Y). $$
and written in coordinates this will result in Eq. (1).
I don't understand the following:

*

*From their indices, the Christoffel symbols look like components of a $(1, 2)$-tensor, so assuming that the connection is such a tensor makes sense to me. However, in the equal sign marked with a question mark, this is the formal expression for the Lie derivative of a $(0, 2)$-tensor; also, the third argument, a 1-form, is missing. What am I missing here?

*We also need to turn the coordinate-free expression on the left-hand side into the coordinate expression, i.e.
$$
(\mathcal{L}_{\xi}\nabla) \rightarrow \mathcal{L}_\xi \Gamma^\mu {}_{\nu\lambda}
$$
How would this work in detail? Since the coordinate-free calculation takes only two vector fields, it's unclear to me how I would the free upstairs index?
I could see that the whole calculation is an equation of vector fields; however, I still don't understand why we use the $(0, 2)$-tensor formula for the Lie derivative when we say we want it to be a $(1, 2)$-tensor.
I have found several posts regarding this topic, however, none of them ultimately tell the formal proof and every explanation I find contains one unexplained detail or two that I cannot figure out myself.

A: The formula for the Lie derivative of a $\binom12$-tensor is not the definition, but you can easily deduce it from the definition. In the definition, you would view a $\binom12$-tensorfield $A$ as mapping two vector fields and one one-form to a smooth function. But you can also view your tensor field as a map $\hat A$ that takes two vector fields as input and gives one vector field as output. The relation simply looks like $A(X,Y,\phi)= \phi(\hat A(X,Y))$. Now using the definition you get
$$
(\mathcal L_\xi A)(X,Y,\phi)=\xi(A(X,Y,\phi))-A(\mathcal L_\xi X, Y,\phi)-A(X,\mathcal L_\xi Y,\phi)-A(X,Y,\mathcal L_\xi \phi).
$$
The last term can be written as $-(\mathcal L_\xi \phi)(\hat A(X,Y))=-\xi(\phi(\hat A(X,Y)))+\phi(\mathcal L_\xi (\hat A(X,Y)))$. The second and third term in the right hand side of the above equation can be directly rewritten as $-\phi(\hat A(\mathcal L_\xi X,Y))-\phi(\hat A(X,\mathcal L_\xi Y))$. But the left hand side of the equation should just be interpreted as $\phi((\mathcal L_\xi \hat A)(X,Y))$ so the above equation simply reads as
$$
\phi((\mathcal L_\xi \hat A)(X,Y))=\phi(\mathcal L_\xi (\hat A(X,Y)))-\phi(\hat A(\mathcal L_\xi X,Y))-\phi(\hat A(X,\mathcal L_\xi Y)),
$$
Since this has to hold for each $\phi$, we get
$$
(\mathcal L_\xi \hat A)(X,Y)=\mathcal L_\xi (\hat A(X,Y))-\hat A(\mathcal L_\xi X,Y)-\hat A(X,\mathcal L_\xi Y),
$$
which is the formula that is used.
I think you have partly misunderstood the answer you have linked to. The connection is not a $\binom12$-tensor and it is nowhere claimed in that answer that it is. Formula (1) is used there as the definition of the Lie derivative of a connection, the relation to tensor fields is just an analogy. The justification for this definition is explained in the answer, it is via pullbacks of local flows of $\xi$.
The reason I am pointing this out is that in my opinion the formulation "Lie derivatives of the Christoffel symbols" is misleading and this is why you have problems with the coordinate expression. The general version of a Lie derivative can be defined on geometric objects as long as there is a natural action of local diffeomorphisms on them. This is the case for connections, but not for the Christoffel symbols which are just functions defined on the domain of a chart (and taking the Lie derivative in this picture would lead to a different result). What you actually want to get is the analog for $(\mathcal L_\xi\nabla)$ of what the Christoffel symbols are for $\nabla$. This means that you have to look at the value $(\mathcal L_\xi\nabla)(\partial_\nu,\partial_\lambda)$ of $\mathcal L_\xi\nabla$ on two coordinate vector fields and expand the result in coordinate vector fields. Otherwiese put the definition of the symbols you write as $\mathcal L_\xi\Gamma^\mu_{\nu\lambda}$ is that
$$
(\mathcal L_\xi\nabla)(\partial_\nu,\partial_\lambda)=\sum_\mu (\mathcal L_\xi\Gamma^\mu_{\nu\lambda})\partial_\mu.
$$
Once this is clear, the result is easily obtained from the explanations in the answer you have linked to.


text:
Q: Getting new Context State after Context State is updated I have a child component inside a context provider. After a child component calls an update state to the context provider, the context provider's state changes. However, this new changed value is not attainable from the child state. How would I be able to retrieve the updated value of the changed state from the Child component?
Or... is this just a bad practice and is there another way to do this?
I have a Context State in a Context Provider
AuthContextProvider=()=>{
    const[data,updatedata]=React.useState(null)
    AuthUpdate function(){
       updateData() //updates the state
    }
    //... pass AuthUpdate, data to children
}

and a child component... as such
<AuthContextProvider>
   <NavBar>
   </NavBar>
</AuthContextProvider>

Navbar looks like this:
NavBar=()=>{
   const {data,AuthUpdate}=useAuth()
   onClick function(){
        AuthUpdate()  //data in the context changes
        console.log(data) //somehow use the UPDATED data after context state changes
   }

}


text:
Q: React-navigation v5 (evaluating 'this._callListeners.bind') when this.props.navigation.navigate I am currently working with the React navigation v5.
But i cannot achieve a simple navigation by this error:

TypeError: undefined is not an object (evaluating
  'this._callListeners.bind')

This is the sample work from this repo,
https://github.com/SinghDigamber/reactNativeNavigation
This error is located at:
in Card (at CardContainer.tsx:154)
in CardContainer (at CardStack.tsx:518)
in RCTView (at CardStack.tsx:109)
in MaybeScreen (at CardStack.tsx:511)
in RCTView (at CardStack.tsx:92)
in MaybeScreenContainer (at CardStack.tsx:410)
in CardStack (at StackView.tsx:384)
in KeyboardManager (at StackView.tsx:382)
in RNCSafeAreaView (at src/index.tsx:28)
in SafeAreaProvider (at SafeAreaProviderCompat.tsx:42)
in SafeAreaProviderCompat (at StackView.tsx:379)
in RCTView (at StackView.tsx:378)
in StackView (at createStackNavigator.tsx:67)
in StackNavigator (at App.js:15)
in NavStack (at App.js:50)
in EnsureSingleNavigator (at BaseNavigationContainer.tsx:267)
in ForwardRef(BaseNavigationContainer) (at NavigationContainer.tsx:39)
in ThemeProvider (at NavigationContainer.tsx:38)
in ForwardRef(NavigationContainer) (at App.js:49)
in App (at renderApplication.js:40)
in RCTView (at AppContainer.js:101)
in RCTView (at AppContainer.js:119)
in AppContainer (at renderApplication.js:39)

Here is the code:
App.js
// App.js

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

import Home from './screens/Home';
import Blog from './screens/Blog';
import BlogDetails from './screens/BlogDetails';

const Stack = createStackNavigator();

function NavStack() {
  return (
     <Stack.Navigator
        initialRouteName="Home"
        screenOptions={{
          headerTitleAlign: 'center',
          headerStyle: {
            backgroundColor: '#621FF7',
          },
          headerTintColor: '#fff',
          headerTitleStyle :{
            fontWeight: 'bold',
          },
        }}
      >
      <Stack.Screen
        name="Home"
        component={Home}
        options={{ title: 'Home' }}
      />
      <Stack.Screen
        name="Blog"
        component={Blog}
        options={{ title: 'Blog' }}
      />
      <Stack.Screen
       name="BlogDetails"
       component={BlogDetails}
       options={{ title: 'Blog Detail' }}
      />
    </Stack.Navigator>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <NavStack />
    </NavigationContainer>
  );
}

console.disableYellowBox = true;

Home.js
// screens/Home.js

import React, { Component } from 'react';
import { Button, View, Text } from 'react-native';

class Home extends Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Home Screen</Text>
        <Button
          title="Go to Blog"
          onPress={() => this.props.navigation.navigate('Blog')}
        />
        <Button
          title="Go to Blog Details"
          onPress={() => this.props.navigation.navigate('BlogDetails')}
        />
      </View>
    );
  }
}

export default Home;

But the error occur when the button onPress.
I cannot find any solutions about this, maybe v5 is quite new.

A: In your App.js declare your NavStack() function as fat arrow function as below :
// App.js

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

import Home from './screens/Home';
import Blog from './screens/Blog';
import BlogDetails from './screens/BlogDetails';

const Stack = createStackNavigator();

const NavStack = () => { // declare NavStack as fat arrow functions
  return (
    <Stack.Navigator
      initialRouteName="Home"
      screenOptions={{
        headerTitleAlign: 'center',
        headerStyle: {
          backgroundColor: '#621FF7',
        },
        headerTintColor: '#fff',
        headerTitleStyle: {
          fontWeight: 'bold',
        },
      }}
    >
      <Stack.Screen
        name="Home"
        component={Home}
        options={{ title: 'Home' }}
      />
      <Stack.Screen
        name="Blog"
        component={Blog}
        options={{ title: 'Blog' }}
      />
      <Stack.Screen
        name="BlogDetails"
        component={BlogDetails}
        options={{ title: 'Blog Detail' }}
      />
    </Stack.Navigator>
  );
}

export default App = () => { // declare App als as fat arrow functions
  return (
    <NavigationContainer>
      <NavStack />
    </NavigationContainer>
  );
}

console.disableYellowBox = true;

Also I notice that you are using NavigationContainer, you should use NavigationNativeContainer as below :
// import from @react-navigation/native
import {NavigationNativeContainer} from '@react-navigation/native'; // import NavigationNativeContainer

Now change :
<NavigationContainer>
  <NavStack />
</NavigationContainer>

to
<NavigationNativeContainer >
  <NavStack />
</NavigationNativeContainer >

A: For me it was an issue adding plugins in babel.config.js, such us decorators, private methods, class-properties etc. When I remove them and run expo start -c now all it's working again.

A: This crash happens when you change your Babel configuration to something other than what React Native uses by default.
My issue solves by removing these plugins from babel.config.js

*

*@babel/plugin-proposal-decorators

*@babel/plugin-proposal-class-properties

*@babel/plugin-proposal-private-methods

Check this

A: Using BaseNavigationContainer instead of NavigationContainer fixed it for me.

A: same error,now i want give up react-native, develop experience so bad.


text:
Q: How to send mail with attachment in JavaScript via Gmail API I'm trying to send a mail with attachment via Gmail API.
I'm successfully sending my mail as specified below:
function sendmail(to, subject, message) {
    var email =
        "To: " + to + "\r\n" +
        "Subject: " + subject + "\r\n" +
        'Content-Transfer-Encoding: 8bit\r\n' +
        'Content-Type: text/html; charset="UTF-8"\r\n' +
        "" +
        message + "\r\n\r\n";
    var sendRequest = gapi.client.gmail.users.messages.send({
        'userId': 'me',
        'resource': {
            'raw': window.btoa(unescape(encodeURIComponent(email))).replace(/\+/g, '-').replace(/\//g, '_')
        }
    });

    sendRequest.execute();
}

Now I want to send some file as attachment and tried it in following way:
<input id="inputFile" type="file" onChange="convertToBase64();"/>
<script>
    var file_ = '';

    function convertToBase64() {
        //Read File
        var file = document.getElementById("inputFile").files[0];
        var reader = new FileReader();
        reader.onload = function () {
            file_ = reader.result.split('base64,')[1];
        };
        reader.onerror = function (error) {
            console.log('Error: ', error);
        };
        reader.readAsDataURL(file);
    }

    function sendmail(to, subject, message, date) {
        console.log(date);

        if (typeof file_ !== "undefined" && file_ != '') {
            var email =
                "To: " + to + "\r\n" +
                "Subject: " + subject + "\r\n" +
                'Content-Transfer-Encoding: 8bit\r\n' +
                'Content-Type: text/html; charset="UTF-8"\r\n' +
                "" +
                message +
                "\r\n\r\n" +
                "--foo_bar_baz\r\n" +
                "Content-Type: application/pdf\r\n" +
                "MIME-Version: 1.0\r\n" +
                "Content-Disposition: attachment; filename=example.pdf\r\n\r\n" +
                file_ + "\r\n\r\n";
            var sendRequest = gapi.client.gmail.users.messages.send({
                'userId': 'me',
                'resource': {
                    'raw': window.btoa(unescape(encodeURIComponent(email))).replace(/\+/g, '-').replace(/\//g, '_')
                }
            });

            sendRequest.execute();
        } else {
            alert('boo');
        }
    }
</script>

And I would receive the mail BUT I see no text and cannot open the file because of 'bad coding!'.
I did check the whole gmail documentation but without avail.
Could somebody please help me out?

A: Have you tried: Content-Transfer-Encoding: base64
I read somewhere that encoding pdf's as base64 require you to set the content transfer encoding accordingly.


text:
Q: How do you keep view logic out of the model and business logic out of the view-model in MVVM? I can't quite figure out how to get the view model to be notified of changes in the model without adding a bunch of UI specific stuff like INotifyProperyChanged and INotifyCollectionChanged in my model or create tons of different events and do a bunch of things that feel like they're UI specific and should stay out of the model.
Otherwise I'd just have to duplicate all the business logic in the view-model to make sure everything is up to date, and then what's the point of having the model then?
One of the tricky ones that I have in my model is a property of a "Category" class.  You can think of it as a tree structure and the property is all leaf-node descendants.  Well in the model that property is generated on the fly recursively through all it's children, which is all fine and good.  The view-model however needs to bind to that property and needs to know when it changes.  Should I just change the model to accommodate the view-model?  If I do then the view-model doesn't really do anything at this point, the model raises all the necessary notifications of changes and the view can just bind straight to the model.  Also if the model was something I didn't have the source to, how would I get around this?

A: I disagree that INotifyPropertyChanged and INotifyCollectionChanged are UI-specific. They are in namespaces and assemblies that are not tied to any particular UI stack. For that reason, I typically put that kind of behavior as low in the system as I can (usually the data layer).
If there's some reason you don't want to put it at that level, that's fine. You can put it in at a higher level such as the service or UI layer. However, you need to make sure all changes to the data structures occur through that layer also.


text:
Q: Handling JWT token renewal within Apache Camel I've recently been working on setting up a project to use Azure and part of that involves requesting a token to access a REST API. I've been told that the token will expire in 30 minutes, but calling the API to get a new token isn't particularly expensive. I can do all this without any issue, but I'm curious if Camel has anything built in that can handle this for me without having to explicitly call to get a new token?

A: I don't know of anything built in, but you could have a timer route that runs every 25 minutes that requests a token and puts it in some kind of global state.
from("timer:getAuthToken?period=1500000")
    .to("http:myKeyServer/getKey")
    .process(new MyKeyProcessor()) // store in global state, static, spring, etc.

Then any route that needs the key can get it from global state and set it in a header or exchange property.


text:
Q: Apache Spark Custom groupBy on Dataframe based on value count I have a sample data as below and I want to group based on value count. I have thresold count of value in each group. If more than 3 values are there then I need to have that as another row.. Can someone please advise..  I have normal groupby but how to transform the based on thresold count. I need to call an api which can accept max x amount of value in input so need to somehow break the value
val tdf1=tDf.groupBy(col("attr1")).agg(concat_ws(",",collect_list(col("attr2"))).as("value"))

Input:
scala> tdf1.show(false)
+-----+-----------------------+
|attr1|value                  |
+-----+-----------------------+
|1    |2,20                   |
|2    |200,201,202,203,204,205|
+-----+-----------------------+

Expectation:
scala> tdf1.show(false)
    +-----+-----------------------+
    |attr1|value                  |
    +-----+-----------------------+
    |1    |2,20                   |
    |2    |200,201,202
    |2    |203,204,205            |

Input file:
    [{
  "attr1":"1",
  "attr2":"2"
},{
  "attr1":"1",
  "attr2":"20"
},{
  "attr1":"2",
  "attr2":"200"
},{
  "attr1":"2",
  "attr2":"201"
},{
  "attr1":"2",
  "attr2":"202"
},{
  "attr1":"2",
  "attr2":"203"
},{
  "attr1":"2",
  "attr2":"204"
},{
  "attr1":"2",
  "attr2":"205"
}]

A: we can do it using collect_list() window function that selects only 3 records and slides.
First, create the list of 3 elements for every record window, along with a row number to keep the track of the record number. The record number will be used later for filtering.
data_sdf. \
    withColumn('rn', func.row_number().over(wd.partitionBy('attr1').orderBy('attr2')) - 1). \
    withColumn('attr3', func.concat_ws(',', func.collect_list('attr2').over(wd.partitionBy('attr1').rowsBetween(0, 2)))). \
    show()

# +-----+-----+---+-----------+
# |attr1|attr2| rn|      attr3|
# +-----+-----+---+-----------+
# |    1|    2|  0|       2,20|
# |    1|   20|  1|         20|
# |    2|  200|  0|200,201,202|
# |    2|  201|  1|201,202,203|
# |    2|  202|  2|202,203,204|
# |    2|  203|  3|203,204,205|
# |    2|  204|  4|    204,205|
# |    2|  205|  5|        205|
# +-----+-----+---+-----------+

Once we get it for all records, we can just retain the required records that will give us the 3 elements i.e., every 3rd record after the first one in the group.
data_sdf. \
    withColumn('rn', func.row_number().over(wd.partitionBy('attr1').orderBy('attr2')) - 1). \
    withColumn('attr3', func.concat_ws(',', func.collect_list('attr2').over(wd.partitionBy('attr1').rowsBetween(0, 2)))). \
    filter((func.col('rn') == 0) | (func.col('rn') % 3 == 0)). \
    show()

# +-----+-----+---+-----------+
# |attr1|attr2| rn|      attr3|
# +-----+-----+---+-----------+
# |    1|    2|  0|       2,20|
# |    2|  200|  0|200,201,202|
# |    2|  203|  3|203,204,205|
# +-----+-----+---+-----------+

we can get rid of the rn and attr2 columns in the aforementioned step after the filter.


text:
Q: How update properly VueJs .env files Getting old value still after updating with the fresh new values
VUE_APP_API_URL="http://example.com/api/"

Is there a command to clear the cache?
I have event build my project again... :(


text:
Q: How to search and remove ^M in all files in a directory recursively? Files edited in Windows have M^ at end lines. How would I remove them ?

A:
NOTE
Be careful when using this command, as it will replace all LF/CR
  character sequence regardless of position or context. Take extra care
  in situations where you have binary files or files that have special
  configuration formats. Directories with git submodules is an example
  that will likely have problems with this command, as the character
  sequence has already been stored as persistent commits.

It is a control code for carriage return. Windows uses the LF/CR notation for line delimiters, while UNIX systems used only LF.
Below should do it for all files recursively down the file system tree relative to the current directory.
find . -type f | xargs -Ix sed -i.bak -r 's/\r//g' x

The code above will make automatic backups (with extension .bak appended to the file name).
Once you made sure the files are good, use the following to delete the backups.
find . -type f -name '*.bak' | xargs -Ix rm x


text:
Q: Why is my specific selector not working with nth-of-type() and nth-child()? I am still a beginner and I can not find the mistake in my code. Your help would really be appreciated so I can learn the basics right.
I want to change the background of the class="post-content" in every even post to red.
It is not working. If I just change it in every post it is totally fine. But the moment I use the child or type selector it just applies it to both posts.
If I try to change the class="container" and then specify with the child or type selector it works on every even post. Why does it not function on the "post-content" class?
Html

           Me

Today

Post1

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
              tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
              quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
              consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
              cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
              proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

           Ahmad

Today

Post2

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
              tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
              quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
              consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
              cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
              proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

CSS
.container:nth-of-type(2n+0)  {
 background-color: #f2f2f2;
}

`works (with child or type)`

.post-content {
  background-color: red;
}

`works as well, all posts are now red`

.post-content:nth-of-type(2n+0){
  background-color: red;
}

`does not work, both post backgrounds are still red (if I try the odd ones, none is red)`

A: the nth-of-type pseudo selector is applied to a group of sibling elements see the docs. Since in your div with class post is only one element of the class post-content. This element is always on position 0 therefore 2n+0 (which could be just written as 2n will match them.
To achieve what you want you should use: .container:nth-of-type(2n) .post-content { ... } as selector. This will first select every second div with the container class and then apply the stuff to the div with the post-content class in it. To learn more about CSS selectors, I'd recommend taking a look at https://flukeout.github.io/, you'll need to provide different selectors including nested to pass the levels.
Explanation (run the snippet for a visual example)

.foo {
  background-color: coral;
  padding: 0.6em;
  border: 1px solid #333333;
  margin: 0.2em;
}

.foo:nth-of-type(2n) {
  background-color: lightblue;
}

.foo .foo {
  margin-left: 1.2em;
}

    Foo even (foo within .wrapper at index 0)

      Foo even (foo within .foo, at index 0)

      Foo odd (foo within .foo, at index 1)

      Foo even (foo within .foo, at index 2)

    Foo odd (foo within .wrapper at index 1)

    Foo even (foo within .wrapper at index 2)

What hapend in your case, was the nested example, since, all of your .post-content elements where the first element in their scope, they where always selected.


text:
Q: What would be a good particle point-of-view model of a self-gravitating molecular cloud: with orbit or not? Excuse my poor English, I have a lot to learn.
Should we imagine a particle falling directly to the center without an orbit like an apple falling from a tree to Earth, converting its potential energy into kinetic energy or a particle orbiting the center, like a planet around a star, an orbit that decreases as the particle converts its potential energy into kinetic energy. Also, what comes before, cloud collapse or thermal radiation release, i.e. cloud collapse that causes thermal radiation to be released or thermal radiation release that causes the cloud collapse? If I want to do calculations, do I have to put all the mass of the cloud in the center?
Does the particle, when it emits thermal radiation, immediately lose kinetic energy to regain more as it converts its potential energy or does its kinetic energy only increase in the process, i.e. there is no momentary drop in kinetic energy.
I watched a video on the subject - a link that directs to the video in question is quoted at the bottom of the details - and it wasn't clear.
https://youtu.be/ULYK_9NwN28

A: It doesn't make sense to think about the particles in a gas cloud being in orbit. The particles bump into each other and change their motion frequently. A gas cloud is supported by pressure, not orbital motion. However, if the cloud is systematically rotating that would be an additional source of (centrifugal) support.
In terms of what comes first, radiation or contraction - it is radiation that causes contraction. If the gas cloud has a temperature it will radiate, whatever its state of (dis)equilibrium.
If the gas cloud is spherically symmetric then you can assume that a particle is under the gravitational influence only of the mass interior to its radius, and that mass can be considered to be placed at the centre.


text:
Q: How to lock down image on CSS Hi I am trying to set the image to be locked meaning that i want the images not to be moved able although the website being minimize.
MY CSS :
.header-shadow{
    background-image: url('../images/aTOP1.png');
    background-repeat: no-repeat;
    width:180px;
    height:180px;
    left: 348px;
    top: 705px;
    position: absolute;
    display: block;

}

HTML :

                    星光传奇

                    鬼速战

                    时空之门

                    91GAME

                    暗夜传说

                    KING

IMAGE that move :

A: .header-shadow{
    background-image: url('../images/aTOP1.png');
    background-repeat: no-repeat;
    width:180px;
    height:180px;
    left: 348px;
    top: 705px;
    position: fixed;
    display: block;

}

*

*just change position absolute to fixed.