text:
Q: Crawling simple web site at certain depth by Scrapy I want to scrape a 3-depth web site about some problems and answers. It has a simple structure like the following:

*

*2nd depth -> contain meta data (problems description)

*3rd depth -> contain actual data (problems and answers)
  /prob
    +-> /prob/problemLists.html
      +-> /prob/problem123456.html

I wrote Scrapy code like the following, using response.meta['depth'] as condition.
Are there any better ways to do that?
class DmzSpider(CrawlSpider):
    rules = (
         Rule(SgmlLinkExtractor(deny=('index\.htm',callback='parse_list'))),
    )

    def parse_list(self, response):
        if response.meta['depth'] == 2:
        # Scrape descriptions ...
        return items

        elif response.meta['depth'] ==3:
            parse_item(response)

    def parse_item(self, response):
        # Parse items and save it according to prob_id...

        return items

Also I have tried the 3 following options, noone of them worked and the request_depth_max=1 at summary:

*

*Adding:
from scrapy.conf import settings
settings.overrides['DEPTH_LIMIT'] = 2
to spider file

*running the command line with -s option:
/usr/bin/scrapy crawl -s DEPTH_LIMIT=2 mininova.org

*Adding to settings.py and scrapy.cfg:
DEPTH_LIMIT=2

How should it be configured to more than 1?

A: You can set the depth limit to 3 in this case, see the settings page in Scrapy documentation


text:
Q: Does the Vimeo Unity SDK allow Vimeo livestreams to display in my Unity App? Im interested in using the Vimeo Unity SDK to display Vimeo livestreams in our app. We plan to have the app built both for Unity WebGL and Mobile.
Can someone confirm if this is possible using Vimeo Unity SDK? I know it allows for uploaded videos to be streamed, but does it also allow for livestreams to be displayed?
Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Proof about rational sequences
I'm stuck on part (iii). I wanted to use induction, but i'm having trouble proving the base case, which I took as n=3. Perhaps this was the wrong idea, but we'll see.
The only thing we know anything is $x_1$, so I wrote $x_3$ in terms of $x_2$ which I in turn wrote in terms of $x_1$.
I've reduced the expression of $x_3$ down to:
$$ {\large x_3} = \frac{\dfrac{x_1^{4}}{2} + ax_1^{2} + \dfrac{a^{2}}{2} + ax_1}{x_1^{2} +a}$$
but I still don't see how I can get the result I want. I was thinking of taking a limit, but $x_1$ is fixed, can I take a limit on $a$?

A: We want to show first that $x_2^2 \ge a$. (We have $x_2^2=a$  if $x_1=\sqrt{a}$.) So we want to show that
$$\left(\frac{x_1^2+a}{2x_1}\right)^2\ge a.$$
Equivalently, we want to show that
$$(x_1^2+a)^2\ge 4x_1^2 a,$$
or equivalently that
$$(x_1^2-a)^2\ge 0.$$
This is obvious.
I will stop here. The induction step is essentially a repeat of the above, and does not even use the induction hypothesis!

A: An idea putting $\;x_0:=a\;$:
$$x_1:=\frac{x_0^2+a}{2x_0}=\frac{a+1}{2}\implies x_2^2=\left(\frac{x_1^2+a}{2x_1}\right)^2=\left(\frac{\frac{(a+1)^2}4+a}{a+1}\right)^2=\left(\frac{a^2+6a+1}{4a+4}\right)^2$$
Thus, we get that
$$x_2^2>a\iff\frac1{16}(a^2+6a+1)^2>a(a+1)^2\iff$$
$$\iff a^4+12a^3+2a^2+36a^2+12a+1>16a^3+32a^2+16a\iff$$
$$\iff a^4-4a^3+6a^2-4a+1>0\iff (a-1)^4>0$$


text:
Q: Trying to run retries on before() Method before failing a test I have an unstable ENV which im running JUnit tests on.
Many tests fails on before() method because connection/network/non test related issues and I want to add a feature that retries a before method - before failing the test completely.
I've added the code snippet but im not sure this is the best way/practice to do so...
//hold the max number of before attempts
final private int retries = 3;
//will count number of retries accrued
private int retrieCounter = 0 ;

@Before
public void before() {
    try {
        //doing stuff that may fail due to network / other issues that are not relevant to the test
        setup = new Setup(commonSetup);
        server = setup.getServer();
        agents = setup.getAgents();
        api = server.getApi();
        setup.reset();
    }
    //if before fails in any reason
    catch (Exception e){
        //update the retire counter
        retrieCounter++;
        //if we max out the number of retries exit with a runtime exception
        if (retrieCounter > retries)
            throw new RuntimeException("not working and the test will stop!");
        //if not run the before again
        else this.before();
    }

}

A: You can use a TestRule for this, please look at my answer to How to Re-run failed JUnit tests immediately?. This should do what you want. If you use the Retry rule defined in that answer, this will actually re-execute the before() if it throws an exception:
public class RetryTest {
  @Rule
  public Retry retry = new Retry(3);

  @Before
  public void before() {
    System.err.println("before");
  }

  @Test
  public void test1() {
  }

  @Test
  public void test2() {
      Object o = null;
      o.equals("foo");
  }
}

This produces:
before
test2(junit_test.RetryTest): run 1 failed
before
test2(junit_test.RetryTest): run 2 failed
before
test2(junit_test.RetryTest): run 3 failed
test2(junit_test.RetryTest): giving up after 3 failures
before


text:
Q: Excel - How to delete specific parts of url in new column I have an excel column that has a list of URLs, I'm attempting to update the existing URLs with a new schema. There are over thousands of ones to update so I am attempting on creating a function that can handle this for me.
Here is an example of some of my entries.
/online-sales/new-jersey/online/top-selling-items-in-new-jersey.html
/retail-sales/new-york/online/top-selling-retail-shops-in-new-york.html
They all follow the same url schema. I would like for my end result to remove the first half of the url and the in-state.html at the end.
I've attempted using this function =REPLACE(A1,1,79,"") which could give me the result I'm expecting but each cell may have a different position so I'm stuck on how to use create this function and make it dynamic if possible.
This is my expected outcome:
/online/top-selling-items/
/online/top-selling-retail-shops/

A: If you have Windows Excel 2016+ with the TEXTJOIN and FILTERXML functions, you can try:
="/" &LEFT(TEXTJOIN("/",TRUE,FILTERXML("<t><s>" & SUBSTITUTE(A1,"/","</s><s>")&"</s></t>","//s[position()=2]|//s[last()]")),FIND("-in-",TEXTJOIN("/",TRUE,FILTERXML("<t><s>" & SUBSTITUTE(A1,"/","</s><s>")&"</s></t>","//s[position()=2]|//s[last()]")))-1) & "/"

If you don't have those functions, you can use the following:

*

*Define a Named formula: Formula-->Define Name

name: seq
Refers to: =ROW(INDEX(Sheet1!$A:$A,1):INDEX(Sheet1!$A:$A,255))

Then use this formula:
=CONCATENATE("/", INDEX(TRIM(MID(SUBSTITUTE(A1,"/",REPT(" ",999)),IF(seq=1,1,(seq-1)*999),999)),2),"/",LEFT(INDEX(TRIM(MID(SUBSTITUTE(A1,"/",REPT(" ",999)),IF(seq=1,1,(seq-1)*999),999)),SUM(N(LEN(TRIM(MID(SUBSTITUTE(A1,"/",REPT(" ",999)),IF(seq=1,1,(seq-1)*999),999)))>0),1)),FIND("-in-",INDEX(TRIM(MID(SUBSTITUTE(A1,"/",REPT(" ",999)),IF(seq=1,1,(seq-1)*999),999)),SUM(N(LEN(TRIM(MID(SUBSTITUTE(A1,"/",REPT(" ",999)),IF(seq=1,1,(seq-1)*999),999)))>0),1)))-1),"/")

Both formulas

*

*Split the string into "nodes" delimited by the /

*Return the 2nd and last node concatenated with /

*

*Note that the first node will be blank since your strings start with the delimiter.

*Using LEFT and FIND, return only the portion of the last node that is before the -in-

*Prepend and append a / to the string.

NOTE: if, in the last node, there might be more than one -in-, the formula will need modification
Both return the same result:


text:
Q: How to merge two different groupings if they are not disjoint with dplyr Suppose that I have two sets of identifiers id1 and id2 in a data frame. How can I create a new identifier id3 that works as follows:
I consider id1 as the stricter key, so that observations are first grouped in id1 and then in id2. If there are two sets of rows with different values of id2 that have some of its elements with the same id1, these two sets should have the same value for id3 (the exact value in id3 doesn't matter much).
 df <- data.frame(id1 = c(1, 1, 2, 2, 5, 6),
             id2 = c(4, 3, 1, 2, 2, 7),
             id3 = c(1, 1, 2, 2, 2, 3))

Rows 1 and 2 are grouped together because they have the same id1. Rows 3, 4 and 5 are grouped together because 3 and 4 have the same id1 and 4 and 5 have the same id2.
Can someone help? I would rather have a solution with dplyr that encompasses a general case in which there is an arbitrary number of possible values in the id columns.

A: This is a graph theory problem. Each id1 and id2 is a separate node and df gives the links between them. You are looking to see which weakly connected clusters each id belongs too.
library(igraph)
df <- df %>% mutate(from = paste0('id1', '_', id1), to = paste0('id2', '_', id2))
dg <- graph_from_data_frame(df %>% select(from, to), directed = FALSE)
df <- df %>% mutate(id3 = components(dg)$membership[from])
df %>% select(id1, id2, id3)

#>   id1 id2 id3
#> 1   1   4   1
#> 2   1   3   1
#> 3   2   1   2
#> 4   2   2   2
#> 5   5   2   2
#> 6   6   7   3


text:
Q: Limit number of trailing zeroes for fixed output I need some help with output formatting using C++ streams. I would like to print numbers with a fixed decimal point and at most 2 trailing places. I have tried the following:
#include <iostream>
#include <iomanip>
using namespace std;

int main(int argc, char **argv)
{
  float testme[] = { 0.12345, 1.2345, 12.345, 123.45, 1234.5, 12345 };

  std::cout << std::setprecision(2) << std::fixed;

  for(int i = 0; i < 6; ++i)
  {
      std::cout << testme[i] << std::endl;
  }

  return 0;
}

The output is:
0.12
1.23
12.35
123.45
1234.50
12345.00

But I would like to have
0.12
1.23
12.35
123.45
1234.5
12345

Can I achieve this without using additional string manipulation?

A: I am not aware of a suiting manipulator, hence you might use:
#include <iostream>
#include <iomanip>
#include <cmath>

template <typename T>
struct Fixed
{
    const T& value;
    const unsigned precision;
    const T significant;

    Fixed(const T& value, unsigned precision)
    : value(value), precision(precision), significant(std::pow(10, precision))
    {}

    void write(std::ostream& stream) const {
        // Adjust stream settings
        std::ostream::char_type restore_fill = stream.fill('0');
        std::ios_base::fmtflags restore_flags = stream.setf(
            std::ios_base::fixed, std::ios_base::floatfield);
        std::streamsize restore_precision = stream.precision(0);

        // Split the floating point into an integral and rounded fractional part
        T integral;
        unsigned long fractional = std::round(significant * std::modf(value, &integral));

        // Determine the length of the fractional part
        unsigned digits = precision;
        while(fractional && fractional % 10 == 0) {
            fractional /= 10;
            --digits;
        }

        // Carry over to the integral part
        if( ! digits && fractional) {
            integral += 1;
            fractional = 0;
        }

        // Output
        stream << integral;
        if(fractional) {
            stream <<  '.' << std::setw(digits) << fractional;
        }

        // Restore stream settings
        stream.precision(restore_precision);
        stream.flags(restore_flags);
        stream.fill(restore_fill);
    }
};

template <typename T>
inline Fixed<T> fixed(const T& value, unsigned precision) {
    return Fixed<T>(value, precision);
}

template <typename T>
inline std::ostream& operator << (std::ostream& stream, const Fixed<T>& value) {
    value.write(stream);
    return stream;
}

int main(int argc, char **argv)
{
  float testme[] = { 0.12345, 1.2345, 12.345, 123.45, 1234.5, 12345 };
  for(int i = 0; i < 6; ++i)
  {
      std::cout << fixed(testme[i], 2) << std::endl;
  }

  return 0;
}

A: This works (http://ideone.com/CFcVhu), but it is not that beautiful ...
#include <iostream>
#include <iomanip>
using namespace std;

int main(int argc, char **argv)
{
  float testme[] = { 0.12345, 1.2345, 12.345, 123.45, 1234.5, 12345 };

  //std::cout << std::setprecision(2) << std::fixed;

  for(int i = 0; i < 6; ++i)
  {
      std::cout << ((int)(testme[i]*100.0))/100.0f << std::endl;
  }

  return 0;
}

A: In other words, you want to represent a number using 2 decimal digits if it's smaller than 1000 (always positive?), 1 decimal if it's smaller than 10000 and zero otherwise. Hmm, how could one codify this?


text:
Q: restrict the function input to be float32 NumPy array Is there a way to restrict the type of function input in python or I should always convert the input NumPy array to be float 32 array if I want?
I am trying to restrict the function input argument type to be a float 32 NumPy array. I have try something like below:
import numpy as np

def f(input : np.float32):
    return input*2

However, if I give an int NumPy array, the function is still work and return an int array.

A: Read more about Python Annotations here PEP3107.
Annotations doesn't force the function to accept input as the specified type.
Access annotations by,
print(f.__annotations__) in your case.
You can use yourlist.astype(np.float32) to force the list argument to be NumPy float32.
def f(input : np.float32)-> np.float32:
    return input.astype(np.float32)*2


text:
Q: Simultaneous diagonalizability of three endomorphisms So I understand two endomorphisms on a finite dimensional vector space are simultaneously diagonalisable if (and only if) they commute.
But suppose we have three endomorphisms a, b and c.
What is the 'iff' condition for simultaneous diagonalisability here. Is it pair wise commute or is it, say, a commutes with both b and c.
The question arises from quantum mechanics.
Thanks in advance.

A: Strictly speaking, one should specify that the endomorphisms are diagonalisable; there exists commuting matrices (and thus endomorphisms) which are not all diagonalisable. (Just take for example the identity and a non-diagonalisable endomorphism)
In general, one has that for $A_1, \ldots , A_r$ diagonalisable endomorphisms on a finite dimensional vector space, that they are simultaneously diagonalisable if and only if they commute. (i.e. pairwise commute) A proof can be found here, Theorem 5.1.


text:
Q: Create a grid with checkboxes in R shiny I am trying to create a grid which has its rows and column names as variables in a particular data set so that I can map individual rows for regression in r on backend (where row names will be dependent variable and column names will be independent variables). Can anybody help on how to approach towards this problem.
I am trying to get something like this on my app. when a user selects lets say app and alerts and when he presses the submit button it does the regression on the backend i.e website ~ app + alerts
I dont have any code right now because i am very new to r shiny and dont know how to create this grid with checkboxes. If anyone could just guide me on how to approach that would be very helpful.
Thanks

A: You can create table with checkboxes (or other active elements) using DT package. Please see the code below (based on "Showing as Checkbox" anwser:
library(shiny)
library(DT)

# create data.frame of row/column names of futre datable
my_df <- data.frame(nam = c("Favorite1", "Favorite2"))

runApp(
  list(
    ui = fluidRow(
      sidebarLayout(
      h2("Checkboxes Datatable"),
      DT::dataTableOutput("mytable", width = "1%")),
      mainPanel(h2("Selected"),
      tableOutput("checked"))
    ),
    server = function(input, output) {

    # helper function for making checkbox
    shinyInput <- function(FUN, len, id, ...) {
      inputs <- character(len)
      for (i in seq_len(len)) {
        inputs[i] <- as.character(FUN(paste0(id, i), label = NULL, ...))
      }
      inputs
    }
    # datatable with checkbox
    output$mytable <- DT::renderDataTable(
      expr = {
        df <- data.frame(
        #  my_df,
          my_df,
          Favorite1 = shinyInput(checkboxInput, nrow(my_df), "cbox1"),
          Favorite2 = shinyInput(checkboxInput, nrow(my_df), "cbox2")
        )
        names(df)[1] <- " "
        df
      },
      rownames = FALSE,
      server = FALSE,
      escape = FALSE,
      options = list(
        ordering = FALSE,
        searching = FALSE,
        paging = FALSE,
        info = FALSE,
        preDrawCallback = JS("function() {
          Shiny.unbindAll(this.api().table().node()); }"
        ),
        drawCallback = JS("function() {
          Shiny.bindAll(this.api().table().node()); } "
        )
      )
    )

    # helper function for reading checkbox
    shinyValue <- function(id, len) {
      unlist(
        x = lapply(
          X = seq_len(len),
          FUN = function(i) {
            value = input[[paste0(id, i)]]
            if (is.null(value)) {
              NA
            } else {
              value
            }
          }
        )
      )
    }
    # output read checkboxes
    output$checked <- renderTable({
      data.frame(
        Favorite1 = shinyValue("cbox1", nrow(my_df)),
        Favorite2 = shinyValue("cbox2", nrow(my_df))
      )
    }
  )
 }
  )
)

Output (checkboxes clicked in the upper table show their status at lower one):


text:
Q: regex / heuristic to detect repetitive words e.g. "gfgfgfgf" "dadadada" "sdsdsd" How can we search for repetitive patterns in word(s) using regex in order to detect "junk" or dummy words such as "gfgfgfgfg" and similar, but not limit creative words like "aweeesssoome", "omggg" etc.
Examples:

*

*In the case of "gfgfgfgfg" regex search / detection / result should be positive ("gf" base pattern detected, which ultimately constructs the entire word, mind the "hanging" final character "g")

*In the case of word "aweesooomee" it should return false, as no repetitive pattern is used to construct the entire word.

re possible duplicate mark by rsjaffe:
Question Detect repetitions in string has a generic and not so "smart" solution I am looking for. As explained above, the solution / variation I'm currently using considerably reduces false positives detection. Simple test in the link I've posted on regex101.com can serve as a proof and see why it does not satisfy my requirements.
Additional explanation:
Above method detects repetitions from neighboring words, as well, and limits creative ("valid") words, which is not a desirable effect.
Examples:
"this is" -- detects "is" as repetitions in 2 separate words ("is is" pattern match).
"awesoooommeee" -- detects repetitions of single letters like "o", "m" and "e".

Searching for this solution proved to be a bit hard to find, so I'm forced to ask the question.
First, a bit of a background story:

*

*I run a blog

*I have a post about reCaptcha

*Sometimes (every week or so) someone tries to be funny and posts spam comments in the similar form to this:

gfgfgfgf
sdsdsdsds
dadadada

You get the idea. Are they testing an automated reCaptcha bypass systems as a proof of concept or just trying to be funny, I don't know and I don't really care (most probably a mix of both).
(edit) Interestingly enough, no other posts are affected by this type of spam comments.
However, thinking about this, it should be relatively simple and easy to detect patterns in the (mostly) single words which those comments have (99%) and prevent those comments from posting. Sounds simple?
But, it must also be good enough to avoid false positives.
If, for example, a comment has single repetitive word like above, then it's definitely a spam.
If, on the other hand, it just has a typo in the middle of the normal sentence, it should pass.
Now, I can already 'hear' comments below why not use Akismet. Or solution X. Or solution Y. Why not external comments system like Disqus or Facebook comments. Because, I can't. It must be in-house. And I wish to be simple. I already have some things that prevent a lot of junk, but for this particular case they all fail.
Solution(s) that I have tested so far:
This is one regex example that is a variant of this answer here, but it's not perfect:
(.+\w)(?=\1+)/gu

see live regex101 example
Problems with it is that in examples below it will pass most of the time, but it will trigger false positives, too:
correct/proper detection:

123123123123
daddaddaddad
sadsadasad
sadsadsad
121212121
sasasasasas
sdsdsdsds
dsdsdsdsd
ffffffff
blahblah
ioiooioioioi
popopopopop
Hi I dont think this is a spam.

improper/incorrect detection (false positive):

I loooovve this. It's awesooooommeee!

Now, this is tricky. The filter does exactly what it was instructed to do, however, "ooovv" and "oooommeee" patterns are not exactly repetitive in the same sense like the first ones listed above ("gfgfgfgf" etc.). Filter detects "oo" pattern repetition. Yes, correct, but not exactly what I want to target.
Does anyone have an idea how can I improve this regex detection to be smarter a bit?
Thanks!

A: I finally solved it! And with a single regex line :)
Searching for regex detect repetitive string I found the required clues.
This is the question: Matching on repeated substrings in a regex and the particular answer that inspired me to find a solution.
The solution is to use capturing groups and backreference in a slightly modified regex from above original answer in order to include both letters and numbers:
^([a-z0-9]{2,}).*(\1)$/gumi

Example: https://regex101.com/r/xG40cL/1
Another variation of above solution is to include single characters, so that both words with even and odd number of characters (even and odd symmetry) will also be matched (e.g. "ooo", "iii" etc.):
^([a-z0-9]{1,}).*(\1)$/gumi

Example: https://regex101.com/r/m9aqNk/1
It is still not perfect, but definitely better and closer to ideal case.
Sorry everyone for being such a pain, as now I understand the proper terminology I was seeking regarding regex (it's called backreference).


text:
Q: socket.io App to web chat I'm using socket.io to chat from user (App) to admin (to browser). here admin msg has been received properly to the user but user message not received by the admin. I'm following https://www.sitepoint.com/using-socket-io-and-cordova-to-create-a-real-time-chat-app/ for the chat application. Also there is App to App chat, which is working  fine for me.
here is my server side code
  socket.on('send:message', function (msg) {
    console.log("send:message", msg);
    if (msg.orderChat) var q = models.orderChat.create(msg)
    else var q = models.chat.create(msg)
    q.then(function (ret) {
        console.log(ret.get({ plain: true }));
        socket.in(msg.chat_room).emit('send:message', msg);
        //socket.emit('send:message', msg);
    }).catch(function (err) {
        console.log(err);
        socket.in(msg.chat_room).emit('send:message', 'Server Error');
    });
});

here is my Client side code
socket.on('send:message', function (msg) {
    username = $('.pchat').attr('data-username');
    console.log(msg);
    $("#chat_div_" + username).chatbox("option", "boxManager").addMsg(username, msg.message);
})

update
Also code work fine when to user chat in same browse but not in cross browse

A: I believe there are chance there are bugs outside of the code provided here,
In your Server side I have changed:
    socket.in(msg.chat_room).emit('send:message', msg);

to
socket.in(msg.chat_room).emit('send:message', {
            message: msg
        });

Though if you could provide your full code I'll be able to help you troubleshoot further.


text:
Q: Vue.js: Target other div than the bound one within vue object I'm using Vue and Leaflet for displaying polygons (zones) on a map and display appropriate information (messages) about the specific polygons after clicking on them on the map. The div, where I render the messages in, has the id "#messagearea" and is bound to the "el" object. To display the appropriate messages, I am dependant on the "Zone-id".
Now I also want to display information into another div with a different id. I am also dependant on the "Zone-id" here, so I would like to do this in the same Vue. If I would create another Vue, I would have to render the Leaflet map again to write another polygon.on('click',...) function, which displays appropriate information for the polygons. What is the most elegant and/or easiest way to realize this?
Here my vue object:
var mapVue = new Vue({
    el: '#messagearea',
    data: {
        function() {
            return {
                map: false
            };
        },
        zones: [],
        messages: [],
    },
    ready: function () {
        this.map = L.map('map').setView([51.959, 7.623], 14);
        L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors'
        }).addTo(this.map);
        this.$http.get('/api/zones', function (data) {
            this.$set('zones', data);
            for (var i = 0; i < this.zones['Zones'].length; i++) {
                polygon = L.polygon(
                    this.zones['Zones'][i]['Geometry']['Coordinates']).addTo(this.map);
                polygon.bindPopup(this.zones['Zones'][i]['Name']);
                polygon.on('click', messageCallback(i))
              // HERE I WOULD LIKE TO ADD THE FUNCTION FOR THE OTHER DIV
            }
            function messageCallback(i) {
                return function () {
                    mapVue.getMessages(mapVue.zones['Zones'][i]['Zone-id']);
                }
            }
        });
    },
    methods:
    {
        getMessages: function (id) {
            this.$http.get('/api/messages?zone=' + id, function (data) {
                console.log("messages called");
                this.$set('messages', data['Messages']);
            });
        }
    }
})

A: I solved this issue by making use of Vue.component(), the vue.$dispatch() and vue.$broadcast() functions. I just dispatched the zone id to a parent component and then delivered it with the broadcast function to all child components, which are in need of the zone id. Displaying the appropriate messages was no problem then anymore.


text:
Q: Does using fact tblname in all DAX fucntions result in table expansion? Given a model with fact table having multiple dimension tables, Does using the fact tblname in all DAX fucntions result in table expansion?
Example:
SUMX(tblname, expr)
CALCULATE(expr, FILTER(tblname, criteria))

A: Yes, when a relationship exists, there is an expanded table.
In the first example
SUMX(tblname, expr)

the iterator creates a row context over the tablname. RELATED must be used to access fields in the tblname expanded tables that are not parte of tablename, but reachable through a many to one relationship.
in the second example
CALCULATE(expr, FILTER(tblname, criteria))

the FILTER is an iterator and therefore it works like in the first example.
The table returned by FILTER inside CALCULATE acts as an expanded table, therefore affecting not only the existing filters over tblname, but also the existing filters over the columns that are part of the tblname expanded table.
For instance, assuming to have a model with a table Customers and a table Sales with a one to many relationship between Customers and Sales, in this code
CALCULATE([Sales Amount], FILTER(ALL(Sales), Sales[Quantity] > 2))

the FILTER returns a filtered Sales expanded table that removes any existing filter over Customers table.


text:
Q: A man, woman, boy, girl, cat, and dog are walking down a path.. I'm hoping someone can explain how this works.
The problem:
A man, woman, boy, girl, cat, and dog are walking down a path in single file.
How many ways can this happen if the dog is between the man and the boy?
The given solution: There are $2*4!  = 48$ lines with the dog directly between the man and the boy.  There are $3 * 2 * 2 * 3! = 78$ lines with the dog and one other between the man and boy.   There are $3*3!*2*2 = 78$ lines with the dog and two others between them.  There are $4! *2 = 48$ lines with the dog and the other 3 between them.   so there are a possible $48+72+72+48 = 240$ possible lines with the dog between the man and the boy.
The way I went about this was that there are $6!$ total possible lines and $3!=6$ possible orders.   In two of those orders, the dog is between the man and boy.   So the possibility of having the dog between them is  $\frac{2}{6} * 6! = 240$.
What I don't understand is where the numbers they came up with for each solution came from.   For example, There are $3*3!*2*2 = 78$ lines with the dog and two others between them. Where do these numbers comes from?

A:

There are 3∗3!∗2∗2=78 lines with the dog and two others between them.

So we consider (man, _, _, _, boy). We begin by choosing two of the three (woman, cat, girl). We then permute those two with the dog in the three slots. So $\binom{3}{2} = 3$ ways to choose two remaining persons. There are $3!$ ways to permute the two chosen with the dog in the slots between the man and boy. We then consider the symmetry case of the boy appearing before the man (the first two). Finally, we have one unchosen person, which could appear at the front or end of the line (the second two).

A: We do the example you specifically asked about.
We have Man, Boy, Dog, and $3$ others.
So the "two others" can be selected in $3$ ways. (We are leaving out one.) For each of these choices, Dog and the two others can be arranged in $3!$ way. For each of these, the Man can be ahead of the Boy or behind ($2$ choices). And for each such choice, the leftover other can be leading the band, or at the tail end ($2$ choices).  Multiply.
Your way of course is much better.


text:
Q: c++ undefined symbol when compiling FIXED: had the method twice in the header file
I get the following error when trying to compile my project
% make
g++ -o p4 testTree.o tree.o node.o check.o
Undefined                       first referenced
 symbol                             in file
Tree::inTree(int)                   tree.o
ld: fatal: Symbol referencing errors. No output written to p4
collect2: ld returned 1 exit status
*** Error code 1
make: Fatal error: Command failed for target `p4'

Makefile
p4: testTree.o tree.o node.o check.o
    g++ -o p4 testTree.o tree.o node.o check.o
testTree.o: testTree.cc tree.h node.h check.h
    g++ -c -Wall -Werror testTree.cc

tree.o: tree.h tree.cc node.h check.h
    g++ -c -Wall -Werror tree.cc
node.o: node.h node.cc check.h
    g++ -c -Wall -Werror node.cc
check.o: check.h check.cc
    g++ -c -Wall -Werror check.cc
clean:
    rm -f *~ *.o p4

Relevant code from tree.cc and tree.h:
tree.cc
...
bool Tree::inTree(int k) const
{
     return locate(k,root) != NULL;
}
...

tree.h
#ifndef TREE_H
#define TREE_H

#include "node.h"
#include "check.h"
using namespace std;
class Tree
{
  private:
    Node *root;
  public:
    Tree();
    Tree(const Tree & t);
    const Tree & operator=(const Tree &t);
    friend ostream & operator<<(ostream &out, const Tree &t);
    bool inTree(int k) const;
    double & operator[](int k);
    double & operator[](int k) const;
    ~Tree();
    bool inTree(int index);
  private:
    Node * locate(int k, Node *rt) const;
    ostream & display(ostream &out, Node *r, int dir=Node::L) const;
    void add(int k, Node*&r);
    void kill(Node *&rt);
    void copy(Node *rt, Node *&newRt);
};
#endif

I get the feeling that it's something really simple, but I can't seem to figure it out.

A: Here is your error:
bool Tree::inTree(int k) const
{
 return locate(k,root) != NULL;
}

in your .h you define
bool inTree(int);

This is a difference!

A: The message you are getting actually comes from the linker, not from the compiler.
One of your member functions, bool Tree::inTree(int index);, is correctly declared and defined as a const member function:
 // Declaration in tree.h
 bool inTree(int index) const;

 // Definition in tree.cc
 bool Tree::inTree(int k) const
 //                       ^^^^^

However, in tree.h you also define this non-const overload of inTree():
// Declaration in tree.h, definition (supposedly) nowhere
bool Tree::inTree(int k)

For which no definition is provided. This is what the linker complains about.


text:
Q: Is there an R function to clean via a custom dictionary I would like to use a custom dictionary (upwards of 400,000 words) when cleaning my data in R. I already have the dictionary loaded as a large character list and I am trying to have it so that the content within my data (VCorpus) compromises of only the words in my dictionary.
For example:
#[1] "never give up uouo cbbuk jeez"

would become
#[1*] "never give up"

as the words "never","give",and "up" are all in the custom dictionary.
I have previously tried the following:
#Reading the custom dictionary as a function
    english.words  <- function(x) x %in% custom.dictionary
#Filtering based on words in the dictionary
    DF2 <- DF1[(english.words(DF1$Text)),]

but my result is a character list with one word. Any advice?

A: Since you use a dataframe you could try this:
library(tidyverse)
library(tidytext)

dat<-tibble(text="never give up uouo cbbuk jeez")
words_to_keep<-c("never","give","up")

keep_function<-function(data,words_to_keep){
 data %>%
  unnest_tokens(word, text) %>%
  filter(word %in% words_to_keep) %>%
  nest(text=word) %>%
  mutate(text = map(text, unlist),
         text = map_chr(text, paste, collapse = " "))
  }

keep_function(dat,words_to_keep)

A: You can split the sentences into words, keep only words that are part of your dictionary and paste them in one sentence again.
DF1$Text1 <- sapply(strsplit(DF1$Text, '\\s+'), function(x)
                    paste0(Filter(english.words, x), collapse = ' '))

Here I have created a new column called Text1 with only english words, if you want to replace the original column you can save the output in  DF1$Text.


text:
Q: OneDrive procedure for making product live? I am going into the final stages for releasing my product which uses OneDrive and I was not able to find any sort of procedure for doing so online. For Dropbox I had to apply for production and get reviewed, does OneDrive have similar requirements?

A: There is no such process for OneDrive. No special steps need to be taken to release an app that utilizes OneDrive APIs


text:
Q: Alternate Methods For Working with ZST Files in R? I am working with the R programing language.
I have large .ZST files on my computer that I want to import in to R Studio (e.g. https://files.pushshift.io/reddit/comments/).
I found this library in R https://github.com/thekvs/zstdr - but apparently this library is not available for Windows and is very difficult to install.
I tried looking online, but there really does not seem to be any other way to work with these .ZST files.
Can someone please show me a way in R to import and work with these .ZST files without downloading this library? Is there some direct way to do this while working "natively" in R?
Thanks!


text:
Q: Hibernate composite id merge I'm using Hibernate with JPA and have a relation like this:
@Entity
@Table(name = "first")
public class First {
...
@OneToMany(mappedBy = "first")
private List<Availability> availabilities;
...
}

@Entity
@Table(name = "second")
public class Second {
...
@OneToMany(mappedBy = "second")
private List<Availability> availabilities;
...
}

@Entity
@Table(name="availability")
public class Availability implements Serializable {
@Id
@ManyToOne
@JoinColumn(name = "first_id")
private First first;

@Id
@ManyToOne
@JoinColumn(name = "second_id")
private Second second;

@Column(name = "availability")
private Integer availability;

...
hashcode and equals
}

I want to manage these 3 entities separately. First and Second work fine, but when I try to merge() the third one postgresql gets a null value instead of the id's and constraint violation exception is thrown. Why? Can I even use merge on this entity to add new rows to the table?
update:
The merge is something like this:
public Availability setAvailability(Availability a) {
return em.merge(a);
}

where the availability is deserialized from front-end (just to mention, the collections of "key" classes are detached in it).

A: You already solved your issue, but I leave here a suggestion for users that need to use multiple-columns primary keys and can't change the database.
Apparently, using multiple @Id annotations by themselves produces an inconsistency when trying to merge: you assign all fields, and then during the merge the fields annotated with @Id get assigned null values (and the merge fails). I can guess an explanation: hibernate doesn't expect there to be a non-managed object with assigned @Ids; but this is an issue only with multiple column primary keys, so it seems to be a bug.
Note: calling persist instead of merge works (but in some cases you would duplicate rows or get database constraint errors, because the primary key in this case is checked only at database level).
I solved a similar issue using @IdClass. In your old code you would have to:

*

*Create a class (for example AvailabilityId) with fields first and second (matching exactly the fields annotated with @Id in class Availability), and overriding equals and hashCode methods

*No annotations are required in AvailabilityId other than @Override (by the way, if you use @Column on both Availability and AvailabilityId fields you can get monstruous errors). This has not to be an entity or a table, it is a POJO.

*Annotate class Availability with @IdClass(AvailabilityId.class)

That should be it. Sorry for being 3 years late, but if you got rid of your multiple column primary key you are in a better world now anyway.
I tried @EmbeddedId but it broke a couple of other requirements (easy json->object conversion and queries working both in SQL and HQL with minor adjustments).

A: I solved the problem by avoiding the use of Composite ID. After rethinking the problem I found out that this case I actually can use an unique constraint.
@Entity
@Table(name = "availabilities", uniqueConstraints = { @UniqueConstraint(columnNames = {
    "first_id", "second_id" }) })
@SequenceGenerator(initialValue = 1, name = "availabilities_sequence", sequenceName =     "availabilities_sequence")
public class Availability implements IAvailability, Serializable {

private static final long serialVersionUID = -2977047920673617888L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "availabilities_sequence")
@Column(name = "id")
private Integer id;

@ManyToOne
@JoinColumn(name = "first_id", nullable=false)
private First first;

@ManyToOne
@JoinColumn(name = "second_id", nullable=false)
private Second second;

@Column(name = "availability", nullable=false)
private Integer availability;

...
}


text:
Q: Coefficients of rational involution. Question:
(Spivak Calculus 3rd, Chapter 3, Problem 8)
For which numbers $a,b,c,d$ will the function
$$f(x) = \frac{ax + d}{cx + b}$$
satisfy $f(f(x)) = x$ for all $x$?
Attempt at an answer:
I tried to substitute $f(x)$ into itself, resulting in
$$f(f(x)) = \frac{a(\frac{ax + d}{cx + b}) + d}{c(\frac{ax + d}{cx + b}) + b} = \frac{(a^2 + cd)x + (a+b)d}{[(a+b)c]x+(b^2+cd)}$$
When this expression is set equal to $x$, I get an equation
$$[(a+b)c]x^2 + (b^2-a^2)x - (a+b)d = 0$$
Now, since this equation must hold for all $x$, I can select several arbitrary values, creating a system of as many equation as I want. This is where I am a little stuck; it seems that picking the correct values of $x$ is a matter of guessing and a little luck. Is there a better way to go about doing this?

A: Your computations are fine and, no, you don't need guessing or luck. Note that$$(a+b)cx^2+(b^2-c^2)x-(a+b)d=(a+b)\bigl(cx^2+(b-a)x-d\bigr)$$and this will be the null polynomial if and only if one of these things occur:

*

*$a+b=0$;

*$c=b-a=d=0$.

So, there are two types of solutions to your problem:

*

*the functions of the type $\displaystyle x\mapsto\frac{ax+d}{cx-a}$;

*the functions of the type $\displaystyle x\mapsto\frac{ax}a=x$.

Of course, this last type consist only of the identity function.


text:
Q: How to fetch Certificate from Azure Key vault to be used in docker image I am using a ssl certificate while building the docker image to communicate with other different services with in the Kubernetes. right now I have the ssl certificate in my repo and will be published as part of the artifact. we are planning to move the cert to key vault and fetch it while executing our pipeline. I am not sure how can I fetch it while building the docker image. I have tried the default azure key vault task and I am able to get the cert but its not a file(.crt or pfx).
Below is my final step in Docker Image
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
COPY $(ps-test-cert)  /usr/local/share/ca-certificates/ps-test-cert
RUN chmod 644 /usr/local/share/ca-certificates/ps-test-cert
RUN update-ca-certificates
ENTRYPOINT ["dotnet", "Logging.API.dll"]

and the cert name in the key vault is ps-test-cert
Here is my key vault task
    - task: AzureKeyVault@1
      inputs:
        azureSubscription: 'ARMDeployment-Service-Conn'
        KeyVaultName: 'OneK-KeyVault'
        SecretsFilter: 'ps-test-cert'
        RunAsPreJob: false

Do I have to get the cert and publish as artifact? since I need this in the build time not sure how should I import the cert so that I can use.
Update
I am able to get the certificate using azure cli with the below command. but I am not sure how will I use that inside docker file.When I publish I can see that the certificate is there in the published items.
> az keyvault certificate download --vault-name one-KeyVault -n
> ps-test-cert -f cert.pem openssl x509 -outform der -in cert.pem -out
> ps-test-cert.crt

in the publish task, I can use it like this.
- task: PublishPipelineArtifact@1
  displayName: 'Publish Pipeline Artifact'
  inputs:
    targetPath: 'ps-test-cert.crt'
    artifact: test

How can I use it in docker file?

A: Okay, Here is How I solved my current scenario. as updated in the question I was able to read the certificate from key vault. next piece was to access the cert within the docker file, since docker doesn't know the location(because its not part of the context), Its not able to read the cert. so, what I have done is used a copy task to add the cert to the source directory when docker context is set. then docker is able to see the certificate and access is(because its now in docker context).
below are the copy task, if that helps.
- task: CopyFiles@2
          displayName: 'Copy Files to: $(Build.ArtifactStagingDirectory)'
          inputs:
            Contents: |
              **\ps-test-cert.crt
            TargetFolder: '$(Build.SourcesDirectory)/Source/Logging.API/'

and in the docker file, I just have to use the name because its available inthe context.
COPY ps-test-cert.crt  /usr/local/share/ca-certificates/ps-test-cert.crt
RUN chmod 644 /usr/local/share/ca-certificates/ps-test-cert.crt
RUN update-ca-certificates

A:
How to fetch Certificate from Azure Key vault to be used in docker image

According to the Azure Key Vault task:

Use this task to download secrets such as authentication keys, storage
account keys, data encryption keys, .PFX files, and passwords from an
Azure Key Vault instance.
If the value fetched from the vault is a certificate (for example, a
PFX file), the task variable will contain the contents of the PFX in
string format.

So, this task will not download the certificate file directly. Then we could not use it in the dockerfile with syntax COPY $(ps-test-cert)  /usr/local/share/ca-certificates/ps-test-cert.
As workaround, you could use powershell scripts to download and import to the file:
- task: AzurePowerShell@5
  displayName: 'import certificates'
  inputs:
    azureSubscription: ToMicrosoft365Customers
    ScriptPath: '$(System.DefaultWorkingDirectory)/_Microsoft365/import-certificatesFromKeyvault.ps1'
    ScriptArguments: '-vaultname $(vaultname) -tempStoreLocation "D:\a\_temp\"'
    errorActionPreference: continue
    azurePowerShellVersion: LatestVersion
    pwsh: true

You could check this document Using KeyVault certificates in Azure DevOps for the powershell scripts and some more details.


text:
Q: SQLSRV Invalid parameter when converting DataTables from MySQL I am trying to convert this:
http://www.datatables.net/examples/server_side/server_side.html
Into using SQLSRV, this is my code so far:
<?php

ini_set("memory_limit",-1);
define('IN_INDEX', 1);
require_once 'config.php';

    $aColumns = array( 'ID', 'CardNumber');

    /* Indexed column (used for fast and accurate table cardinality) */
    $sIndexColumn = "ID";

    /* DB table to use */
    $sTable = "ActivityLog";

    /*
     * Paging
     */
    $sLimit = "";
    if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
    {
    $sLimit = "OFFSET  ".$_GET['iDisplayStart']." ROWS
                                FETCH NEXT ".$_GET['iDisplayLength']." ROWS ONLY ";
    }

    /*
     * Ordering
     */
    if ( isset( $_GET['iSortCol_0'] ) )
    {
        $sOrder = "ORDER BY  ";
        for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
        {
            if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
            {
                $sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
                    ".addslashes( $_GET['sSortDir_'.$i] ) .", ";
            }
        }

        $sOrder = substr_replace( $sOrder, "", -2 );
        if ( $sOrder == "ORDER BY" )
        {
            $sOrder = "";
        }
    }

    /*
     * Filtering
     * NOTE this does not match the built-in DataTables filtering which does it
     * word by word on any field. It's possible to do here, but concerned about efficiency
     * on very large tables, and MySQL's regex functionality is very limited
     */
    $sWhere = "";
    if ( $_GET['sSearch'] != "" )
    {
        $sWhere = "WHERE (";
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            $sWhere .= $aColumns[$i]." LIKE '%".addslashes( $_GET['sSearch'] )."%' OR ";
        }
        $sWhere = substr_replace( $sWhere, "", -3 );
        $sWhere .= ')';
    }

    /* Individual column filtering */
    for ( $i=0 ; $i<count($aColumns) ; $i++ )
    {
        if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
        {
            if ( $sWhere == "" )
            {
                $sWhere = "WHERE ";
            }
            else
            {
                $sWhere .= " AND ";
            }
            $sWhere .= $aColumns[$i]." LIKE '%".addslashes($_GET['sSearch_'.$i])."%' ";
        }
    }

    /*
     * SQL queries
     * Get data to display
     */
    $sQuery = "
        SELECT COUNT (*) OVER () AS ROW_COUNT ".str_replace(" , ", " ", implode(", ", $aColumns))."
        FROM   $sTable
        $sWhere
        $sOrder
        $sLimit
    ";
    $rResult = sqlsrv_query( $sQuery ) or die(print_r(sqlsrv_errors()));

    /* Data set length after filtering */
    $sQuery = "
        SELECT @@ROWCOUNT
    ";
    $rResultFilterTotal = sqlsrv_query( $sQuery ) or die(print_r(sqlsrv_errors()));
    $aResultFilterTotal = sqlsrv_fetch_array($rResultFilterTotal);
    $iFilteredTotal = $aResultFilterTotal[0];

    /* Total data set length */
    $sQuery = "
        SELECT COUNT(".$sIndexColumn.")
        FROM   $sTable
    ";
    $rResultTotal = sqlsrv_query( $sQuery ) or die(print_r(sqlsrv_errors()));
    $aResultTotal = sqlsrv_fetch_array($rResultTotal);
    $iTotal = $aResultTotal[0];

    /*
     * Output
     */
    $output = array(
        "sEcho" => intval($_GET['sEcho']),
        "iTotalRecords" => $iTotal,
        "iTotalDisplayRecords" => $iFilteredTotal,
        "aaData" => array()
    );

    while ( $aRow = sqlsrv_fetch_array( $rResult ) )
    {
        $row = array();
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            if ( $aColumns[$i] == "version" )
            {
                /* Special output formatting for 'version' column */
                $row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
            }
            else if ( $aColumns[$i] != ' ' )
            {
                /* General output */
                $row[] = $aRow[ $aColumns[$i] ];
            }
        }
        $output['aaData'][] = $row;
    }

    echo json_encode( $output );
?>

When running this I get this error:

Array ( [0] => Array ( [0] => IMSSP [SQLSTATE] => IMSSP [1] => -14
  [code] => -14 [2] => An invalid parameter was passed to sqlsrv_query.
  [message] => An invalid parameter was passed to sqlsrv_query. ) ) 1

This is how my connection is set up with SQL Server 2008:
$pdo = new PDO("sqlsrv:Server=$DB_HOST;Database=$DB_DBNAME", $DB_USER, $DB_PWD);

I'm not too sure what the actual problem is, and I can't see a line number to check.
Edit: the HTML I'm using:

            ID
            CardNumber

            ID
            CardNumber

A: In the end I fixed it with much help from Michael Berkowski
Here is my final code:
<?php

$serverName = ""; //serverName\instanceName
$connectionInfo = array( "Database"=>"", "UID"=>"", "PWD"=>"");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

    /*
     * Script:    DataTables server-side script for PHP and MySQL
     * Copyright: 2010 - Allan Jardine
     * License:   GPL v2 or BSD (3-point)
     */

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * Easy set variables
     */

    /* Array of database columns which should be read and sent back to DataTables. Use a space where
     * you want to insert a non-database field (for example a counter or static image)
     */
    $aColumns = array( 'ID', 'TerminalNumber');

    /* Indexed column (used for fast and accurate table cardinality) */
    $sIndexColumn = "ID";

    /* DB table to use */
    $sTable = "ActivityLog";

    /*
     * Paging
     */
    $sLimit = "";
    if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
    {
    $sLimit = "OFFSET  ".$_GET['iDisplayStart']." ROWS
                                FETCH NEXT ".$_GET['iDisplayLength']." ROWS ONLY ";
    }

    /*
     * Ordering
     */

    $sOrder = "";
    if ( isset( $_GET['iSortCol_0'] ) )
    {
        $sOrder = "ORDER BY  ";
        for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
        {
            if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
            {
                $sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
                    ".addslashes( $_GET['sSortDir_'.$i] ) .", ";
            }
        }

        $sOrder = substr_replace( $sOrder, "", -2 );
        if ( $sOrder == "ORDER BY" )
        {
            $sOrder = "";
        }
    }

    /*
     * Filtering
     * NOTE this does not match the built-in DataTables filtering which does it
     * word by word on any field. It's possible to do here, but concerned about efficiency
     * on very large tables, and MySQL's regex functionality is very limited
     */
    $sWhere = "";
    if ( $_GET['sSearch'] != "" )
    {
        $sWhere = "WHERE (";
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            $sWhere .= $aColumns[$i]." LIKE '%".addslashes( $_GET['sSearch'] )."%' OR ";
        }
        $sWhere = substr_replace( $sWhere, "", -3 );
        $sWhere .= ')';
    }

    /* Individual column filtering */
    for ( $i=0 ; $i<count($aColumns) ; $i++ )
    {
        if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
        {
            if ( $sWhere == "" )
            {
                $sWhere = "WHERE ";
            }
            else
            {
                $sWhere .= " AND ";
            }
            $sWhere .= $aColumns[$i]." LIKE '%".addslashes($_GET['sSearch_'.$i])."%' ";
        }
    }

    /*
     * SQL queries
     * Get data to display
     */
    $sQuery = "
        SELECT COUNT (*) OVER () AS ROW_COUNT, ".str_replace(" , ", " ", implode(", ", $aColumns))."
        FROM   $sTable
        $sWhere
        $sOrder
        $sLimit
    ";

    $rResult = sqlsrv_query($conn,  $sQuery ) or die(print_r(sqlsrv_errors()));

    /* Data set length after filtering */
    $sQueryRow = "
        SELECT ".str_replace(" , ", " ", implode(", ", $aColumns))."
        FROM   $sTable
        $sWhere
    ";
    $params = array();
    $options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
    $stmt = sqlsrv_query( $conn, $sQueryRow , $params, $options );

    $iFilteredTotal = sqlsrv_num_rows( $stmt );

    //echo "TOTAL " . $iFilteredTotal;
    /* Total data set length */
    $sQuery = "
        SELECT COUNT(".$sIndexColumn.")
        FROM   $sTable
    ";
    $rResultTotal = sqlsrv_query($conn,  $sQuery ) or die(print_r(sqlsrv_errors()));
    $aResultTotal = sqlsrv_fetch_array($rResultTotal);
    $iTotal = $aResultTotal[0];

    /*
     * Output
     */
    $output = array(
        "sEcho" => intval($_GET['sEcho']),
        "iTotalRecords" => $iTotal,
        "iTotalDisplayRecords" => $iFilteredTotal,
        "aaData" => array()
    );

    while ( $aRow = sqlsrv_fetch_array( $rResult ) )
    {
        $row = array();
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            if ( $aColumns[$i] == "version" )
            {
                /* Special output formatting for 'version' column */
                $row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
            }
            else if ( $aColumns[$i] != ' ' )
            {
                /* General output */
                $row[] = $aRow[ $aColumns[$i] ];
            }
        }
        $output['aaData'][] = $row;
    }

    echo json_encode( $output );
?>


text:
Q: Is $\Bbb Q$ homeomorphic to $\Bbb Q^2$? It's an easy excercise in set theory to exhibit a bijection $\Bbb Q \cong \Bbb Q\times \Bbb Q$. However, none of the bijections I'm aware of respect the topologies on $\Bbb Q$ and $\Bbb Q^2$, inherited from their respective embeddings into $\Bbb R$ and $\Bbb R^2$.
Therefore, I'm asking whether there exists a homeomorphism $\phi: \Bbb Q^2 \to \Bbb Q$.
I don't believe that there is any such map, but since the standard techniques of algebraic topology don't enable one to discern between $\Bbb Q$ and a discrete space, I wasn't able to prove it. Maybe Cech cohomology provides a means to attack this problem, but I haven't even got the slightest Iiea how to calculate $H^1(\Bbb Q,\Bbb Z)$.

A: The set of the rational numbers with its usual topology is the unique countable metrizable space without isolated points.
Can you use that property to conclude?


text:
Q: Spinning cricket balls and weight distribution An article on ESPN Cricinfo discusses the possibility of the internal weight distribution of cricket balls having an impact on the ability of a bowler to achieve 'spin'.
In cricket, a spin bowler imparts rotations on the ball at the point of release and thereby seeks to deceive their opponent (the batter) through either (i) the trajectory of the ball through the air; or (ii) the ball's behaviour once it comes into contact with the playing surface. [The ball will, as a general rule, be delivered at an initial velocity of 80-90kph and will travel c. 15 metres after it is delivered prior to bouncing, and a further 3 metres before reaching the position in which the batter is initially situated]
In the article, a cricket ball manufacturer states:

You can change the construction of the core so that it is more conducive to spin bowling, by weighting the core more heavily in the middle. It has an effect like an ice skater on the rink: when she spins with her arms wide, she spins slowly, and as she brings her arms in, she accelerates. All she has done is bring her weight in, which has enabled her to spin faster.

Is this claim accurate?

A: Yes, different weight distributions in cricket balls affect how conducive they are to being spun.
The quote seems self-explanatory. You must have encountered this phenomenon in school physics.  A solid cylinder rolls down an incline more quickly than a hollow cylinder of the same mass and radius. After rolling the same distance they lose the same PE and gain this same amount as KE. However, the solid cylinder has greater translational KE while the hollow cylinder has greater rotational KE.
How this distribution of mass is achieved can be seen in the following photo from your link. This core is made up of cork and rubber particles which have been heated and compressed. Surrounding it are alternate layers of cork bound by woollen yarn. The outer coating of the ball is made of smooth leather, but a heavy thread is used around the seam (just visible at the rim) to give the bowler enough grip to spin the ball.

How difficult a ball is to spin - its rotational inertia - is measured by its moment of inertia (MI). For a ball of mass $M$ and radius $R$ the MI about an axis through the centre can be written as $\frac25 kMR^2$ where $k$ is a fraction depending on the distribution of mass. If the mass of the ball is distributed uniformly then $k=1$ whereas if all the mass were concentrated in a shell at the rim then $k=\frac53$. If the mass were concentrated at the centre then $k=0$.
The Laws of Cricket require the mass of the ball to be within the range 156-163g and to have a circumference of 224-229mm, but there are no restrictions on internal construction or distribution of mass. National standards (eg British Standards Institute, BSI) cover seam height, hardness and wear.
Although all balls are traditionally made of cork and rubber inside a leather cover, there is considerable variety in construction even at international level. There is usually a core surrounded by 5-6 layers of cladding which alternate cork with wool or cotton yarn. Cores vary from solid cork to solid rubber, or a mixture of the two - or none at all - which may or may not be compressed. Cladding varies between winding the woollen yarn under tension when wet (which increases the tension when it has dried) or relatively loosely (as in the image above). With these options. the mass of the ball could be concentrated in the core (easy to spin) or in the cladding (more difficult to spin). Another variation is an irregularly-shaped core - which gives the ball a preferred axis of spin.
Assuming that core and cladding densities are in the ratio $d+1$, and the radii of the core and the ball are in the ratio of $r$, and ignoring any difference between cladding and leather cover, the MI of the ball is characterised by
$k=(dr^5+1)/(dr^3+1)$.
Cork and rubber have densities of about 14-16 and 69-74 lb/cu.ft respectively. Assuming these are the extreme densities possible for the core and cladding - giving $d \approx 4$ or $d \approx -\frac45$ - and assuming $r \approx \frac12$, then by switching cork and rubber between core and cladding we can achieve the extreme values $k \approx \frac34$ and $k \approx \frac{13}{12}$.
So the moment of inertia of a cricket ball could be varied in the ratio of about $13:9$ by shifting mass from the cladding to the core.


text:
Q: Parsing snake-case returning null I have this class below:
@JsonAutoDetect
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class AggregationModel {
   @JsonProperty(value = "doc_count_error_upper_bound")
   private Integer docCountErrorUpperBound;

   @JsonProperty(value = "sum_other_doc_count")
   private Integer sumOtherDocCount;

   @JsonProperty(value = "buckets")
   private List<Bucket> buckets;

   public Integer getDocCountErrorUpperBound() {
       return docCountErrorUpperBound;
   }

   public void setDocCountErrorUpperBound(Integer docCountErrorUpperBound) {
      this.docCountErrorUpperBound = docCountErrorUpperBound;
   }

   public Integer getSumOtherDocCount() {
      return sumOtherDocCount;
   }

   public void setSumOtherDocCount(Integer sumOtherDocCount) {
       this.sumOtherDocCount = sumOtherDocCount;
   }

   public List<Bucket> getBuckets() {
       return buckets;
   }

   public void setBuckets(List<Bucket> buckets) {
      this.buckets = buckets;
   }
}

Here's the json:
{
  "took": 15,
  "timed_out": false,
  "_shards": {
     "total": 5,
     "successful": 5,
     "failed": 0
  },
  "hits": {
     "total": 10,
     "max_score": 0,
     "hits": []
  },
  "aggregations": {
     "group_by": {
        "doc_count_error_upper_bound": 0,
        "sum_other_doc_count": 0,
        "buckets": [
           {
              "key": 439,
              "doc_count": 7,
              "average": {
                 "value": 5
              }
           }
       ]
     }
  }
}

Please consider the "aggregations" part only.
Only bucket is being returned fine, while the other two are returned as null. I am not sure why is that the case. I am using fasterxml.jackson.* (version 2.8.4).
Please help.
TIA.

A: The test case that I wrote used Gson in the background to parse JSON, once I converted it to Jackson, it started working.
Thanks a lot.


text:
Q: Unexpected error launching Internet Explorer. IELaunchURL() returned HRESULT 80070012 with Selenium 3.13.0: IEDriverServer_x64_3.13.0 My selenium test cases were executing just fine on internet explorer 11 browser but some thing got changed and now I'm getting the below error.
Started InternetExplorerDriver server (64-bit)
3.13.0.0
Listening on port 32274
Only local connections are allowed
[ERROR] [BaseTest] [startWebDriverClient] Could not start a new session.      org.openqa.selenium.SessionNotCreatedException: Unexpected error launching Internet Explorer. IELaunchURL() returned HRESULT 80070012 ('There are no more files.') for URL 'http://localhost:32274/'
Build info: version: '3.13.0', revision: '2f0d292', time: '2018-06-25T15:24:21.231Z'
System info: host: 'LUSMIN-F00Q46Y', ip: '***.**.**.**', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '9.0.1'
Driver info: driver.version: unknown
remote stacktrace:
    at com.tcs.saf.base.BaseTest.startWebDriverClient(BaseTest.java:496)
    at com.tcs.saf.base.BaseTest.beforeMethod(BaseTest.java:258)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.base/java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:59)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:451)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:222)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:516)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:707)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:979)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)

Below is my code for instantiating the IE browser;
if (browserType.equalsIgnoreCase("InternetExplorer")) {
            try {
                System.setProperty("webdriver.ie.driver", curProj+"\\drivers\\IEDriverServer.exe");
                InternetExplorerOptions options = new InternetExplorerOptions();
                options.introduceFlakinessByIgnoringSecurityDomains();
                options.requireWindowFocus();
                webdriver = new InternetExplorerDriver(options);
                logger.info("getWebDriver - Setting webdriver.ie.driver system property as: " + System.getProperty("webdriver.ie.driver"));
            } catch(IllegalStateException e) {
                logger.error("The path to the driver executable must be set by the webdriver.ie.driver system property. ",e.fillInStackTrace());
                throw new IllegalStateException("The path to the driver executable must be set by the webdriver.ie.driver system property.");
            }
        }

A: Please try the steps mentioned below and then try to run the automation script for IE Browser.

*

*For IE 11 only, you will need to set a registry entry on the target the computer so that the driver can maintain a connection to the instance of Internet Explorer it creates. For 32-bit Windows installations, the key you must examine in the registry editor is HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BFCACHE.

*For 64-bit Windows installations, the key is HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BFCACHE.
Please note that the FEATURE_BFCACHE subkey may or may not be present, and should be created if it is not present. Inside this key, create a DWORD value named iexplore.exe with the value of 0.
Protected mode settings are the same for all zones.
Enhanced Protected Mode is disabled.

A: As per the error log, you are using java 9. Selenium doesn't support Java 9 yet.
Please change the settings to use the java 8 and try again. It may resolve the issue.

A: This error message...
Could not start a new session. org.openqa.selenium.SessionNotCreatedException: Unexpected error launching Internet Explorer. IELaunchURL() returned HRESULT 80070012 ('There are no more files.') for URL 'http://localhost:32274/'

...implies that the IEDriverServer was unable to initiate/spawn a new WebBrowser i.e. IE Browser session.

As per Unexpected error launching Internet Explorer. IELaunchURL() returned HRESULT 80070012 ('There are no more files.') @JimEvans clearly mentions:

The IELaunchURL() function is a Windows API. The driver simply calls it. If it's returning an error, then that's where the issue is. There is no documentation provided by Microsoft about what would cause this error when using this API. If you attempt to run the test on a workstation-class OS like Windows 10, instead of on Windows Server, what happens? I realize that's not a "silver-bullet" solution, but there may be security settings at play in the server environment that are not in the workstation environment that would prevent additional file handles from being allocated in that context.

introduceFlakinessByIgnoringSecurityDomains();
As you have added the option introduceFlakinessByIgnoringSecurityDomains(); as per You're Doing It Wrong: IE Protected Mode and WebDriver @JimEvans again clearly mentions that adding options.introduceFlakinessByIgnoringSecurityDomains(); may get you past the initial exception and will allow the test to run in most cases without incident. However using this capability doesn't solve the underlying problem though. If a Protected Mode Boundary is crossed, very unexpected behavior including hangs, element location not working, and clicks not being propagated, could occur.

Solution
If you look into the Required Configuration of Internet Explorer Driver the folowing points are clearly mentioned :
Protected Mode
On Internet Explorer 7 or higher on Windows Vista or Windows 7, you must set the Protected Mode settings for each zone to be the same value. The value can be on or off, as long as it is the same for every zone. To set the Protected Mode settings you have to choose "Internet Options" from the "Tools" menu and then click on the Security tab. For each zone, there will be a check box at the bottom of the tab labeled Enable Protected Mode.

Browser Zoom Level
The browser zoom level must be set to 100% so that the native mouse events can be set to the correct coordinates.
References
You can find some detailed discussion in:

*

*Internet Explorer Protective mode setting and Zoom levels

*How to ignore zoom setting


text:
Q: PrintWindow() returns black image I have written a program in C# for automation. It runs on Windows Server 2008 R2 and captures screenshots of a flash app, that runs inside Firefox. These images are then analysed to read the status of the flash app.
When the connection to the server is establish through "Remote Desktop Connection" and I can see the desktop of the server, then PrintWindow() usually works (it returns black images randomly, but I can live with that). But when I disconnect the Remote Desktop, and stop seeing the desktop, PrintWindow() fails and returns only black images.
I can't keep open connection to the server forever, can this behaviour be fixed?


text:
Q: Creating a class which inherits from another class in Ruby I'm trying to create a class called Musician which inherits from my class Person and then adds an instrument attribute. I know my Musician class is wrong, but I just wanted to know what the correct format is in Ruby. Here is all of my code:
class Person
  attr_reader :first_name, :last_name, :age
  def initialize (first_name, last_name, age)
    @first_name = first_name
    @last_name = last_name
    @age = age
  end
end

p = Person.new("Earl", "Rubens-Watts", 2)
p.first_name
p.last_name
p.age

class Musician < Person
  attr_reader :instrument
  def initialize (instrument)
    @instrument = instrument
  end
end

m = Musician.new("George", "Harrison", 58, "guitar")
m.first_name + " " + m.last_name + ": " + m.age.to_s
m.instrument

Thanks for the help!

A: If you want first_name, last_name and age to be available in Musician then you must include them in the initializer and take advantage of super. Something like:
class Musician < Person
  attr_reader :instrument

  def initialize(first_name, last_name, age, instrument)
    super(first_name, last_name, age)
    @instrument = instrument
  end
end

super calls the method with the same name inside of the parent class.
UPDATE
I will drive the point home. You would also use super in this totally made up situation:
class GuitarPlayer < Person
  attr_reader :instrument

  def initialize(first_name, last_name, age)
    super(first_name, last_name, age)
    @instrument = 'guitar'
  end
end

We haven't changed the arguments to initialize but we have extended the behavior.

A: That is the format for extending a class.
The problem is that you're calling the Musician initializer with more attributes than it accepts.
The error message you get states this pretty explicitly. When reporting or asking for help regarding an error, the error message you get should be shared so we don't have to guess or run your program.
You have at least options:

*

*Give Musician an initialize that takes all the params, grabs instrument, and passes the rest.

*Use Rails' Hash-based initialize (or roll your own, but you tagged it with rails).


text:
Q: Oracle complex update statement I have a table where data is as given below

My requirement is to update this table in such a way that, within a group (grouping will be done based on column A), if there is value in column B, same value should be updated to other rows in column B having null values within that group. If column B have null value for all the records within that group, then new sequence should be generated.Also I can't use pl/SQL block for this. I need to write a SQL query to perform this
My expected output is given below

A: Something like this:
update table t1
set B = (select nvl(max(b),sequence_name.nextval) from table where a=t1.a)

Ps: I couldn't test this.
Indeed we can't use sequences in correlated subqueries... :(
One workaround is the use of merge :
merge into teste t1
using (select max(b) as m,a from teste group by a) t2
on (t1.a=t2.a)
when matched then update set b= nvl(t2.m,seq_teste.nextval);

One thing: that nextval will ALWAYS be consumed even when it won't be inserted. If you don't want that, you might need some pl/sql code.

A: You won't be able to use the sequence_name.nextval directly in your update statement, as the value will increase with every row, meaning that you would end up with different values in your b column for each a value.
The best way round that I can think of doing this is to first of all ensure every set of all-null b values has a single value in it, which you can do as follows:
merge into t1 tgt
  using (select a,
                b,
                rid,
                row_number() over (partition by a order by b) rn
         from   (select a,
                        b,
                        rowid rid,
                        max(b) over (partition by a) max_b
                 from   t1)
         where  max_b is null) src
    on (tgt.rowid = src.rid and src.rn = 1)
when matched then
update set tgt.b = t1_seq.nextval;

This finds the rows which have all the b values as null for a given a, and then updates one of them to have the next sequence value.
Once you've done that, you can then go ahead and populate the null values based on the max b value for that group, like so:
update t1
set    b = (select max(b) from t1 t2 where t1.a = t2.a)
where  b is null;

See this LiveSQL script for evidence that this works.


text:
Q: Init some variables when opening rails console Here's the thing. I use quite a lot the console to test my methods before plugging them in my app (nothing new here I guess).
What I'd find convenient, would be to have like a console_seed.rb file that I would load and then all my variables are ready for use.
Ex: console_seed.rb
me = User.find(77)
other_person = User.find(89)

So I can immediately test:
me.add_friend(other_person)

when opening the console, without having to write the .find() lines again and again.
I found this post : how can I run an initializer from the rails console?
load "#{Rails.root}/config/db/console_seed.rb"

which would do the trick but unfortunately, the variables created in the file don't share the same context as the console ...
Could rails magik happen again in this situation ? :)

A: Thanks to @dave-newton suggestions, I found a nice solution through .irbrc
Created a ~/.irbrc file:
// when rails constole is started, go find the console_seed.rb - project specific - file
require Dir.pwd + "/db/console_seed.rb"
puts 'Config init'

And App_Root_Path/db/console.seed.rb file:
Me = User.find(77)
Other_person = User.find(89)

The trick is that Me and Other_person have to be constants and not variables, otherwise they are not passed to the console scope. But in my case, it actually makes sense to have constants. Otherwise, method definition could be used, but I haven't explored this possibility yet.
My only frustration remains on the fact that my teamates need to create their own ~/.irbrc file to get the same behaviour, it is not automatically included into git scope ... Any suggestion for doing this? Ain't there any script that is loaded everytime the console is initialized?


text:
Q: Ideas for troubleshooting "audio not working" on dell vostro 1710 laptop Since the last days (I guess but not sure the problem started  on the same day Windows 7 SP1 was installed) on my Vostro 1710 laptop the audio doesn't work anymore.
If I try to do a Skype call it says "problems with the audio device".
I cannot play a song.
Of course the basic checklist is ok: audio is not disabled, volume is at 60%, on control panel/devices I see that latest driver is installed and works properly.
Do you have other ideas? Are you aware of Windows 7 SP1 problems with dell laptops?

A: Just some ideas:

*

*Boot from a live disc into some linux system to verify it is a windows problem.

*Reinstall drivers

*Try to roll back SP1 or did you mean you installed the whole windows 7 recently?

*Verify there are no hardware conflicts, like several devices on the same irq sometimes causes trouble. In that case try throwing a bunch out and letting windows reinstall them sometimes assigns different irqs.

*If all else fails, you will have to find users with the same problem and hope they have a solution or debug the system which I suppose you don't want to do. (Google is your friend...)

A: Skype helped me by telling "I cannot access your sound card".
So I went to Control Panel and this time I clicked on "Audio" (Instead than going to the list of devices).
I message told me "I cannot access your audio card. Probably the improved driver (and i think this is something Win 7 SP1 installed automatically) doesn't work with your card. Click Ok ti siable it".
After this all worked properly.


text:
Q: Let AutoMapper throw error for getter-only properties Is there a way I can make AutoMapper throw an error when calling AssertConfigurationIsValid when the target type contains a readonly (or getter only if you will) property that is settable in the source? It is silently ignored by default and AutoMapper does not seem to contain configuration to do it differently.
class Program
{
    public class Foo
    {
        public int Hello { get; set; }
        public string World { get; set; }
    }

    public class Bar
    {
        public int Hello { get; set; }
        public string World { get; } // Should throw error
    }

    static void Main(string[] args)
    {
        Mapper.Initialize(cfg => cfg.CreateMap<Foo, Bar>());
        Mapper.Configuration.AssertConfigurationIsValid();
    }
}


text:
Q: Geometry and Footskip: Footer wrong placed I am writing simple LaTeX documents with just sections and text in between (in general), but I have some problems placing the footer correctly. My header comes from a template I have downloaded ages ago, but it had this problem for years.
Sometimes the text directly writes itself over the line of the footer. The footer should always be just a line and the page number under that. I am using these packages because of the header function, separated in three parts.
Example:

Here is an example code:
\documentclass[12pt,a4paper]{scrartcl}
\usepackage[norsk]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[paper=a4paper,left=25mm,right=25mm,top=25mm,bottom=15mm]{geometry}
\usepackage{geometry}
\setlength{\footskip}{0.2cm}
\usepackage[headsepline,footsepline]{scrpage2}
\pagestyle{scrheadings}
\usepackage{blindtext}

\clearscrheadfoot
\ihead{Some Header Elements}
\chead{Middle}
\ohead{\today}
\cfoot{- \thepage \hspace{1pt} - }

\begin{document}

\section{Section 1}
\blindtext
\section{Section 2}
\blindtext[30]

\end{document}

How are geometry and footskip working with each other, so how can I solve this?

A: footskip is the distance between the textbody and the baseline of the footer. 2mm is not enough here, use at least 6mm. You can set footskip in geometry, no need to do a \setlength.
\documentclass[12pt,a4paper]{scrartcl}
\usepackage[norsk]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[paper=a4paper,left=25mm,right=25mm,top=25mm,bottom=15mm,
           footskip=6mm]{geometry}

\usepackage[headsepline,footsepline]{scrpage2}
\pagestyle{scrheadings}
\usepackage{blindtext}

\clearscrheadfoot
\ihead{Some Header Elements}
\chead{Middle}
\ohead{\today}
\cfoot{- \thepage \hspace{1pt} - }

\begin{document}

\section{Section 1}
\blindtext
\section{Section 2}
\blindtext[30]

\end{document}

A: it is easier to let geometry do all the setting, which can be done with includefoot:
\documentclass[12pt,a4paper,usegeometry]{scrartcl}
\usepackage[norsk]{babel}
\usepackage[T1]{fontenc}
\usepackage[paper=a4paper,left=25mm,right=25mm,
   top=25mm,bottom=10mm,includefoot]{geometry}
\usepackage[headsepline,footsepline]{scrlayer-scrpage}
\pagestyle{scrheadings}
\usepackage{blindtext}
\clearscrheadfoot
\ihead{Some Header Elements}
\chead{Middle}
\ohead{\today}
\cfoot{- \thepage \hspace{1pt} - }
\begin{document}
    \section{Section 1}
    \blindtext
    \section{Section 2}
    \blindtext[30]
\end{document}

If you want less space between text and footrule use ...,footskip=8mm]{geometry}

A: The absolute simplest solution is to let KOMA-script do the job. Since you are using 12pt font and A4 paper, scrartcl will automatically calculate a type area where the left, right and top margins are approximately 25mm, (exclusive header). The bottom margin will be ca. 31mm (to baseline of the page number).
Using KOMA-script internal functions gives you much better control, and the possibility to use all KOMA-script's flexible commands without running into compatibility issues.
All you have to do is load scrartcl with the option fontsize=12, and KOMA-script will do the rest. In addition, you should use the new scrlayer-scrpage instead of scrpage2.
If you insist using geometry you should only load it once.
The package widows-and-orphans is optional, but will help you to avoid widows and orphans ('enker og faderløse') in the document. And I changed the text to Norwegian to have correct hyphenation.
Here is the output and the code:

\documentclass[fontsize=12pt]{scrartcl}   % A4 is standard for KOMA-script
\usepackage[norsk]{babel}
\usepackage{lmodern}                  % Scalable fonts for microtype
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[babel=true]{microtype}    % For better linebreakes
\usepackage[headsepline=true, footsepline=true]{scrlayer-scrpage}
\pagestyle{scrheadings}
\usepackage{blindtext}
\usepackage{widows-and-orphans}

\clearscrheadfoot
\ihead{Some Header Elements}
\chead{Middle}
\ohead{\today}
\cfoot{-- \thepage \hspace{1pt} -- }  % Alway use enspace

\begin{document}

\section{Fra representanten Audun Lysbakken}

[Teksten er hentet fra regjeringen.no, ]

Spørsmål: Kan statsråden gjøre rede den konkrete begrunnelsen for avgjørelsen om å stanse eksport av forsvarsmateriell og flerbruksvarer til Saudi-Arabia, hvorvidt denne avgjørelsen vil få konsekvenser for annen eksport til andre land, og hvor stort omfanget er på eksporten til Saudi-Arabia over allerede inngåtte lisenser?

Begrunnelse: Utenriksdepartementet meldte fredag 9. november at det ikke lenger vil inngås lisenser til eksporten av forsvarsmateriell og flerbruksmateriell til Saudi-Arabia. I begrunnelsen vises det til at det er foretatt en helhetsvurdering, men det vises ikke til hvilke konkrete bestemmelser i regelverket som legges til grunn for avgjørelsen, eller om dette vil få konsekvenser for eksport til andre land. Spørsmålsstiller ønsker også at det redegjøres for i hvor stort omfang eksporten etter allerede inngåtte lisenser vil være.

\section{Utenriksministerens svar}
Norge har et meget strengt og omfattende eksportkontrollregelverk. Eksportkontrollforvaltningen følger Retningslinjer for Utenriksdepartementets behandling av søknader om eksport av forsvarsmateriell, samt teknologi og tjenester for militære formål av 28. februar 1992. Retningslinjene baserer seg blant annet på Stortingets vedtak av 11. mars 1959. Hovedprinsippet er at Norge ikke tillater eksport av forsvarsmateriell til områder hvor det er krig eller krig truer, eller til land der det er borgerkrig.

Ved en oppdatering 5. november 2014 ble kriteriene i EUs felles holdning om våpeneksport (2008/944/CSFP) artikkel 2 og de kriteriene som følger av ATTs artikler 6 og 7 innarbeidet i en konsolidert liste i retningslinjene. Retningslinjene gir også klare bestemmelser om krav til sluttbrukerdokumentasjon.

Når det gjelder Saudi-Arabia, står Norge i en annen situasjon enn mange andre land, fordi vi aldri har åpnet for eksport av våpen og ammunisjon (såkalt A-materiell) til landet. Utenriksdepartementet har besluttet at det i den nåværende situasjon heller ikke skal gis nye lisenser for eksport av annet forsvarsmateriell eller flerbruksvarer til militær bruk til Saudi-Arabia.

Beslutningen er fattet etter en helhetlig vurdering, og på grunnlag av et «føre-var» prinsipp. Den samme linjen ledet til at regjeringen i desember 2017 besluttet å suspendere eksport av A-materiell til De forente arabiske emirater (FAE), samt å ytterligere senke terskelen for å avslå eksport av annet militært materiell (B-materiell) til land som deltar i militære handlinger i Jemen.

At det må gjøres helhetlige og sammensatte vurderinger, følger av retningslinjene for eksport av forsvarsmateriell. Som nevnt ovenfor, reflekterer retningslinjene blant annet Stortingets 1959-vedtak, som forutsetter en grundig vurdering av de innen- og utenrikspolitiske forholdene i det aktuelle mottakerlandet.

Utenriksdepartementet gjør grundige, individuelle vurderinger av hver enkelt søknad om eksportlisens. Ved eksport av forsvarsmateriell kreves alltid dokumentasjon om sluttbruker før lisens kan innvilges. Dersom vi vurderer at det er en uakseptabel risiko for at det aktuelle utstyret kan bli brukt til intern undertrykking eller til å begå alvorlige brudd på humanitærretten eller menneskerettighetene, vil lisens ikke innvilges.

Omfanget av eksporten til Saudi-Arabia og andre land fremgår av de årlige meldingene til Stortinget. Gjennom disse meldingene ligger Norge i det internasjonale tetsjiktet når det gjelder åpenhet om eksporten av forsvarsmateriell. Samtidig må dette skje innenfor rammen av den lovpålagte taushetsplikten som følger av eksportkontrolloven.
\end{document}


text:
Q: Trying to find channel by name I'm trying to find a channel named "raidprotect-logs" on my server, by name, with my bot. But, it throws me the error ReferenceError: msg is not defined. I put this code in bot.on('ready', () => {.
This is my code:
const logChannel = msg.client.channels.find('raidprotect-logs', channelName)
logChannel.send(logEmbed)

So, my main question is : How can I define msg ?
(I declared logEmbed properly before those lines)
I tried to put it in bot.on('message', msg => { section but it throws me the error ReferenceError: channelName is not defined. I think when I'll pass the msg is not defined error i'll have this one. I don't know how to define channelName.

A: The message channel its a Discord collection, so you need use array map to find it.
You can get channel with 2 methods, second the better.
bot.on('message', msg => {
    logChannel = msg.guild.channels.find(channel => channel.name === 'raidprotect-logs') // Find method
    LogChannel = bot.channels.get('CHANNELID HERE') //Best way
}


text:
Q: Using python's urllib.quote_plus on utf-8 strings with 'safe' arguments I have a unicode string in python code:
name = u'Mayte_Martín'

I would like to use it with a SPARQL query, which meant that I should encode the string using 'utf-8' and use urllib.quote_plus or requests.quote on it. However, both these quote functions behave strangely as can be seen when used with and without the 'safe' arguments.
from urllib import quote_plus

Without 'safe' argument:
quote_plus(name.encode('utf-8'))
Output: 'Mayte_Mart%C3%ADn'

With 'safe' argument:
quote_plus(name.encode('utf-8'), safe=':/')
Output:
---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-164-556248391ee1> in <module>()
----> 1 quote_plus(v, safe=':/')

/usr/lib/python2.7/urllib.pyc in quote_plus(s, safe)
   1273         s = quote(s, safe + ' ')
   1274         return s.replace(' ', '+')
-> 1275     return quote(s, safe)
   1276
   1277 def urlencode(query, doseq=0):

/usr/lib/python2.7/urllib.pyc in quote(s, safe)
   1264         safe = always_safe + safe
   1265         _safe_quoters[cachekey] = (quoter, safe)
-> 1266     if not s.rstrip(safe):
   1267         return s
   1268     return ''.join(map(quoter, s))

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 10: ordinal not in range(128)

The problem seems to be with rstrip function. I tried to make some changes and call as...
quote_plus(name.encode('utf-8'), safe=u':/'.encode('utf-8'))

But that did not solve the issue. What could be the issue here?

A: According to this bug, here is the workaround:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from urllib import quote_plus
name = u'Mayte_Martín'
quote_plus(name.encode('utf-8'), safe=':/'.encode('utf-8'))

You must encode both argument in quote or quote_plus method to utf-8

A: I'm answering my own question, so that it may help others who face the same issue.
This particular issue arises when you make the following import in the current workspace before executing anything else.
from __future__ import unicode_literals

This has somehow turned out to be incompatible with the following sequence of code.
from urllib import quote_plus

name = u'Mayte_Martín'
quote_plus(name.encode('utf-8'), safe=':/')

The same code without importing unicode_literals works fine.

A: #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import urllib
name = u'Mayte_Martín'
print urllib.quote_plus(name.encode('utf-8'), safe=':/')

works without problem for me (Py 2.7.9, Debian)
(I don't know the answer, but I cannot make comments with regard to reputation)


text:
Q: Is there any way to dynamically add data into a gird? I have a carousel with n number of widgets and I want to load another n number of items to the carousel once the user focus the last item of the carousel. I have added afteralign event listener in the carousel to detect the navigation between carousel items and inside the listener I have created one widget and tried to append it to the current carousel using appendChildWidget() method
 _handleLazyLoading: function (evt) {
                var selectedItem = evt.target.getActiveChildWidget().getDataItem();
                if (selectedItem.page < selectedItem.totalPages) {
                    if (evt.target.getActiveChildIndex() === evt.target.getChildWidgetCount() - 3) {
                        var sampleData={"type":"VOD","id":1234,"accessLevel":"GRANTED","title":"sample","description":"A look back at all the Premier League action from the 31st of March 2018.","thumbnailUrl":"url of image","metaFields":{},"tags":
                        ["review","match-round-32"],"watchProgress":0,"favourite":true,"duration":3098,"watchedAt":1522675749000}
                        var videoCard=new CommonVideoCard(sampleData);
                        evt.target.appendChildWidget(sampleData)
                    }
                }
            }

This is what my event listener code. I have checked in the dom also, if i put a break point after the appending method then I can see the data in the dom after that it seems like the particualr carousel is stuck and I cannot navigate to other items in the carousel.
I just have a try with removeWidget method and it works.
Any help will be really appreciated.

A: set the setWidgetLengths(length); after appending a new child widget.
So the code will look like
 _handleLazyLoading: function (evt) {
                var selectedItem = evt.target.getActiveChildWidget().getDataItem();
                if (selectedItem.page < selectedItem.totalPages) {
                    if (evt.target.getActiveChildIndex() === evt.target.getChildWidgetCount() - 3) {
                        var sampleData={"type":"VOD","id":1234,"accessLevel":"GRANTED","title":"sample","description":"A look back at all the Premier League action from the 31st of March 2018.","thumbnailUrl":"url of image","metaFields":{},"tags":
                        ["review","match-round-32"],"watchProgress":0,"favourite":true,"duration":3098,"watchedAt":1522675749000}
                        var videoCard=new CommonVideoCard(sampleData);
                        evt.target.appendChildWidget(sampleData);
                        evt.target.setWidgetLengths(620);
                    }
                }
            }


text:
Q: The name of this type of matrix whats the name and the rules of a matrix thats like this.
    1   2   3   4   5   6
1   X   .   .   .   X   .
2   .   .   .   X   .   .
3   .   .   .   .   X   .
4   .   .   .   .   .   .
5   .   .   .   .   X   .
6   X   .   .   .   .   X

and it gets turned into this.
    1   2   3   4   5   6
1   1   1   1   1   2   2
2   1   1   1   2   3   3
3   1   1   1   2   4   4
4   1   1   1   2   4   4
5   1   1   1   2   5   5
6   2   2   2   3   6   7

A: Well, the rule seems to be that the value of each element corresponds to the number of 'X' that are both above and to the left.


text:
Q: Write MDX / DAX on azure analysis services and copy data to azure data warehous using ADF How can we create ADF pipeline to write MDX/DAX query from azure data factory to Azure Analysis Service Tabular Models and get the data stored into tables in Azure Data Warehous Tables?

A: Unfortunately there is no direct SSAS or AAS connector available in ADF .
So there is a workaround:

*

*Create a linked server on an IaaS/On prem/SQL MI server connecting to the tabular model

*via openrowset execute the query in SQL server to tabular model

*In ADF SQL would act as linked service

Reference:
https://datasharkx.wordpress.com/2021/03/16/copy-data-from-ssas-aas-through-azure-data-factory/


text:
Q: A finite-diameter Riemannian manifold with properly embedded infinite geodesics I'm working on the following problem:

Let $S$ be the unit $2$-sphere minus the north and south poles, and let $M = (0,\pi) \times \mathbb R$. Define $q : M \to S$ by $q(\phi,\theta) = (\sin\phi\cos\theta, \sin\phi\sin\theta, \cos\phi)$, and let $g$ be the metric on $M$ given by pulling back the round metric $g = q^*\mathring{g}$. Prove the Riemannian manifold $(M,g)$ has diameter $\pi$, but contains infinitely long properly embedded geodesics.

Constructing the geodesics in question is simple: they are the preimages of great circles that do not pass through the north and south poles. The equator, for example, is one: $\gamma(t) = (\frac\pi 2, t)$ is a properly embedded geodesic in $M$ with infinite length. But this specific example seems to disprove the assertion that the diameter of $M$ is finite. What am I overlooking to show the diameter is finite?

A: That this problem illustrates that for some Riemannian manifolds $(M, g)$ the length-minimizing paths are not geodesics.

Example (Up to reparameterization) the only geodesic that passes through $(\frac{\pi}{2}, 0)$ and $(\frac{\pi}{2}, \frac{5\pi}{4})$ is the preimage of the the equator, that is, $t \mapsto (\frac{\pi}{2}, t)$, but the length of this geodesic between those two points is $\frac{5 \pi}{4}$, which (as the problem shows) is larger than the diameter $\pi$ of $M$, hence it is not length-minimizing.

(In fact, for this particular example there are pairs of points that are not connected by any geodesic, despite that the space is connected.) Indeed, this reinforces the point that geodesics are locally length-minimizing, but globally they need not be. (There are simpler examples of this fact, too: For any nonantipodal points $x, y \in S^n$, the minor and major arcs of the great circle passing through them are both geodesics, but the major arc is longer than the minor arc and hence not minimizing.)
Hint The key observation is that the metric in the preimage of the polar regions is small, so a strategy for building a short path between two points is to travel from your starting point to that region, do your lateral movement there, and then drop down to the point of interest.

 Additional hint Suppose we want to travel from $(a, b)$ to $(a', b')$. Then we have at least one of $a + a' \leq \pi$ or $(\pi - a) + (\pi - a') \leq \pi$, and by symmetry (reflection $M$ across the preimage of the equator) we may as well assume the former. Consider the path $\gamma_\epsilon$ defined to be the concatenation of the paths $\gamma_\epsilon^1$ connecting $(a, b)$ vertically (along a "meridian") from to $(\epsilon, b)$ where $0 < \epsilon \leq \min\{a, a'\}$, $\gamma_\epsilon^2$ connecting $(\epsilon, b)$ horizontally (along a "parallel") to $(\epsilon, b')$, and $\gamma_\epsilon^3$ connecting $(\epsilon, b')$ to $(a', b')$ vertically. Then, length of $\gamma$ satisfies \begin{align}L(\gamma_\epsilon) &= L(\gamma_1) + L(\gamma_2) + L(\gamma_3)\\ &= (a - \epsilon) + |b' - b| \sin \epsilon + (a' - \epsilon)\\ &\leq (a + a') + (|b' - b| - 2) \epsilon \leq \pi + (|b' - b| - 2) .\epsilon\end{align} So, the distance from $(a, b)$ to $(a', b')$ satsfies$$d((a, b), (a', b')) = \inf_\gamma L(\gamma) \leq \inf_{\epsilon > 0} L(\gamma_\epsilon) \leq \pi ,$$ where in the second expression $\gamma$ varies over all curves from $(a, b)$ to $(a', b')$. But those points were arbitrary, so $$\operatorname{diam}(M, d) = \sup d((a, b), (a', b')) \leq \pi ,$$ where the supremum is taken over $M \times M$. To show equality, by definition we need to produce sequences $(a_i, b_i)$ and $(a_i', b_i')$ such that $$\sup_i d((a_i, b_i), (a_i', b_i')) = \pi .$$ Of course, it would suffice to find points $(a, b), (a', b')$ such that $d((a, b), (a', b')) = \pi$. One such pair is $(\frac{\pi}{2}, 0)$ and $(\frac{\pi}{2}, \pi)$.


text:
Q: Snowflake SQL - How to get count of records grouped by week for the last n weeks I'm trying to records in a table on a per week basis and using this link as a reference on how to group by time in Snowflake SQL:
select COUNT(table_id), DATE_TRUNC('WEEK', DATEADD(Day, -49, CURRENT_DATE))
FROM data_warehouse_source
GROUP BY 2

I basically want to get the count of records for each of last say 7 weeks(hence 49 days above and using the DATEADD function to help me get the data from the last 7 weeks onwards up to the current date).
I'm not sure what I'm missing in the above query. Any suggestions please?

A: If you have a date column you can get the count for last 7 weeks / 49 days like below.
select
    COUNT(1),
    DATE_TRUNC('WEEK', "Date_Column") // Week("Date_Column") can also be used to get week of the year
from
    Table
where
    "Date_Column" > DATEADD(day,-49,date_trunc('day', current_date))
group by 2;


text: Q: webgl : Quad wireframe remove the diagonal line Using the braycentric method I am able get the wireframe drawn (ref: http://codeflow.org/entries/2012/aug/02/easy-wireframe-display-with-barycentric-coordinates/). What is the best way to discard the diagonal line using the shaders.