text:
Q: display data from database, edit it, but when click on previous page, the data gone. i got 4 pages which are company details, job requirements, job responsibilities and design. so im gonna update the data from these pages. so i retrieve the data from database to be display into form for these 4 pages. after i edit the values on first page, then i go to next page for next update. but when i go back to previous page, the data wont keep the edited value but display the old data that i retrieved from database. so how to prevent this to happen ? same goes if i refresh the pages. i know i can use the session to store edited value but still i think that form will display the old data. help me give the idea how to do this pls ! thanks

A: You need to follow below steps

*

*Go to next page by submit & action attribute

*In next page hold all the post value into hidden fields

*Use a back button to go back.

*when go button will be pressed submit the form which is holding the hidden fields

*Now you are in first page and simply use $_REQUEST or $_POST to get the previous value.

Hope you under stand.
N.B: If you use browser back button browser will ask you to confirm to resubmit the form. If you confirm then no problem but if you didn't confirm then you lost your values.


text:
Q: Scaling view leads to wrong (unscaled) touch positions I have a RelativeLayout that contains a lot of sub views, e.g. a RecyclerView with clickable items. I add this view to the WindowManager.
If I scale this view, I see the side effect, that touches are handled as if the view is not scaled. It looks like this effect only happens if a view is attached to the WindowManager.
Can I somehow solve this?
If I scale all sub views inside my RelativeLayout, everything works fine as those views are not attached to the WindowManager directly... But this means, I must scale + translate them which is a little more work as scaling the parent view only...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Running Karma from TeamCity Does anyone know how you would run the following command within TeamCity? (the command is normally ran in a Node.js command window)..."Karma start karma.conf.js". I have successfully installed Nodejs on the TeamCity server. I have then successfully installed Karma on  the same server (using npm install -g karma).
In TeamCity, my build step has "Runner type = Command Line", and the Custom Script is set to "FULLPATHOFKARMAEXE\karma.cmd start FULLPATHOFKARMACONFIGFILE/kara.conf.js"
When i run TeamCity, it comes back with the error "node is not recognized as an internal or external command"
Anyone know the step-by step process of running Karma within TeamCity?

A: In your case, the Karma installation seems to be OK, but your TeamCity agent process is unable to resolve the path to Node.exe (it's installation folder is missing from the %PATH% variable).
First verify the NodeJS installation by opening a Commandline window on the agent machine, type node and press enter:
c:> node
>

If the result in your Command window is a >-prompt, you might solve your problems by restarting the build agent.
If the result in your Command window is some error message saying "node is not recognized as an internal or external command", you need to add the NodeJS installation folder to the %PATH% variable, and restart the build agent.
You can, of course, just change the %PATH% for your build agent service by running a initialization script included in the NodeJS installtion folder in your build step. Depending on where your NodeJS installastion is, your custom script might look like this:
"C:\Program Files (x86)\nodejs\nodevars.bat"
"FULLPATHOFKARMAEXE\karma.cmd start FULLPATHOFKARMACONFIGFILE/kara.conf.js"


text:
Q: Set height of list items to fill fluid parent height I have a fluid width div (width: 100%) that contains a fluid width unordered list (width: 30%) and a fluid width block of content (width: 70%) positioned to the right of it. As the block of content exceeds the height of the unordered list I would like each list item's height to increase to fill the containers height. Obviously an li height of 25% isn't going to work but that is what I'm looking for. I'm stuck. Any suggestions?

Item 1

Item 2

Item 3

Item 4

Lorem ipsum dolor sit amet...

A: You may try this by adding a static background to your unordered list (width: 30%) like this:
#your_tab_id_here:before {
  content: "";
  display: block;
  width:30%;
  position: fixed;
  bottom: 0;
  top: 0;
  z-index: -9999;
  background-color: #cccccc; // same with the background of your tabs

}
Also, for the footer, with this kind of approach, just try to make it sticky at the bottom :)
Hope, this gives you the idea..
See my JSFiddle Here

A: With jQuery:
var adjustHeight;

$(document).ready(function() {
    var $tabs = $('#tabs');
    var $content = $('#content');

    adjustHeight = function() {
        var tabsH = $tabs.height();
        var contentH = $content.height();
        if(contentH > tabsH) {
            $tabs.height(contentH); //set height if greater than tabs
        } else {
            $content.attr('height', ''); //remove height if one has been set
        }
    }

    adjustHeight();

    // If the #content height changes, you need to rerun adjustHeight()
});

This code will run when the page first loads. If the #content height changes after the page load (if content is getting changed via ajax, for instance), then you'll need to set up a callback to run adjustHeight().

A: If you are willing to add an extra container to your html:

Item 1

Item 2

Item 3

Item 4

Lorem ipsum dolor sit amet...

Then you can use the magic of display: table; and display: table-row; to size your li elements to fit with pure css.
I used position: absolute; around the tabs-wrapper element and the 'stretch' method of declaring the extents of each side to be where I want them, to get it to fill the height of the main container.
#container {
    position: relative;
}
#tabs-wrapper, #content {
    display: inline-block;
}
#tabs-wrapper {
    position: absolute;
    top: 0;
    left: 0;
    right: 70%;
    bottom: 0;
}
#tabs {
    display: table;
    height: 100%;
    width: 100%;
}
#tabs li {
    display: table-row;
}
#content {
    width: 70%;
    margin-left: 30%;
}

I did this pretty quick so I'm sure it could be done a bit more efficiently. Heck, you might even be able to get rid of that extra container element if you play around with it enough, who knows.
Here's the fiddle:
http://jsfiddle.net/Dx4L8/


text:
Q: leaflet map changes with respect to selections in dc.js charts I want to implement map overlay using leaflet. In the following code mainmap is the baselayer; heat and markLayer are two heat maps. I want to link only the 'heat' layer to my dc.js charts. The two overlays are successfully working but the 'heat' layer is not changing according to selections in the chart.
I am unable to figure out where I am wrong. My problem is that I am unable to link the dcCharts (array of dc charts) with leaflet map heatlayer. The visualization on the map remains the same even after selections.
`var mainmap;
  var heat;
  mapLink = 'OpenStreetMap';
  mainmap = L.tileLayer(
      'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© ' + mapLink + ' Contributors',
        maxZoom: 15,
      });

    //1st HeatMap
  var geoData = [];
  _.each(allDim.top(Infinity), function(d) {
      geoData.push([d["lat"], d["long"], 1]);
        });
   heat = L.heatLayer(geoData,{
      radius: 10,
      blur: 20,
      maxZoom: 1,
    });

   //2nd HeatMap
    var geoDataa =[];
    _.each(allDimm.top(Infinity), function(d){

      geoDataa.push([d["lat"], d["long"], 1]);
    });

  var markerLayer = L.heatLayer(geoDataa, {
    radius: 10,
      blur: 20,
      maxZoom: 1,
});

  map = L.map('map',{
  layers: [mainmap, heat, markerLayer]
});
  map.setView([22.97, 100.65], 4);

  var baseMaps = {
    "BaseMap": mainmap
    };

var overlayMaps = {
    "heat": heat,
    "markerLayer": markerLayer
};

 mainmap.addTo(map);

 function drawMap()
  {
    heat.addTo(map);
    mainmap.addTo(map);
  }
  L.control.layers(baseMaps, overlayMaps).addTo(map);
  drawMap();

  //Update the heatmap if any dc chart get filtered

  _.each(dcCharts, function (dcChart) {
    dcChart.on("filtered", function (chart, filter) {
        map.eachLayer(function (layer) {
          map.removeLayer(layer)
        });
        console.log("Yes, I am called");
    drawMap();
    });
  dc.renderAll();

}); `


text:
Q: JQuery remove last number of list items I have a var containing a number and need to subtract this number from the total number of list items. Then I need to remove the end items in the list eg. Total = 20; Number of list items = 18; Final number = 2; Then remove the last 2 list items.
Thanks for any help.

A: $.slice(start, [end])
jQuery Documentation
UPDATE:
Example:
$('li').slice( -numToRemove ).remove();

A: I'd use the :gt() selector.
$( 'li:gt(' + ( maxAllowed-1 ) + ')' ).remove();

Demo: http://jsfiddle.net/JAAulde/5GdQx/


text:
Q: Returning a new object or initializing member in constructor? We have a data provider class that returns repositories for each aggregate in our database.
Let's consider following scenario:
public class DataProvider {
    public IBookRepository Books { get { retun new BookRepository(); } }
    public IAuthorRepository Authors { get { retun new AuthorRepository(); } }
}

As you can see, we return a new Instance of the given object every time we call the Member: DataProvider.Books.DoBANANAS();
vs.
public class DataProvider {
    public IBookRepository Books { get; }
    public IAuthorRepository Authors { get; }

    public DataProvider()
    {
        Books = new BookRepository();
        Authors = new AuthorRepository();
    }
}

Will the call to `DataProvider.Books.BANANAS(); be less CPU / Memory heavy now?
As I just got around implementhing both version and they suprisingly worked!
But my experience tells me that Version 1 Sucks. Yet I've got more than enough time to fully optimize and implement the final product. (That's one of the benefits of working in a research group)

A: The implementations shown are different in how they construct and manage objects. In the first example, a new repository is created every time the property is called on the DataProvider. If the repository holds any state (eg. a cache of fetched objects), you will get very different behaviour than with the second example, because this state will be reset to its default each time.
From the fact that you said both version work, I would hazard a guess that the repository objects do not hold state and are just proxies to the database calls. In this case, it probably will not have much difference.
However, the performance and the memory profile of the two approaches are very different. Whilst premature optimisation is a bad thing and often a waste of time, I would not class this as such because making a new repository on each property call could clearly be a performance problem later, or worse still introduce hard to track down bugs if you introduce state into the repositories. Creating less objects will ultimately put less of a strain on the garbage collector, but unless you are creating millions of objects, it will be a negligible difference.
In summary, the second example is the better one going forward, and I see no real problem considering that now.

A: Your first example creates a new instance of the XXXRepository object each time, where the second is returning a handle to an already existing one, so the second should perform better and use less CPU as new memory does not need to be allocated.
The bigger problem is that unless the repository classes are entirely static or something, the 2 scenarios produce completely different results.  If the repository classes are some sort of interface to a database, then option 1 does not need to be thread-safe where option 2 does.


text:
Q: Java: SOAP Message fails to Send but Works in SOAPUI I am creating a SOAP message and then trying to send it using the following code.
try {
  System.setProperty("http.proxyHost", "proxy.myproxy.com");
  System.setProperty("http.proxyPort", "80");
  connection = SOAPConnectionFactory.newInstance().createConnection();
  response = connection.call(message, "https://www.service.com/call");
  connection.close();
} catch (SOAPException e) {
  e.printStackTrace();
} catch (UnsupportedOperationException e) {
  e.printStackTrace();
}
finally{
  System.setProperty("http.proxyHost", "");
  System.setProperty("http.proxyPort", "");
}

The finally is because I need to bypass the proxy when I access urls on the local domain. I know this is kind of a hack and would be interested in other solutions. However, the real issue deals with a Timeout. This times out every time, however, if I take the SOAP message and send it using SOAPUI (same proxy settings) I get a successful response.
Response from Java Code...
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"><soapenv:Body><soapenv:Fault><faultcode>soapenv:Server</faultcode><faultstring>java.net.ConnectException: Connection timed out: no further information</faultstring></soapenv:Fault></soapenv:Body></soapenv:Envelope>

A: I ended up using this...
public static String soapHttpRequest(RequestInfo re) {
    HttpURLConnection connection = null;
    OutputStreamWriter wr = null;
    BufferedReader rd = null;
    StringBuilder sb = null;
    String line = null;

    URL serverAddress = null;

    System.setProperty("http.proxyHost", "proxy.my.com");
    System.setProperty("http.proxyPort", "80");
    System.setProperty("https.proxyHost", "proxy.my.com");
    System.setProperty("https.proxyPort", "80");

    try {
                    serverAddress = new URL("https://site.com/service/default.asp");
        // set up out communications stuff
        connection = null;

        // Set up the initial connection
        connection = (HttpURLConnection) serverAddress.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-type", "text/xml; charset=utf-8");
        connection.setRequestProperty("SOAPAction",
              "https://site.com/service/default.asp#Method");
        OutputStream reqStream = connection.getOutputStream();
        reqStream.write(getSoapMessageString(re).getBytes());
        connection.connect();

        // read the result from the server
        rd = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        sb = new StringBuilder();

        while ((line = rd.readLine()) != null) {
            sb.append(line + '\n');
        }
        String val = sb.toString();
        System.out.println(val);
        return val;

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // close the connection, set all objects to null
        connection.disconnect();
        rd = null;
        sb = null;
        wr = null;
        connection = null;
              // Closing to prevent issues with local calls
        System.setProperty("http.proxyHost", "");
        System.setProperty("http.proxyPort", "");
        System.setProperty("https.proxyHost", "");
        System.setProperty("https.proxyPort", "");
    }
    return null;
}


text:
Q: Rendering Grid Layout From JToken in Umbraco 8 I have created a DocType MyDocType.
DocTypeGridEditor requires it to be of type ElementType, therefore, I checked it to be of that type in the Umbraco Backoffice.
It contains one property: GridLayout, i.e:
public Newtonsoft.Json.Linq.JToken MyGrid => this.Value<Newtonsoft.Json.Linq.JToken>("myGrid");

And in my cshtml I would like to render it but
@Html.GetGridHtml()

requires first parameter to be of type IPublishedContent.
I am using UmbracoViewPage for the template.
Is there a way to render its content?
Is it even possible to render Grid from ElementModel?

A: I have managed to resolve this issue by creating my own extension to the HtmlHelper.
Here is a snippet:
public static class GridLayoutExtensions
{
    public static MvcHtmlString GetGridHtml(this HtmlHelper html, IPublishedElement publishedElement, string propertyAlias)
    {
        if (propertyAlias == null)
        {
            return new MvcHtmlString("");
        }

        var model = publishedElement
            .GetProperty(propertyAlias)
            .GetValue();

        return html.Partial("Grid/bootstrap3", model);
    }
}

And now all I need to do is to use it by passing an element which contains GridLayout property.
@Html.GetGridHtml2(Model.MyDocType, "gridLayout")

And it works flawlessly.


text:
Q: Exponential r.v.s. problem Here is the question.
A total of n people has been invited to a party for honouring a scholar.  The party begins at time 0.  The arrival times of n guests are independent exponential r.v.s. with mean 1, and the arrival time of scholar is uniform distributed between 0 and 1.
Find the probability that exactly k of the guests arrive before the scholar.
For my understanding,
Let X be people arrive party, $0 \le x \le n$
and Y be the arrival times of x guest
$pY \mid X=n\{Y=t\mid X=n\} = λe^{−λx}$ for $x\gt 0$,
then given mean, $E[Y] = \frac{1}{\lambda} = 1$
i.e. $\lambda=1$.
So $pY \mid X=n\{Y=t\mid X=n\}$ becomes $e^{−x}$
as we have to consider the time before scholar, so $0 \lt t \lt 1$.
and $X=k$.
I know that I have to find $pX(X=k)$, which can be used the equation of $\frac{pYX}{pY}\mid X$.
but how can I find $pYX$?
or my concept is something wrong here?
Please help!!

A: A possible approach:

*

*Suppose the scholar arrives at time $t$:

*

*What is the probability a particular guest arrives before time $t$?

*What is the probability a particular guest arrives after time $t$?

*What is the probability exactly $k$ out of $n$ guests arrive before time $t$?

*What happens when you combine this with the scholar's arrival time being uniformly distributed?

*

*Hint: $\displaystyle P(K=k) = E_T[P(K=k\mid T=t)]=\int_t P(K=k \mid T=t)\, p(t)\, dt$


text:
Q: Multiple ggtext Markdown Annotations in ggplot2 Take Long Time to Render/Don't Render I have been using Claus Wilke's great ggtext package for markdown annotations for a while now, and until now it's worked perfectly. In the course of using ggtext to make multiple text annotations (mix of bold face and regular text on multiple lines), either with the ggtext::geom_richtext() or ggtext::geom_textbox(), I found the more geom_richtext()s I added increased the rendering time to the point where it would just churn on end (I gave up after 45 minutes the last time).
Of course, creating and saving the ggplot object with all of the geom_richtext() and element_markdown()s took little time. But when I tried to view the plot or use ggsave to save as a png/jpeg it again churned forever (again, I gave up after 30 minutes).
I've included a sample reprex below.
My questions for ggtext and ggplot2 power users:

*

*Is there an upper limit to the number of ggtext objects you can use in a ggplot2 plot? I'm not well-versed in grid and the underlying mechanics of ggplot.

*Are there alternatives to ggtext to mix font weights in annotations in ggplot2? I already tried the plotmath route after seeing this from @aosmith on SO: html - Embolden substring of object passed through geom_text() - Stack Overflow. The problem? atop() only works on one line, not multiple lines of text.

FWIW, the full non-reprex version of my code (and the viz I'm trying to recreate in ggplot2) are at https://github.com/kpivert/wsj/tree/main/01_R/06_cpi_again.
Any recommendations you may have would be greatly appreciated.
Please let me know if you need further clarification or if the reprex doesn't work.
Thanks for your time and consideration.
Kurtis
require(ggthemes)
#> Loading required package: ggthemes
require(ggtext)
#> Loading required package: ggtext
require(tictoc)
#> Loading required package: tictoc
require(tidyverse)
#> Loading required package: tidyverse

df <- data.frame(
  DATE = seq(as.Date("1913-01-01"), as.Date("2020-12-01"), "month")
  ) %>%
  mutate(
    var = rnorm(n = nrow(.), mean = 0, sd = 0.5)
  )

# Years for X Axis Labels

yr_labs <- seq(as.Date("1915-01-01"), as.Date("2020-01-01"), by = "5 years") %>%
  str_sub(start = 1, end = 4)

yr_labs <- case_when(
  yr_labs == "1915" ~ "1915",
  yr_labs == "2020" ~ "2020",
  TRUE ~ str_c("'", str_sub(yr_labs, 3, 4))
)

tic()
ggplot(
  df,
  aes(
    x = DATE,
    y = var
    )
  ) +
  geom_line(
    lwd = 0.2,
    color = "blue"
  ) +
  scale_x_continuous(
    breaks = seq(as.Date("1915-01-01"), as.Date("2020-01-01"), by = "5 years"),
    labels = yr_labs
  ) +
  theme_tufte() +
  theme(
    panel.grid.major.y = element_line(size = .1),
    axis.ticks.y = element_blank(),
    axis.text.y = element_text(
      vjust = - 0.8,
      margin = margin(l = 20, r = -20)
    ),
    plot.title = element_text(size = 16),
    plot.subtitle = element_text(size = 10),
    plot.caption = element_text(hjust = 0)
  ) +
  labs(
    x = "",
    y = "",
    caption = "Source: Randomness",
    title = "Reprex Title",
    subtitle = "Reprex Subtitle"
  ) +
  # Annotations ----
# 1. WW I ----
geom_segment(
  aes(
    x = as.Date("1914-09-01"),
    y = 1.25,
    xend = as.Date("1918-11-01"),
    yend = 1.25
  ),
  lwd = 1
) +
  geom_segment(
    aes(
      x = as.Date("1916-08-01"),
      y = 1.25,
      xend = as.Date("1916-08-01"),
      yend = 1.28
    ),
    linetype = "dotted"
  ) +
geom_richtext(
  x = as.Date("1916-01-01"),
  y = 1.28,
  label = "1914-18
World
War I",
  fill = NA,
  label.color = NA
)

toc()
#> 20.668 sec elapsed

Created on 2021-12-07 by the reprex package (v2.0.1)

Session info

sessioninfo::session_info()
#> ─ Session info ───────────────────────────────────────────────────────────────
#>  setting  value
#>  version  R version 4.1.0 (2021-05-18)
#>  os       macOS Big Sur 10.16
#>  system   x86_64, darwin17.0
#>  ui       X11
#>  language (EN)
#>  collate  en_US.UTF-8
#>  ctype    en_US.UTF-8
#>  tz       America/New_York
#>  date     2021-12-07
#>
#> ─ Packages ───────────────────────────────────────────────────────────────────
#>  package     * version date       lib source
#>  assertthat    0.2.1   2019-03-21 [1] CRAN (R 4.1.0)
#>  backports     1.2.1   2020-12-09 [1] CRAN (R 4.1.0)
#>  broom         0.7.9   2021-07-27 [1] CRAN (R 4.1.0)
#>  cellranger    1.1.0   2016-07-27 [1] CRAN (R 4.1.0)
#>  cli           3.0.1   2021-07-17 [1] CRAN (R 4.1.0)
#>  colorspace    2.0-2   2021-06-24 [1] CRAN (R 4.1.0)
#>  crayon        1.4.1   2021-02-08 [1] CRAN (R 4.1.0)
#>  curl          4.3.2   2021-06-23 [1] CRAN (R 4.1.0)
#>  DBI           1.1.1   2021-01-15 [1] CRAN (R 4.1.0)
#>  dbplyr        2.1.1   2021-04-06 [1] CRAN (R 4.1.0)
#>  digest        0.6.28  2021-09-23 [1] CRAN (R 4.1.0)
#>  dplyr       * 1.0.7   2021-06-18 [1] CRAN (R 4.1.0)
#>  ellipsis      0.3.2   2021-04-29 [1] CRAN (R 4.1.0)
#>  evaluate      0.14    2019-05-28 [1] CRAN (R 4.1.0)
#>  fansi         0.5.0   2021-05-25 [1] CRAN (R 4.1.0)
#>  farver        2.1.0   2021-02-28 [1] CRAN (R 4.1.0)
#>  fastmap       1.1.0   2021-01-25 [1] CRAN (R 4.1.0)
#>  forcats     * 0.5.1   2021-01-27 [1] CRAN (R 4.1.0)
#>  fs            1.5.0   2020-07-31 [1] CRAN (R 4.1.0)
#>  generics      0.1.0   2020-10-31 [1] CRAN (R 4.1.0)
#>  ggplot2     * 3.3.5   2021-06-25 [1] CRAN (R 4.1.0)
#>  ggtext      * 0.1.1   2020-12-17 [1] CRAN (R 4.1.0)
#>  ggthemes    * 4.2.4   2021-01-20 [1] CRAN (R 4.1.0)
#>  glue          1.4.2   2020-08-27 [1] CRAN (R 4.1.0)
#>  gridtext      0.1.4   2020-12-10 [1] CRAN (R 4.1.0)
#>  gtable        0.3.0   2019-03-25 [1] CRAN (R 4.1.0)
#>  haven         2.4.3   2021-08-04 [1] CRAN (R 4.1.0)
#>  highr         0.9     2021-04-16 [1] CRAN (R 4.1.0)
#>  hms           1.1.0   2021-05-17 [1] CRAN (R 4.1.0)
#>  htmltools     0.5.2   2021-08-25 [1] CRAN (R 4.1.0)
#>  httr          1.4.2   2020-07-20 [1] CRAN (R 4.1.0)
#>  jsonlite      1.7.2   2020-12-09 [1] CRAN (R 4.1.0)
#>  knitr         1.36    2021-09-29 [1] CRAN (R 4.1.0)
#>  labeling      0.4.2   2020-10-20 [1] CRAN (R 4.1.0)
#>  lifecycle     1.0.1   2021-09-24 [1] CRAN (R 4.1.0)
#>  lubridate     1.7.10  2021-02-26 [1] CRAN (R 4.1.0)
#>  magrittr      2.0.1   2020-11-17 [1] CRAN (R 4.1.0)
#>  markdown      1.1     2019-08-07 [1] CRAN (R 4.1.0)
#>  mime          0.12    2021-09-28 [1] CRAN (R 4.1.0)
#>  modelr        0.1.8   2020-05-19 [1] CRAN (R 4.1.0)
#>  munsell       0.5.0   2018-06-12 [1] CRAN (R 4.1.0)
#>  pillar        1.6.3   2021-09-26 [1] CRAN (R 4.1.0)
#>  pkgconfig     2.0.3   2019-09-22 [1] CRAN (R 4.1.0)
#>  purrr       * 0.3.4   2020-04-17 [1] CRAN (R 4.1.0)
#>  R6            2.5.1   2021-08-19 [1] CRAN (R 4.1.0)
#>  Rcpp          1.0.7   2021-07-07 [1] CRAN (R 4.1.0)
#>  readr       * 2.0.1   2021-08-10 [1] CRAN (R 4.1.0)
#>  readxl        1.3.1   2019-03-13 [1] CRAN (R 4.1.0)
#>  reprex        2.0.1   2021-08-05 [1] CRAN (R 4.1.0)
#>  rlang         0.4.11  2021-04-30 [1] CRAN (R 4.1.0)
#>  rmarkdown     2.11    2021-09-14 [1] CRAN (R 4.1.0)
#>  rstudioapi    0.13    2020-11-12 [1] CRAN (R 4.1.0)
#>  rvest         1.0.1   2021-07-26 [1] CRAN (R 4.1.0)
#>  scales        1.1.1   2020-05-11 [1] CRAN (R 4.1.0)
#>  sessioninfo   1.1.1   2018-11-05 [1] CRAN (R 4.1.0)
#>  stringi       1.7.5   2021-10-04 [1] CRAN (R 4.1.0)
#>  stringr     * 1.4.0   2019-02-10 [1] CRAN (R 4.1.0)
#>  styler        1.5.1   2021-07-13 [1] CRAN (R 4.1.0)
#>  tibble      * 3.1.5   2021-09-30 [1] CRAN (R 4.1.0)
#>  tictoc      * 1.0.1   2021-04-19 [1] CRAN (R 4.1.0)
#>  tidyr       * 1.1.3   2021-03-03 [1] CRAN (R 4.1.0)
#>  tidyselect    1.1.1   2021-04-30 [1] CRAN (R 4.1.0)
#>  tidyverse   * 1.3.1   2021-04-15 [1] CRAN (R 4.1.0)
#>  tzdb          0.1.2   2021-07-20 [1] CRAN (R 4.1.0)
#>  utf8          1.2.2   2021-07-24 [1] CRAN (R 4.1.0)
#>  vctrs         0.3.8   2021-04-29 [1] CRAN (R 4.1.0)
#>  withr         2.4.2   2021-04-18 [1] CRAN (R 4.1.0)
#>  xfun          0.26    2021-09-14 [1] CRAN (R 4.1.0)
#>  xml2          1.3.2   2020-04-23 [1] CRAN (R 4.1.0)
#>  yaml          2.2.1   2020-02-01 [1] CRAN (R 4.1.0)
#>
#> [1] /Library/Frameworks/R.framework/Versions/4.1/Resources/library

A: For the record, Jon Spring correctly noted the issue, which was the aesthetic mapping problem in the geom_segment() and geom_richtext() calls.  In addition to his solution using annotate(), you can also pass a dataframe and use inherit.aes = FALSE so the text or segment isn't overplotted the same number of times as there are rows in the dataset. For example:
 geom_richtext(
    inherit.aes = FALSE,
    data = tibble(
    x = as.Date("1916-01-01"),
    y = 1.28,
    label = "1914-18
World
War I"),
    aes(
      x = x,
      y = y,
      label = label),
    fill = NA,
    label.color = NA
  )

Kara Woo's great presentation at the 2021 rstudio::global conference addressed this very issue: https://www.rstudio.com/resources/rstudioglobal-2021/always-look-on-the-bright-side-of-plots/.


text:
Q: How can i prevent this negative white space in my website from appearing? I have been working on fixing this problem for a while, my website at some pages that has less or few content, or if it's shown in a big screen, it shows white space right under the footer.
"as shown here (https://imgur.com/ATR59Ts)"
i tried using height:100% but it doesn't work if the screen is small, because if i put the height:100% in body{} it will cause elements inside the body to overlap over the body and cause white space.
"as shown here (https://imgur.com/3fWTNZE)"
i have no idea what else to tinker with to prevent this white space.

*

*i tried to add height:100% in body,html (doesn't work on small screens when i add more element in my divs.

body, html{
    margin: 0;
    padding: 0;
    width: 100%;
    /* height: 100%; */
    /* overflow: scroll; */
}

i expected the result to make the body always at 100% on all possible screens, but the element would overflow over the body and cause white spaces.

A: Looks like content in the container is smaller than screen size? Then you may use min-height:100vh in main container style. This will make its minimum size equals to windows size. Example at Codepen

A: Can you link us to your site so we can see the issue?


text:
Q: Create a C++ table that accepts strings with spaces I'd like to create a console table out of this as a matter of exercise and to enhance my understanding of tables in C++.

I have found what seemed like a good working table but I think fails because my strings contain spaces.
This one tested okay with the values that were provided in the example:
https://github.com/haarcuba/cpp-text-table
However, when I added a string such as "public members are public in derived class and can be accessed directly by member functions and nonmember functions" into a t.add();, it failed to print any of the table whatsoever.
I look forward to learning.

A: If you are asking how to accept a string with spaces from user input, then you need to user the getline() function.
getline(cin,variableToStoreIn);

If your question is about inheritance, please reword your question for clarity.


text:
Q: set cornerRadius of class using UIButton appearanceWhenContainedIn So far I have changed image of all the buttons which are in my class by using the following code
   [[UIButton appearanceWhenContainedIn:[FirstPadViewController class], nil] setBackgroundImage:img forState:UIControlStateNormal];

As I dont want to create an outlet that is why I used this way. So how can I set cornerRadius using UIButton appearanceWhenContainedIn
I tried this but it does not work
 [[[UIButton appearanceWhenContainedIn:[FirstPadViewController class], nil] layer ] setCornerRadius:20];
 [[[UIButton appearanceWhenContainedIn:[FirstPadViewController class], nil] layer ] setMasksToBounds:YES];

A: Basically, you can't do that. And, even if it works, it can break at any moment with any update, or have undefined behavior.
UIAppearance proxy is reserved to method / properties that declares UI_APPEARANCE_SELECTOR.
Have a look at this list to see what you can customize with UIAppearance. According to it you can change only the tintColor. The list is not complete but layer (and by extension, cornerRadius) is not in the appearance selectors.

A: write this code in your class,it'l work but i don't know is it ok for you
for(UIView *view in self.view.subviews)
        if([view isKindOfClass:[UIButton class]]){
            UIButton *btn= (UIButton *)view;
            btn.layer.cornerRadius = 5;
            btn.layer.borderColor = [UIColor redColor].CGColor;
            btn.layer.borderWidth =5;

        }


text:
Q: Update Statement with Inline SQL This syntax keeps giving me an invalid column.  All I want to do is insert the value into the table.  How should I change my syntax to make it possible? This is the error presented.

Msg 207, Level 16, State 1, Line 1
  Invalid column name 'Alpha12'.

Code:
Declare @vector varchar(25), @sql varchar(max)
Set @vector = 'Alpha12'

Create Table #Test (vector varchar(50))

Set @sql = 'Update  #Test '
       + 'set vector = coalesce(''' + @vector + ''', '''')'

Print @sql
Exec (@sql)

Select * from #Test

Drop Table #Test

A: You should escape your interpolated varchar variable @vector with single quotes and use insert instead of update statement:
set @sql = 'insert into  #Test '
         + 'values (coalesce(''' + @vector + ''', ''''))'

SQLFiddle

A: Is it necessary to use Exec Dynamic SQL?  It's risky because it enables sql injection.
Why not do the Insert statement normally:
Insert into  #Test
Values (Coalesce(@vector,''))


text:
Q: difference between checkbox and checkedtextview in Android? Which to use for RecyclerView? I am a beginner in Android Development. When I learned about CheckBox, it's a widget extending compoundbutton and CheckedTextView, widget extending TextView and implements Checkable Interface. When I searched on google, I found no results. Actually, what is the difference between them, If I am using ListView or RecyclerView with CheckBox ability. Which is the better option CheckBox or CheckedTextView?

A: To supplement the other answers, here is a visual comparison between CheckBox and CheckedTextView. This is running in an emulated Pixel 3 under Android R. Each of these screenshots shows three views inside a vertical LinearLayout.
If you don't specify the checkMark attribute, you get no checkbox on the CheckedTextView:

with android:checkMark="?android:attr/listChoiceIndicatorSingle":

with android:checkMark="?android:attr/listChoiceIndicatorMultiple":

There are other differences, but they're covered by other answers.

A: As recommended from @LarsH I've turned my comment into an answer instead.
The differences is CheckedTextView doesn't have a checked/click event, see here why
Therefore if you want to have checked/click event for free (you can customize the checked/click listener by yourself) choose CheckBox and its alignment by default is (left aligned TextView & right aligned CheckBox)
You might want to align the TextView's text position (optional: if you want to align into different position, e.g: right aligned TextView & left aligned CheckBox)
Then use it on your RecyclerView holder

A: CheckBox: Is a specific type of 2 states button that can be either checked or unchecked.
CheckedTextView: Is a TextView with 2 states check and unchecked.
The text is the different between both views, so depend in what you want to do.
About the second question, RecyclerView was created as a ListView improvement.

A: so to set item in recyclerview first define the itemLayout as below
<CheckBox
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/dialog_checklist_checkbox"
  android:layout_width="match_parent"
   android:layout_height="wrap_content"
  android:text="text"
  android:padding="5dp"
  android:gravity="center"
 />

now in recyclerview you can use the checbox properties such as
holder.checkBox.setText("position"+position);

to set the text of respective checkbox.
you can also use other properties of checkbox such as
 holder.checkBox.setOnCheckedChangeListener();

and recyclerview is improved version of listview so try to use recyclerview.


text:
Q: Showing that if E is uncountable, and F is countable then E\F is uncountable? I'm actually trying to construct a proof to show that there exists an uncountable number of irrationals between $x<y$ for $x,y \in \mathbb{R}$. I'd like to do it by using the statement if E is uncountable and F is countable, then E\F is uncountable.
I started by showing that the interval (x,y) is uncountable, and I'd like to use the fact that I've proved that there are a countably infinite number of rationals between x and y.
Can I express the irrationals $ \mathbb{I}$ as $ \mathbb {I} \in (x,y) \backslash \mathbb{Q}$? And then say since $\mathbb{I} \in (x,y)$ and $\mathbb{I} \notin \mathbb{Q}$ it is uncountable since (x,y) is uncountable and $\mathbb{Q}$ is countable?

A: I think the easiest way is to suppose that $E \setminus F$ is countable. Then $E = F \cup (E \setminus F)$ is the union of two countable sets and thus must be countable, which is a contradiction to our definition of $E$. Therefore $E\setminus F$ is uncountable.

A: You can just use the definitions of countable and uncountable.  Biject $F$ with $\Bbb N$, then use the diagonal proof to show that taking $\Bbb N$ elements out of $E$ leaves it uncountable, else $E$ would have cardinality $2|\Bbb N|=\Bbb N$


text:
Q: Two ways of (kind of) instantiating a trait in Scala I know of two ways of making an anonymous class to instantiate a trait in Scala:
scala> trait SomeTrait {
     |   def aUsefulMethod = ()
     | }
defined trait SomeTrait

scala> val instance1 = new SomeTrait{} // Method 1
instance1: SomeTrait = $anon$1@7307556f

scala> instance1.aUsefulMethod // Returns a Unit.

scala> object instance2 extends SomeTrait // Method 2
defined module instance2

scala> instance2.aUsefulMethod // Returns a Unit.

I can't think of a reason why they are not equivalent. Am I wrong?
I'm asking in part because I used to only know method 2 but now I see that method 1 is more common. So I'm wondering if I've been doing something wrong this whole time.

A: The first approach new Trait {} creates a new class-instance.
The second approach creates an object which is a Singleton.
One can see this in the REPL:
Define Trait
scala> trait Example {}
defined trait Example

New anonymous class
Each call to new will return a new Instance. One can see this that each object gets a new address.
scala> new Example{}
res0: Example = $anon$1@768debd

scala> new Example{}
res1: Example = $anon$1@546a03af

Object extending Trait
Here a singleton object is created once.
scala> object X extends Example
defined object X

scala> X
res2: X.type = X$@1810399e

scala> X
res3: X.type = X$@1810399e

Impact and comparison
Even if both approaches on the surface may seem similar they lead to different results.
scala> new Example{} == new Example{}
<console>:12: warning: comparing values of types Example and Example using `==' will always yield false
   new Example{} == new Example{}
                 ^
 res4: Boolean = false

 scala> X == X
 res5: Boolean = true

Going even deeper
On the underlying structure both aproaches will lead to different *class files being generated when run on the JVM
Anonymous class
    $ cat example.scala
    object Example1 {
      trait A
      new A {}
    }

    $ scalac example.scala

    $ ls *class

      Example1$$anon$1.class Example1$A.class
      Example1$.class        Example1.class

    $ cat example2.scala
    object Example2 {
      trait A

      object X extends A
    }

    $ scalac example2.scala

    $ ls *class
    Example2$.class   Example2$X$.class
    Example2$A.class  Example2.class

A: val instance1 = new SomeTrait{} is the same as
class X extends SomeTrait
val instance1: SomeTrait = new X

except the compiler creates the class X and gives it a name like $anon$1. If you then do val instance2 = new SomeTrait{} the compiler will notice it can reuse the same anonymous class. And object instance2 is also basically
class instance2$ extends SomeTrait {
  override def toString = "instance2"
}
lazy val instance2 = new instance2$

except you can't create new instances of instance2$. So one difference is lazy instantiation: instance2 is only actually created when it's accessed (e.g. when you call instance2.aUsefulMethod), which makes a difference if the SomeTrait constructor throws an exception or has other side effects. Another is that you can use object at the top level (outside class, trait or object).


text:
Q: How to make Smart Icon Animations (when Launch and Exit Apps) in Android? Smart Animated Icons is one of the Highlighted Features of MIUI 9.You can see the New Animation when you Launch and Exit Apps. Open/Launch the App and You can notice the Animation on its Icon when you exit the App. Animation seems to be cool and it gives you a live Experience as if Icons are Live. Take a look at the below GIFs to see the Animation on Icons.
Facebook Smart Icon animation exmaple.

Settings app Smart Icon animation

For more smart App icon Animation understanding and information please check this link Smart Icon Animation
1) how to achieve this same features ? How can I do it in my app?
2) Android SDK that supports dynamic app icons ? is it possible to achieve this using <activity-alias> ?

A: Yes, these are Smart Icon animations introduced in MIUI 9. MIUI does the icon animation by itself upon enabling it from system settings as mentioned here on Xiomi MIUI Offical forum.
It happens only for some system apps and some famous social media platforms as of now, may happen for other famous app icons in the future too. But as they mentioned in the link, it is a part of the MIUI 9.0, and is not part of Android SDK.
I too wish they include this feature as part of Android SDK to be shipped with the application. It would be intriguing.


text:
Q: Best way to join this into a temp table and inner join Just wondering the best way to put this into a temp table and then join it.
 IF EXISTS(SELECT LocId
FROM dbo.Locations WITH (NOLOCK)
WHERE SourceSystem = @SourceSystem
AND LocId IN (SELECT ListVal
FROM etopsuser.fnParseListToTable(@LocIdList, ';')) AND IsHot = 1)
BEGIN

Specifically trying to do it on this line of code
    (SELECT ListVal
FROM etopsuser.fnParseListToTable(@LocIdList, ';')) AND IsHot = 1)

The NOLOCK is unrelated

A: You would create a temporary table just like any other table from a select:
SELECT ListVal
INTO #templist
FROM etopsuser.fnParseListToTable(@LocIdList, ';');

Then you would use it as:
SELECT l.LocId
FROM dbo.Locations l JOIN
     #templist tl
     ON l.LocId = tl.Listval
WHERE l.SourceSystem = @SourceSystem AND l.IsHot = 1

A: The best way to pass a list into a procedure is to use a Table Valued Parameter
CREATE TYPE dbo.List AS TABLE (ListVal varchar(255));

IF EXISTS(SELECT 1
    FROM dbo.Locations l
    WHERE l.SourceSystem = @SourceSystem
    AND l.LocId IN (
        SELECT ll.ListVal
        FROM @LocIdList ll
    ) AND IsHot = 1)

Notes: Always use table references on every column, especially if subqueries are involved. Never use NOLOCK unless you are prepared for incorrect results. EXISTS ignores its SELECT, so SELECT 1 or SELECT NULL is standard.

Then you can pass in the table variable either from client code depending on language, or in T-SQL like this
DECLARE @list dbo.List;
INSERT @list (ListVal)
VALUES ('SomeValue');

EXEC YourProc @LocIdList = @list;


text:
Q: The average of 11 results in 50 The average of 11 results in 50.If the average of first six results is 48 and that of last six 51,the sixth result is?

A: We have the following system of equations:
$$x_1+\cdots+x_{11}=50\cdot11 \tag{1}$$
$$x_1+\cdots+x_{6}=48\cdot6 \tag{2}$$
$$x_6+\cdots+x_{11}=51\cdot6 \tag{3}$$
Adding (2) and (3), we obtain: $$x_1+\cdots+2x_6+\cdots +x_{11}=6\cdot(48+51)=6\cdot99.$$
Substituting in (1), $$x_6+50\cdot11=6\cdot99 \implies x_6=44.$$


text:
Q: AWK - 3 for loops in END statement not desired result New to AWK. I have a file with the following content:
FirstName,LastName,Email,ID,Number,IDToBeMatched
John,Smith,js@.com,js30,4,kt78
George,Haynes,gh@.com,gh67,3,re201
Mary,Dewar,md@.com,md009,4,js30
Kevin,Pan,kp@.com,kp41,2,md009
,,,,,ti10
,,,,,qwe909
,,,,,md009
,,,,,kor28
,,,,,gh67

The idea is to check whether any of the fields below the header ID matches any of the fields below IDToBeMatched and if there is a match to print the whole record but for the last field (i.e. IDToBeMatched). So my final output should look like:
FirstName,LastName,Email,ID,Number
John,Smith,js@.com,js30,4
George,Haynes,gh@.com,gh67,3
Mary,Dewar,md@.com,md009,4

My code so far
    awk 'BEGIN{
        FS=OFS=",";SUBSEP=",";
}

{
      # all[$1,$2,$3,$4,$5]
        a[$4]++;
        b[$6]++;
}

END{ #for(k in all){
    for(i in a){
       for(j in b){
           if(i==j){
              print i #k
                    }
                   }
                }
    #}
}' inputfile

This prints the match only. If however I try to introduce another loop by uncommenting the lines in the above script in order to have the whole line for the matching field, things get messy. I understand why but I cannot find the solution. I thought to introduce a next statement but it's not allowed in the END. My AWK defaults to GAWK and I would prefer an (G)AWK solution only.
Thank you in advance.
The last field has more records because it was copied/pasted from an ID "pool" which does not necessarily has the same number of records as the files it was pasted in.

A: $ awk -F, 'NR==FNR{a[$6];next} (FNR==1)||($4 in a){sub(/,[^,]+$/,"");print}' file file
FirstName,LastName,Email,ID,Number
John,Smith,js@.com,js30,4
George,Haynes,gh@.com,gh67,3
Mary,Dewar,md@.com,md009,4


text:
Q: javascript click event queue I made a simple gallery where when you click on a image thumb nail, it will show the larger image with fade in fade out effect with jquery.
$('#thumnail').click(function(){
  $('#piccontainer').fadeOut(function(){
      $('#piccontainer').html('<div> <img src="' + imgsource + '"  /> </div>');
  });

  $('#piccontainer').fadeIn();
});

but if i click on a 5 different thumbnails quickly, the large image will fade in fade out for all 5 images.  How can I disable so that lets say i clicked on 5 thumbnails very quickly, it should only fadein the last 5th one.  basicaly how can i stop the queue of the click events?
thanks for the help.

A: Take a look at - http://api.jquery.com/queue/

A: You could use timeout like this to avoid multiple clicks. Again this is possible to avoid clicks for a small amount of time and not longer.
http://jsfiddle.net/dhavaln/Z7w84/

A: Add this condition at the top of the function:
if ($('#piccontainer').is(":animated")) {
  return false;
}

See Demo


text:
Q: How to Speed UP Mongodb Query? I am using Sails Js and MongoDB database. I want to optimize below Query.
Users.findOne({id:user_id})
    .populate('educations')
    .populate('educations.educationlinks')
    .populate('educations.educationlinks.verify_request_id')
    .populate('educations.educationlinks.verify_request_id.user_id')
.populate('educations.educationlinks.verify_request_id.user_id.company_id')
    .exec(function(err, user){
        return res.json(user);
});

Please Help Me.....

A: By default, SailsJS doesn't use case sensitivity for MongoDB queries.
To optimize MongoDB query performance, try forcing case sensitivity in your Mongo query code (MongoDB code in the connections .js file) with:
  wlNext: {
      caseSensitive: true
   }

//For Example:
    someMongodbServer: {
      adapter: 'sails-mongo',
      host: 'localhost',
      port: 27017,
      database: 'sails_demo' //optional
      wlNext: {
          caseSensitive: true
       }
    },

Hope this helps!
Additional resources:
https://docs.mongodb.com/manual/tutorial/optimize-query-performance-with-indexes-and-projections/


text:
Q: Speed up mongodump+mongorestore I have created a script to copy a MongoDB database to my machine. I am creating an SSH tunnel (ssh -L ...) then I connect to the tunnelled port with mongodump then I pipe its output to mongorestore:
mongodump --host=127.0.0.1:##### --db=***** --archive | mongorestore --host={mongo_dest} --drop --archive

I would like to speed up the copying. --gzip doesn't make sense to be used in this case -- because the same machine and memory are used by mongodump and mongorestore. The data comes uncompressed via the SSH socket.
Is there a way to run mongodump on the SSHed machine and pipe its output to a process on my machine?
Of course I could dump the database, archive, copy over SSH and restore it. But I don't want taking temporary space.

A: Don't know why I didn't think of it:
ssh *** ". /etc/profile; mongodump --host=127.0.0.1:27017 --db=**** --archive --gzip" | mongorestore --host=127.0.0.1:27017 --drop --archive --gzip

Was 1603.96 real        45.24 user        43.57 sys.
Now 209.52 real         7.25 user         6.03 sys.


text:
Q: How do I make a dropdown multi select? I'm trying to make a dropdown to be multi-select.
For example, I should be able to select Option 1, Option 2, Option 3, and Option 4 at the same time.
Just to make things more understandable. I'm attaching the desired result below:

<select>
  <option>All</option>
  <option>Option 1</option>
  <option>Option 2</option>
  <option>Option 3</option>
  <option>Option 4</option>
</select>

A: You can use multiple as a property of select tag. It is a basic feature of HTML.
Here is an example :

<select multiple>
  <option value="val1">Val1</option>
  <option value="val2">Val2</option>
  <option value="val3">Val3</option>
  <option value="val4">Val4</option>
</select>

Or you can use any jQuery plugins for the same.

A: HTML has no such control.
A <select> element will render a dropdown menu that lets you pick one option.
A <select multiple> element will render a list box that lets you pick multiple options.
To get the UI you desire you will need to involve JavaScript. A good starting point would be a list of <input type="checkbox"> elements.


text:
Q: SearchView stops filtering after LongClick action In my app, I have a SearchView in the Toolbar.
When the user clicks the search icon, the SearchView expands and the user starts typing. The search query filters a RecyclerView list by title. This all works fine.
However, the filter function stops working when I perform an OnLongClick action on one of the RecyclerView items.
I have both an OnClickListener and OnLongClickListener attached to each RecyclerView holder, but it's only the OnLongClick action that stops the SearchView from filtering. I don't understand why. I've tried reinstantiating the SearchView and resetting the RecyclerView to no avail.
Here's my code:
Functions that don't affect the SearchView have been removed for the sake of space.
MainActivity.java
public class MainActivity extends AppCompatActivity {

    //LONG CLICK ACTION MODE VARIABLES
    boolean isInActionMode = false;
    TextView selectedCounterText;

    //SEARCH BAR
    SearchView searchView;

    //INSERT DIALOG TEXTVIEWS
    EditText editTitle, editCategory, editSignifier, editDate, editRecurs, editDetails;
    Button btnCreate, btnCancel;

    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;
    CardAdapter adapter;
    Toolbar toolbar;

    ArrayList<Bullet> bullets = new ArrayList<>();
    ArrayList<Bullet> selectedBullets = new ArrayList<>();
    int counter = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        //SET DEFAULT VIEW STATES
        selectedCounterText = (TextView) findViewById(R.id.selected_counter);
        appName = (TextView) findViewById(R.id.app_name);
        selectedCounterText.setVisibility(View.GONE);
        appName.setVisibility(View.VISIBLE);
        noBulletsMessage = (TextView) findViewById(R.id.noBullets_message);
        noBulletsMessage.setVisibility(View.GONE);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //RECYCLERVIEW PROPERTIES
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setHasFixedSize(true);

        //ACTION MODE ON LONG CLICK VIEW STATES
        selectedCounterText = (TextView) findViewById(R.id.selected_counter);
        selectedCounterText.setVisibility(View.GONE);

        //ADAPTER
        adapter = new CardAdapter(this, bullets);

        //RETRIEVE DATA
        retrieveData();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_activity_main, menu);

        //SEARCH
        final MenuItem searchItem = menu.findItem(R.id.item_search);
        searchView = (SearchView) searchItem.getActionView();
        searchView.setIconifiedByDefault(true);
        searchView.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                return false;
            }
        });
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String query) {
                //FILTER AS YOU TYPE
                adapter.getFilter().filter(query);
                return false;
            }
        });

        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        retrieveData();
    }

    /**
     * @param item
     * @return This method includes behavior for all action toolbar menu items: Add, search, edit,
     * and delete.
     * <p>
     * It detects which button is pressed and performs the appropriate action.
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

            //IF HOME (BACK ARROW) IS PRESSED
        } else if (item.getItemId() == android.R.id.home) {
            clearActionMode();
            adapter.notifyDataSetChanged();
        }

        return true;
    }

    public void clearActionMode() {
        isInActionMode = false;
        toolbar.getMenu().clear();
        toolbar.inflateMenu(R.menu.menu_activity_main);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        selectedCounterText.setVisibility(View.GONE);
        appName.setVisibility(View.VISIBLE);
        selectedCounterText.setText("0 Item(s) Selected");
        counter = 0;
        selectedBullets.clear();
    }

    @Override
    public void onBackPressed() {
        if (isInActionMode) {
            clearActionMode();
            adapter.notifyDataSetChanged();
        } else {
            super.onBackPressed();
        }
    }
}

CardHolder.java
public CardHolder(final View itemView, final MainActivity mainActivity) {
        super(itemView);
        signifier_img = (ImageView) itemView.findViewById(R.id.img_id);
        titleText = (TextView) itemView.findViewById(R.id.title);
        categoryText = (TextView) itemView.findViewById(R.id.category);
        cardView = (CardView) itemView.findViewById(R.id.bulletCardView);
        checkBox = (CheckBox) itemView.findViewById(R.id.check_list_item);
        this.mainActivity = mainActivity;

        //CLICK LISTENERS
        cardView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                mainActivity.toolbar.getMenu().clear();
                mainActivity.toolbar.inflateMenu(R.menu.menu_action_mode);
                mainActivity.selectedCounterText.setVisibility(View.VISIBLE);
                mainActivity.appName.setVisibility(View.GONE);
                mainActivity.isInActionMode = true;
                mainActivity.adapter.notifyDataSetChanged();
                mainActivity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);

                return true;
            }
        });
        cardView.setOnClickListener(this);
        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mainActivity.prepareSelection(view, getAdapterPosition());
            }
        });

    }

    @Override
    public void onClick(View view) {
        this.itemClickListener.onItemClick(view, getLayoutPosition());
    }

    public void setItemClickListener(ItemClickListener itemClick) {
        this.itemClickListener = itemClick;
    }
}

CardAdapter.java
public class CardAdapter extends RecyclerView.Adapter<CardHolder> implements Filterable {

    Context context;
    ArrayList<Bullet> bullets, filterList;
    SearchFilter filter;
    MainActivity mainActivity;

    public CardAdapter(Context context, ArrayList<Bullet> bullets) {
        this.context = context;
        this.bullets = bullets;
        this.filterList = bullets;
        mainActivity = (MainActivity) context;
    }

    //INITIALIZE VIEWHOLDER
    @Override
    public CardHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //VIEW OBJ FROM XML
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_card_view, parent, false);

        //HOLDER
        CardHolder holder = new CardHolder(view, mainActivity);

        return holder;
    }

    //BIND DATA TO VIEWS
    @Override
    public void onBindViewHolder(final CardHolder holder, int position) {
        holder.signifier_img.setImageResource(R.drawable.asterisk_48px);
        holder.titleText.setText(bullets.get(position).getTitle());

        if (!mainActivity.isInActionMode) {
            holder.checkBox.setVisibility(View.GONE);
        } else {
            holder.checkBox.setVisibility(View.VISIBLE);
            holder.checkBox.setChecked(false);
        }

        //CARD CLICKED
        holder.setItemClickListener(new ItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                //DISPLAY POPUP OF FULL INFO OF BULLET
                //OPEN DETAIL VIEW
                //PASS DATA TO VIEW

                if (!mainActivity.isInActionMode) {
                    //CREATE INTENT
                    Intent intent = new Intent(context, DetailView.class);

                    //LOAD DATA TO INTENT
                    intent.putExtra("ID", bullets.get(position).getId());
                    intent.putExtra("TITLE", bullets.get(position).getTitle());
                    intent.putExtra("CATEGORY", bullets.get(position).getCategory());
                    intent.putExtra("SIGNIFIER", bullets.get(position).getSignifier());
                    intent.putExtra("DATE", bullets.get(position).getDate());
                    intent.putExtra("RECURS", bullets.get(position).getRecurs());
                    intent.putExtra("DETAILS", bullets.get(position).getDetails());

                    //START ACTIVITY
                    context.startActivity(intent);
                } else {
                    //DO NOTHING
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return bullets.size();
    }

    //RETURN FILTER OBJ
    @Override
    public Filter getFilter() {
        if (filter == null) {
            filter = new SearchFilter(filterList, this);
        }

        return filter;
    }
}

SearchFilter.java
public class SearchFilter extends Filter {

    CardAdapter adapter;
    ArrayList<Bullet> filterList;

    public SearchFilter(ArrayList<Bullet> filterList, CardAdapter adapter) {
        this.adapter = adapter;
        this.filterList = filterList;
    }

    //FILTER OCCURS HERE
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();

        //CHECK CONSTRAINT VALIDITY
        if (constraint != null && constraint.length() > 0) {

            //CHANGE TO UPPER
            constraint = constraint.toString().toUpperCase();

            //STORE FILTERED BULLETS
            ArrayList<Bullet> filteredBullets = new ArrayList<>();

            for (int i = 0; i < filterList.size(); i++) {
                //CHECK
                if (filterList.get(i).getTitle().toUpperCase().contains(constraint)) {
                    //ADD BULLET TO FILTERED BULLETS
                    filteredBullets.add(filterList.get(i));
                }
            }

            results.count = filteredBullets.size();
            results.values = filteredBullets;

        } else {
            results.count = filterList.size();
            results.values = filterList;
        }

        return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        adapter.bullets = (ArrayList<Bullet>) results.values;

        //REFRESH RECYCLERVIEW
        adapter.notifyDataSetChanged();
    }
}

menu_activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/item_search"
        android:icon="@drawable/ic_action_search"
        android:title="Search..."
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="collapseActionView|ifRoom" />

    <item
        android:id="@+id/item_add"
        android:icon="@drawable/ic_action_add2"
        android:title="Add"
        app:showAsAction="always" />

</menu>

I believe that's all the code that affects it, but if there's anything else you need let me know.
Here's the Stack Trace:
I don't really understand what it means, but it's what occurs when I try to filter some query after a LongClick Event.

09-07 01:46:38.184 17027-17104/com.curtiswhite.www.sqlitedatabaseforephemeris I/OpenGLRenderer: Initialized EGL, version 1.4
      09-07 01:47:40.066 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
      09-07 01:47:40.066 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
      09-07 01:47:45.036 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
      09-07 01:47:45.036 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
      09-07 01:47:45.991 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
      09-07 01:47:45.991 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
      09-07 01:47:46.003 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
      09-07 01:47:46.003 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
      09-07 01:47:46.015 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris W/IInputConnectionWrapper: getTextAfterCursor on inactive InputConnection
      09-07 01:47:46.022 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
      09-07 01:47:46.023 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
      09-07 01:47:46.023 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
      09-07 01:47:46.023 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
      09-07 01:47:46.024 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris W/IInputConnectionWrapper: getTextAfterCursor on inactive InputConnection
      09-07 01:47:46.027 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
      09-07 01:47:46.027 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
      09-07 01:47:46.027 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
      09-07 01:47:46.028 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
      09-07 01:47:46.030 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris W/IInputConnectionWrapper: getTextAfterCursor on inactive InputConnection
      09-07 01:47:46.062 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
      09-07 01:47:46.062 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
      09-07 01:47:46.062 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
      09-07 01:47:46.063 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
      09-07 01:47:46.063 17027-17027/com.curtiswhite.www.sqlitedatabaseforephemeris W/IInputConnectionWrapper: getTextAfterCursor on inactive InputConnection

A: I solved the issue.
It turns out that the issue was caused when inflating the new menu onLongClick. This caused the SearchView to deflate (as expected), but upon pressing back (OnBackPressed gets called), the original menu would inflate, but the SearchView that was placed there was a new one which had not been instantiated.
To correct this, I simply called OnCreateMenuOptions(toolbar.getMenu()); in the onBackPressed method. This reinstantiates the SearchView so it will work again after the menu inflates.


text:
Q: Fuseki service capabilities - programmatically I am starting a fuseki server with the provided configuration file (see below).  What I would like to do is to retrieve the capabilities of the service once it is created.  The reason being, there could be multiple such SPARQL services (available over the net but capabilities are not know to me) and I want to select some based on their capabilities (e.g., services with update capabilities).  Is there anyway to find that (i.e., service capabilities) out programmatically?  Any advice regarding this would be much appreciated.
Configuration file
@prefix :        <#> .
@prefix fuseki:  <http://jena.apache.org/fuseki#> .
@prefix rdf:     <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs:   <http://www.w3.org/2000/01/rdf-schema#> .
@prefix tdb:     <http://jena.hpl.hp.com/2008/tdb#> .
@prefix ja:      <http://jena.hpl.hp.com/2005/11/Assembler#> .

[] rdf:type fuseki:Server ;
   fuseki:services (
     <#animal_service_pellet>
   ) .

# TDB
[] ja:loadClass "com.hp.hpl.jena.tdb.TDB" .
tdb:DatasetTDB  rdfs:subClassOf  ja:RDFDataset .
tdb:GraphTDB    rdfs:subClassOf  ja:Model .

<#animal_service_pellet> rdf:type fuseki:Service ;
    rdfs:label                          "TDB Service (RW)" ;
    fuseki:name                         "animals/pellet" ;
    fuseki:serviceQuery                 "query" ;
    fuseki:serviceQuery                 "sparql" ;
    fuseki:serviceUpdate                "update" ;
    fuseki:serviceUpload                "upload" ;
    fuseki:serviceReadWriteGraphStore   "data" ;
    fuseki:serviceReadGraphStore        "get" ;
    fuseki:dataset                      <#inferred_pellet> ;
    .

<#inferred_pellet>
  a ja:RDFDataset;
    ja:defaultGraph [
                      a ja:InfModel;
                      ja:reasoner [
                                    ja:reasonerClass "org.mindswap.pellet.jena.PelletReasonerFactory";
                                  ];
                      ja:baseModel <#data_and_ontology_graph>
                    ];
  .

<#data_and_ontology_graph>
  a tdb:GraphTDB ;
  tdb:location "TDB_LOC" ;
  .

A: The same question has been asked on the Jena users mailing list.
http://mail-archives.apache.org/mod_mbox/jena-users/201206.mbox/%3C4FC884AE.5020409%40apache.org%3E
Try the DatasetRegistry - there is one global one, accessed via it's get() static.
org.apache.jena.fuseki.server.DatasetRegistry
The other way is to read the configuration file as RDF and look in that.
The configuration parser is in FusekiConfig
In the future, there will be support for SPARQL service descriptions [1].  Contributions welcome.
[1] http://www.w3.org/TR/sparql11-service-description/


text:
Q: Scheme (Racket) if within cond returns nothing I have been working in DrRacket, trying to create a "prefix" function (#lang racket).  It should take two lists as an input, and should output #t if pf is either null, or is equal to the beginning of ls.
My problem is that my code doesn't seem to return anything at all when pf is not a prefix of ls and ls isn't null.  If I replace the #f in the if statement with something else, like '(), it will return that properly, but if I try to capture the '() and give an output based on that instead, it gives results that don't make sense (like saying that '() isn't null, or that '() doesn't equal '()).  It seems to have something to do with having an if statement within a cond statement.  Could anyone tell me what it's doing, or why?  Is it possible to make this code work correctly, or am I going to need to rework it another way?
Thanks for the help!
(define prefix
  (lambda (pf ls)
    (cond
      [(null? pf) #t]
      [(null? ls) #f]
      [(if (equal? (car pf) (car ls)) (prefix (cdr pf) (cdr ls)) #f)])
      ))

A: Having an if within a cond condition is usually a sign of doing something wrong. I think you meant to say this:
(define prefix
  (lambda (pf ls)
    (cond
      [(null? pf) #t]
      [(null? ls) #f]
      [(equal? (car pf) (car ls)) (prefix (cdr pf) (cdr ls))]
      [else #f])))


text:
Q: centering a border within a class this is probably a laughable question but for some reason i just can't seem to align these guys so that they are totally centered.  For some reason the border box seems to be to the left and not sure why.  Can someone help...
jsfiddle. http://jsfiddle.net/greggy_coding/b3k9Lhfz/4/
the html and css

            LEARN MORE

Click to find out more

body {
    background: #fff;
}

.container-bottom h4 {
  font-weight: 500;
  font-size : 16px ;
  text-align:center;
  color: #fff;
  margin-left : auto;
  margin-right : auto;
}

.linkbutton{
    border: 2px solid #fff;
    padding: 10px 50px;
    width: 50px;
    border-radius: 30px;
    margin: auto;
    position: relative;
}
.container-bottom{
    background-color: #000;
    width: 300px;
    height:20%;
    padding: 25px;
    position: relative;
   margin-left: auto ;
  margin-right: auto ;
  margin-top:30px;

  }

A: The link is inline so margin: auto; isn't going to work.
Use text-align: center; on the parent element instead.
.container-bottom {
    . . .
    text-align: center;
}

A: An alternative method is:
.linkbutton{
    /* You were missing this */
    display: block;
    /* Need this to align your text in the middle */
    text-align: center;
    border: 2px solid #fff;
    /* Controlling your padding here */
    padding: 10px;
    /* Specifying the width is important */
    width: 200px;
    border-radius: 30px;
    margin: auto;
    position: relative;
}


text:
Q: Calculus, stationary point and sketching the curve i just need help with a tiny question.
Im doing caculus and is told to find stationary point and sketch curve.
I have determined that there are no stationary points. How do i graph this?
The original question is y= (x-1)/ (x^2 -9)
Thanks Everyone for your help!

A: You need to take the first derivative of the given function: $y= \dfrac{(x-1)}{(x^2 -9)}$ and then set $y' = 0$. I.e., solve for the value(s) of $x$ for which $y' = 0$.
Using the quotient rule, we find that
$$y' = \dfrac {x^2 - 2x + 9}{(x^2 - 9)^2} = 0$$ There are no such values of $x$ for which $y' = 0 $. But $y'$ is also useful for determining where the function is increasing and or decreasing.
To graph the function, note where the function is undefined: you'll have asymptotes to help bound portions of your graph. Note in particular, where the denominator equals $0$. Typically, you'd also plot any/all stationary points, after determining whether they are local minimums, maximums, etc. You're correct, there are no such minimums or maximums with your function. But there asymptotes. There will be three separate curves to plot: one which "hugs" closely by the y-axis, and the other two hyperbolic in form.
Then you may want to plot a few other values, to help "fill in the gaps" of the graph.
Compare your sketch, then to the following:


text:
Q: Principal axis of a matrix I try to find the definition of the main axis of a matrix.
I saw this phrase in some exercise:

Let $A$ be a positive matrix, $f:G\longrightarrow \mathbb{R}$ a smooth function, $G$ an open set in $\mathbb{R}^n$. I need to find the orthogonal coordinate transformation $y=Px$ such that the main axis on $y$'s coordinates will be the principle axis of $A$.

The book says to diagonalize $A$: $PAP^t=D$ and to choose $P$ to be the transformation.
What is the definition of principle axis of matrix?
thanks.

A: Often, principal axes of a matrix refer to its eigenvectors. With this diagonalization, $P$ is the matrix of eigenvectors.


text:
Q: python toggle-able function by a button I am messing around python, and made this simple thing that works on my pc that opens up discord logs in and messages something. I want this to run in the background and make it toggle-able by a button, all tho i have no idea how to do it since i started learning only today!
# log in as dave the goat and message dog dave the dog
# positions for my icons below

# 20, 137 chrome
# 307, 48 search bar
# 1674, 105 open discord web
# 687, 685 login
# 681, 517 click on email
# 915, 578 click on the right email
# 220, 310 click on dog
# 654, 1034 click on message

import pyautogui
import time

pyautogui.click(20, 137) # click on chrome

time.sleep(0.7)

pyautogui.click(307, 48) # click on search bar

pyautogui.typewrite("discord.com")
pyautogui.typewrite(["enter"])

time.sleep(0.5)

pyautogui.click(1674, 105)

time.sleep(0.7)

pyautogui.click(687, 685)

time.sleep(3.9)

pyautogui.click(220, 310)

pyautogui.click(654, 1034)

pyautogui.typewrite("Dave the goat says hello")
pyautogui.typewrite(["enter"])


text:
Q: Using python lime as a udf on spark I'm looking to use lime's explainer within a udf on pyspark. I've previously trained the tabular explainer, and stored is as a dill model as suggested in link
loaded_explainer = dill.load(open('location_to_explainer','rb'))

def lime_explainer(*cols):
    selected_cols = np.array([value for value in cols])
    exp = loaded_explainer.explain_instance(selected_cols, loaded_model.predict_proba, num_features = 10)
    mapping = exp.as_map()[1]

    return str(mapping)

This however takes a lot of time, as it appears a lot of the computation happens on the driver. I've then been trying to use spark broadcast to broadcast the explainer to the executors.
broadcasted_explainer= sc.broadcast(loaded_explainer)

def lime_explainer(*col):
    selected_cols = np.array([value for value in cols])
    exp = broadcasted_explainer.value.explain_instance(selected_cols, loaded_model.predict_proba, num_features = 10)
    mapping = exp.as_map()[1]

    return str(mapping)

However, I run into a pickling error, on broadcast.

PicklingError: Can't pickle  at 0x7f69fd5680d0>:
  attribute lookup  on lime.discretize failed

Can anybody help with this? Is there something like dill that we can use instead of the cloudpickler used in spark?

A: I'm the dill author.  I agree with @Majaha, and will extend @Majaha's answer slightly. In the first link in @Majaha's answer, it's clearly pointed out that a Broadcast instance is hardwired to use pickle... so the suggestion to dill to a string, then undill afterward is a good one.
Unfortunately, the extend method probably won't work for you.  In the Broadcast class, the source uses CPickle, which dill cannot extend.
If you look at the source, it uses import CPickle as pickle; ... pickle.dumps for python 2, and import pickle; ... pickle.dumps for python 3. Had it used import pickle; ... pickle.dumps for python 2, and import pickle; ... pickle._dumps for python 3, then dill could extend the pickler by just doing an import dill. For example:
Python 3.6.6 (default, Jun 28 2018, 05:53:46)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from pickle import _dumps
>>> import dill
>>> _dumps(lambda x:x)
b'\x80\x03cdill._dill\n_create_function\nq\x00(cdill._dill\n_load_type\nq\x01X\x08\x00\x00\x00CodeTypeq\x02\x85q\x03Rq\x04(K\x01K\x00K\x01K\x01KCC\x04|\x00S\x00q\x05N\x85q\x06)X\x01\x00\x00\x00xq\x07\x85q\x08X\x07\x00\x00\x00<stdin>q\tX\x08\x00\x00\x00<lambda>q\nK\x01C\x00q\x0b))tq\x0cRq\rc__main__\n__dict__\nh\nNN}q\x0etq\x0fRq\x10.'

You could, thus, either do what @Majaha suggests (and bookend the call to broadcast) or you could patch the code to make the replacement that I outline above (where needed, but eh...), or you may be able to make your own derived class that does the job using dill:
>>> from pyspark.broadcast import Broadcast as _Broadcast
>>>
>>> class Broadcast(_Broadcast):
...   def dump(self, value, f):
...     try:
...       import dill
...       dill.dump(value, f, pickle_protocol)
...     ...[INSERT THE REST OF THE DUMP METHOD HERE]...

If the above fails... you could still get it to work by pinpointing where the serialization failure occurs (there's dill.detect.trace to help you with that).
If you are going to suggest to pyspark to use dill... a potentially better suggestion is to allow users to dynamically replace the serializer.  This is what mpi4py and a few other packages do.

A: Looking at this source, it seems like you have no choice but to use the pickler provided. As such, I can only suggest that you nest dill inside of the default pickler. Not ideal, but it could work. Try something like:
broadcasted_explainer = dill.loads(sc.broadcast(dill.dumps(loaded_explainer)).value)

Or you might try calling the Dill extend() method which is supposed to add Dill datatypes into the default pickle package dispatch. No idea if that will work but you can try it!

A: What's your location_to_explainer data schema? Maybe it better to transform to spark's dataframe.
According to dill desciption

dill can be used to store python objects to a file, but the primary usage is to send python objects across the network as a byte stream. dill is quite flexible, and allows arbitrary user defined classes and functions to be serialized. Thus dill is not intended to be secure against erroneously or maliciously constructed data. It is left to the user to decide whether the data they unpickle is from a trustworthy source.

And When Not To Use pickle

If you want to use data across different programming languages, pickle is not recommended. Its protocol is specific to Python, thus, cross-language compatibility is not guaranteed. The same holds for different versions of Python itself. Unpickling a file that was pickled in a different version of Python may not always work properly, so you have to make sure that you're using the same version and perform an update if necessary. You should also try not to unpickle data from an untrusted source. Malicious code inside the file might be executed upon unpickling.

According to this discuss , you can try pysparkling

I don't think this is a dill issue, as I don't think your code is using dill. So, as far as I know, pyspark uses pickle or cloudpickle and not dill. However, if you do want to use dill with pyspark, there is pysparkling (https://pypi.python.org/pypi/pysparkling)... and using it may clear up your serialization issue. What I suggest is that you open a ticket with pyspark or try pysparkling and if it fails, open a ticket there -- and CC me or refer to this issue so I can follow the thread. I'm going to close this... so if I'm incorrect and you are using dill, please feel free to reopen this issue.

Read more Reading pyspark pickles locally


text:
Q: Dropzone does not work inside jquery tabs I am trying to use dropzone inside a jquery tab.
In the file that is being called by the tab I include dropzone.min.js, dropzone.min.css, basic.min.css.
I copied your code of the form.
I get the normal file input and not the drop zone option.
In firebug, I do see the dropzone.min.js is being called.
Trying the same code on a stand alone html file, everything is fine, besides the fact that I don't get the style you have.
Can this not work inside a tab?
Doesn't make sense to me.

A: You could try to initialize it programatically instead of using a form:
http://www.dropzonejs.com/#create-dropzones-programmatically
Don't forget to set up an URL to an Action...
Regards,


text:
Q: Using Jasmine to spy on document.createElement throws error from angular mock I have an Angular service that handles the webcam. Here is the function I'm trying to test:
this.takePicture = function() {
    var canvas = document.createElement('canvas');
    canvas.width = this.width;
    canvas.height = this.height;

    var context = canvas.getContext('2d');
    context.drawImage(this.videoElement, 0, 0, this.width, this.height);

    return canvas.toDataURL('image/jpeg', 100);
};

I'm trying to mock the call to document.createElement and return a fake canvas object. Here is my test:
it('should draw an image', function() {
    var drawImageSpy = jasmine.createSpy('drawImage');

    var canvas = {
        getContext: jasmine.createSpy('getContext').and.returnValue({ drawImage: drawImageSpy }),
        width: 0,
        height: 0,
        toDataURL: jasmine.createSpy('toDataUrl').and.returnValue('data-uri')
    };

    document.createElement = jasmine.createSpy('createCanvas').and.returnValue(canvas);

    WcCameraService.takePicture();

    expect(drawImageSpy).toHaveBeenCalled();
});

Here is the error I'm getting:
TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
    at TypeError (native)
    at Function.jQuery.extend.buildFragment (C:/Projects/Accurev/WebCOE_FRF_DEV/src/bower_components/jquery/dist/jquery.js:5565:24)
    at Function.jQuery.parseHTML (C:/Projects/Accurev/WebCOE_FRF_DEV/src/bower_components/jquery/dist/jquery.js:9923:18)
    at jQuery.fn.init (C:/Projects/Accurev/WebCOE_FRF_DEV/src/bower_components/jquery/dist/jquery.js:2774:33)
    at Object.jQuery [as element] (C:/Projects/Accurev/WebCOE_FRF_DEV/src/bower_components/jquery/dist/jquery.js:73:10)
    at $get (C:/Projects/Accurev/WebCOE_FRF_DEV/src/bower_components/angular-mocks/angular-mocks.min.js:6:18224)
    at Object.e [as invoke] (C:/Projects/Accurev/WebCOE_FRF_DEV/src/bower_components/angular/angular.min.js:39:193)
    at C:/Projects/Accurev/WebCOE_FRF_DEV/src/bower_components/angular/angular.min.js:41:10
    at Object.d [as get] (C:/Projects/Accurev/WebCOE_FRF_DEV/src/bower_components/angular/angular.min.js:38:394)
    at Object.<anonymous> (C:/Projects/Accurev/WebCOE_FRF_DEV/src/bower_components/angular-mocks/angular-mocks.min.js:6:21105)

Does anyone have any idea why this is happening? I was looking in angular-mocks and it seems to be failing at this point:
if (window.jasmine || window.mocha) {

...

  if (injector) {
    injector.get('$rootElement').off();
  }

A: To the best of my knowledge, document.createElement is immutable. You really shouldn't be spying on it in the first place. It's a built-in function that will perform the same way every time. Your other spies look fine.

A: Its kind of weird to spy on that. But -in greater versions of angular- you can accomplish it by just spying into the createElement method. You can join this with a returnValue with a jasmine spy to expect certain calls. Like this:
const toDataUrlSpy = jasmine.createSpy('dataUrl');
spyOn(document, 'createElement').and.returnValue({
  width: 0,
  height: '',
  getContext: () => ({ drawImage: () => {} })
  toDataURL: toDataUrlSpy
});

service.takePicture();
expect(toDataUrlSpy).toHaveBeenCalledTimes(1);

Cheers!


text:
Q: isHandler Method of RequestMappingHandlerMapping retunrs true for both RequestMapping and Controller annotation I am looking into Dispatcher Servlet code. Here i found that dispatcher servlet uses HandlerMapping to select the handler for the request. Also, RequestMappingHandlerMapping is used as an implementation for HandlerMapping. Now, isHandlerMethod of RequestMappingHandlerMapping returns true if the bean under consideration has either @Controller or @RequestMapping annotation. If certain bean has only @RequestMapping annotation applied at class level would it still be considered as Handler?.
Any Help would be greatly appreciated.

A: The @RequestMapping and @Controller annotation have different meanings. The request mapping is used to decide, which class / method is used to handle a request to a speciffic URL. If you look at the source of the @Controller adnotation you will find that it is annotated with @Component itself. This way it can be used to set up the component scan that will register an instance of the class as a bean.
I'm quessing that, since those annotations are usually used together, it's done so that a minute performance gain can be achieved. Also, you could declare your controllers differently, either by java config or xml.
Edit:
I have done a quick prototype with a controller bean declared in java config, without the @Controller annotation. The answer is yes, the method will be used to handle a request, even if the class is not annotated.


text:
Q: Pysaprk parse complex json to rows I have the following json in a file:
{
    "code": 0,
    "msg": "OK",
    "sensors": {
        "258443": {
            "fieldname": "DeviceStatus2",
            "info": "Unlock Request",
            "id": 258443,
            "work": {
                "1623020526": {
                    "ts": 1623020526,
                    "te": 1623021124,
                    "lat": "-25.911997",
                    "lon": "28.169119"
                },
                "1623021393": {
                    "ts": 1623021393,
                    "te": 1623021453,
                    "lat": "-25.911997",
                    "lon": "28.169119"
                },
                "1623052154": {
                    "ts": 1623052154,
                    "te": 1623052783,
                    "lat": "-25.790348",
                    "lon": "28.308369"
                }
            }
        },
        "258441": {
            "fieldname": "Dis1",
            "info": "Door",
            "id": 258441,
            "work": {
                "1623021447": {
                    "ts": 1623021447,
                    "te": 1623035978,
                    "lat": "-25.911997",
                    "lon": "28.169119"
                },
                "1623052775": {
                    "ts": 1623052775,
                    "te": 1623058925,
                    "lat": "-25.790348",
                    "lon": "28.308369"
                }
            }
        },
        "258442": {
            "fieldname": "AnalogInput",
            "info": "Lock Fire",
            "id": 258442,
            "work": {
                "1623021453": {
                    "ts": 1623021453,
                    "te": 1623021633,
                    "lat": "-25.911997",
                    "lon": "28.169119"
                },
                "1623052783": {
                    "ts": 1623052783,
                    "te": 1623052962,
                    "lat": "-25.790348",
                    "lon": "28.308369"
                }
            }
        }
    }
}

I need to use pyspark to parse it into the following rows:
258443,DeviceStatus2,Unlock Request,258443,1623020526,1623021124,-25.911997,28.169119
258443,DeviceStatus2,Unlock Request,258443,1623021393,1623021453,-25.911997,28.169119
258443,DeviceStatus2,Unlock Request,258443,1623052154,1623052783,-25.790348,28.308369
258441,Dis1,Door,258441,1623021447,1623035978,-25.911997,-25.911997
258441,Dis1,Door,258441,1623052775,1623058925,-25.790348,28.308369
258442,AnalogInput,Lock Fire258442,1623021453,1623021633,-25.911997,28.169119
258442,AnalogInput,Lock Fire258442,1623052783,1623052962,-25.790348,28.308369

I have tried to use explode and arrays_zip but its failing.
How can I parse this json into rows?

A: Using IDs as key in a JSON is a very bad idea because it means your struct change all the time. Ideally, keys should remain the same and just values have to change.
But you can cheat a little bit using MapType.
you need to use this schema to properly acquire your JSON data in spark :
from pyspark.sql import types as T

schm = T.StructType(
    [
        T.StructField("code", T.IntegerType()),
        T.StructField("msg", T.StringType()),
        T.StructField(
            "sensors",
            T.MapType(  # This map type allows any ID as key
                T.StringType(),
                T.StructType(
                    [
                        T.StructField("fieldname", T.StringType()),
                        T.StructField("info", T.StringType()),
                        T.StructField("id", T.IntegerType()),
                        T.StructField(
                            "work",
                            T.MapType(  # Same here
                                T.StringType(),
                                T.StructType(
                                    [
                                        T.StructField("ts", T.IntegerType()),
                                        T.StructField("te", T.IntegerType()),
                                        T.StructField("lat", T.StringType()),
                                        T.StructField("lon", T.StringType()),
                                    ]
                                ),
                            ),
                        ),
                    ]
                ),
            ),
        ),
    ]
)

Then, your dataframe should have this schema :
df.printSchema()
root
 |-- code: integer (nullable = true)
 |-- msg: string (nullable = true)
 |-- sensors: map (nullable = true)
 |    |-- key: string
 |    |-- value: struct (valueContainsNull = true)
 |    |    |-- fieldname: string (nullable = true)
 |    |    |-- info: string (nullable = true)
 |    |    |-- id: integer (nullable = true)
 |    |    |-- work: map (nullable = true)
 |    |    |    |-- key: string
 |    |    |    |-- value: struct (valueContainsNull = true)
 |    |    |    |    |-- ts: integer (nullable = true)
 |    |    |    |    |-- te: integer (nullable = true)
 |    |    |    |    |-- lat: string (nullable = true)
 |    |    |    |    |-- lon: string (nullable = true)

Then, simply using explode and select, you can achieve the desired output :
df.select(F.explode("sensors").alias("key", "sensor")).select(
    "sensor", F.explode("sensor.work").alias("key", "work")
).select(
    "sensor.id",
    "sensor.fieldname",
    "sensor.info",
    "work.te",
    "work.ts",
    "work.lat",
    "work.lon",
).show()

+------+-------------+--------------+----------+----------+----------+---------+
|    id|    fieldname|          info|        te|        ts|       lat|      lon|
+------+-------------+--------------+----------+----------+----------+---------+
|258443|DeviceStatus2|Unlock Request|1623021124|1623020526|-25.911997|28.169119|
|258443|DeviceStatus2|Unlock Request|1623021453|1623021393|-25.911997|28.169119|
|258443|DeviceStatus2|Unlock Request|1623052783|1623052154|-25.790348|28.308369|
|258441|         Dis1|          Door|1623035978|1623021447|-25.911997|28.169119|
|258441|         Dis1|          Door|1623058925|1623052775|-25.790348|28.308369|
|258442|  AnalogInput|     Lock Fire|1623021633|1623021453|-25.911997|28.169119|
|258442|  AnalogInput|     Lock Fire|1623052962|1623052783|-25.790348|28.308369|
+------+-------------+--------------+----------+----------+----------+---------+


text:
Q: Is there a difference between Ruby's Hash "value?" and "has_value?" I'm looking at Hash docs for has_value? and value?.  However the link for value? leads to duplicate information about has_value?.
value? seems to work identically to has_value? (Ruby 3.02).
Does this mean value? is becoming deprecated or is this a documentation error?

A: You can check if they are identical by comparing their method objects:
Hash.instance_method(:value?) == Hash.instance_method(:has_value?)
#=> true

UnboundMethod#== returns true if the methods refer to the same implementation.

Does this mean value? is becoming deprecated or is this a documentation error?

It seems to be a documentation error. The docs from the official website are more explicit regarding the alias:
https://docs.ruby-lang.org/en/3.0.0/Hash.html#method-i-has_value-3F

has_value?(value) → true or false
Returns true if value is a value in self, otherwise false.
Also aliased as: value?

However, the entry for value? doesn't have a heading: (the bold value?(value) → true or false part is missing)
https://docs.ruby-lang.org/en/3.0.0/Hash.html#method-i-value-3F

Returns true if value is a value in self, otherwise false.
Alias for: has_value?


text:
Q: XAML UWP Adaptive Buttons I am trying to implement two side-by-side responsive buttons and I want them to behave like on the image below.

This is my XAML:
<RelativePanel x:Name="contentPanel">
       <Button x:Name="submitButton" Content="Submit"
                Margin="0,40,0,0"
                MinWidth="250"
                RelativePanel.AlignLeftWithPanel="True"/>

        <Button x:Name="annulerButton" Content="Cancel"
                Margin="5,40,0,0"
                MinWidth="250"
                RelativePanel.RightOf="submitButton"
                RelativePanel.AlignRightWithPanel="True"/>
<RelativePanel/>

Please, any help?

A: Use Grid with ColumnDefinition something like below.
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button x:Name="submitButton" Content="Submit" Margin="5" Grid.Column="0" HorizontalAlignment="Stretch" />
    <Button x:Name="annuleButton" Content="Cancel" Margin="5" Grid.Column="1" HorizontalAlignment="Stretch"/>
</Grid>

and end output will be

A: You can use the open-source implementation of the UniformGrid for UWP instead of the relative panel.
Alternatively, you can try to put your buttons into the standard Grid control, though it may misbehave if resized to a rather small size. But as the buttons' minimal width is set to the same value in your case, you will not face this issue.
<Grid x:Name="contentPanel">
   <Grid.ColumnDefinitions>
       <ColumnDefinition Width="*" />
       <ColumnDefinition Width="*" />
   </Grid.ColumnDefinitions>
   <Button x:Name="submitButton" Content="Submit"
            Margin="0,40,0,0"
            MinWidth="250"
            Grid.Column="0"/>
    <Button x:Name="annulerButton" Content="Cancel"
            Margin="5,40,0,0"
            MinWidth="250"
            Grid.Column="1"/>
</Grid>


text:
Q: Is a 9 or 10 cost minion hit by Freezing Trap unplayable? Today I was playing a game and had only my C'Thun on the board and my opponent (a Hunter) played a trap. I figured I was pretty safe as C'Thun would survive a damaging trap and I had an Innervate in my hand if he were to get returned. However, the Freezing Trap returned him to my hand and increased his cost by 2 (to bring it to 12) and when I played Innervate, it did nothing (kept my mana at 10 and did not allow C'Thun to be played).
It seems a bit overpowered for such a low cost trap card to essentially act as both a hard removal AND reduce your hand size by one (because you're then stuck with the useless 12-cost card in your hand), but aside from some sort of "Your minion costs are reduced by two" card, that seems to be the case.
Am I missing something? Is there a better way to defend against this aside from "Play a low cost minion, hope it doesn't die and attack with it first the next turn"?

A: Yes, a 9 or 10 mana minion bounced back by a Freezing Trap becomes unplayable. There's (currently) no way to get above 10 mana and Cost-reducing effects for minions are very rare: as of today only 3 minions offer a cost-reducing effect, Emperor Thaurissan, Pint-Sized Summoner and Summoning Portal. Of these only Thaurissan sees play, since the other two have usually no immediate impact on the game state and can be easily removed. Also, in this specific case, Thaurissan would still require to be played after your C'Thun has been bounced back in hand AND survive for at least another turn after he's been played.
The "Play a low cost minion, hope it doesn't die and attack with it first the next turn" is exactly the way to play around Freezing Trap. Usually anyway the Freezing Trap is used way before turn 10 and most of the Hunter decks in the current meta use only one copy, so normally the chance of your C'Thun being bounced back is pretty low.
The perceived Overpowerednees of the trap is offset by the fact that it has to be played proactively, so the Hunter doesn't get the chance to target the minion to bounce, giving you the opportunity to play around it.

A: You cannot have more than 10 mana at once, so the only way to play a card more expensive than 10 mana is to reduce its cost to 10 or below. So, no you are not missing anything. The way to work against hunter traps generally is to deduce which trap it most likely is and play around it. In case of freezing trap it's using an expendable minion (or one with a good battlecry) to trigger it or use a card which destroys secrets (e.g. eater of secrets)
However, I don't see how this is overpowered. The likelihood of this situation occuring is fairly low and if it happens, you know it is a possibility and have to play around it. There is also the possiblity, that the hunter played misdirection and your own C'thun might have hit you in the face. Taking those two traps into account, it's an easy decision not to attack with C'thun until you have another minion to trigger the trap available or a card to destroy the secret, as the risk is simply too high. So unless, you are in a desperate situation anyway, there is little reason to take that risk.
Additionally take into account what other trap he could have played. Playing an explosive trap, when you only have a C'thun on board is utterly pointless, unless you'd die from the damage; the same applies to dart trap. Bear Trap only makes sense, when the hunter survives the hit from C'thun. Snake trap pointless as well, unless you want to trade, which is unlikely when using C'thun. Snipe? What's the point with a C'thun on board? Apart from that freezing trap is by far the most common hunter secret.
So, you can see, unless the hunter was utterly desperate, there was little reason for him to play anything besides freezing trap or misdirection.