text:
Q: Selecting string columns in pandas df (equivalent to df.select_dtypes) Given a Pandas df with different data types, df.select_dtypes can be very useful to keep only desired columns or to get rid of unwanted columns for a particular application.
However, there seems to be no way of addressing string dtypes using this method.
From the docs (emphasis mine):

ValueError
    If both of include and exclude are empty
    If include and exclude have overlapping elements
    If any kind of string dtype is passed in.

and

To select strings you must use the object dtype, but note that this will return all object dtype columns

Indeed, using df.select_dtypes(exclude=['str']) raises an error (although it is a TypeError and not a ValueError as the docs claim) and using df.select_dtypes(exclude=['object']) removes all object columns, not just string columns.
Given a df like this:
df = pd.DataFrame({'int_col':[0,1,2,3,4],
                   'dict_col':[dict() for i in range(5)],
                   'str_col':list('abcde')})

and considering that
df.dtypes

is object for both str_col and dict_col:
What is the best way of excluding or including all string columns?

A: Option 1
Using df.applymap and type, and equating to str:
In [377]: (df.applymap(type) == str).all(0)
Out[377]:
dict_col    False
int_col     False
str_col      True
dtype: bool

Each element in each column converted to its type and then equated to str. After that, just call .all(0) or .min(0) to get a per-column verdict.

Option 2
Using df.applymap and isinstance:
In [342]: df.applymap(lambda x: isinstance(x, str)).all(0)
Out[342]:
dict_col    False
int_col     False
str_col      True

To include these string columns, you can boolean index on the columns:
idx = ... # one of the two methods above
df_new = df[df.columns[idx]]

Exclusion would be
df_new = df[df.columns[~idx]]

A: From the pandas source:
~/.local/share/virtualenvs/.../lib/python3.7/site-packages/pandas/core/dtypes/cast.py in invalidate_string_dtypes(dtype_set)
    851     non_string_dtypes = dtype_set - {np.dtype("S").type, np.dtype("<U").type}
    852     if non_string_dtypes != dtype_set:
--> 853         raise TypeError("string dtypes are not allowed, use 'object' instead")
    854
    855

best practice is to use object instead, apparently. So, just do
df.select_dtypes(exclude=['object'])
under the assumption that no actual Python objects are in those columns but str types.


text:
Q: ordering facet_wrap levels by frequency I'm trying to do a waffle chart for the championships won by F1 drivers so far. The chart comes out good but it comes out with alphabetical labels. I want it to start from the most titles won to the least.
I've tried ordering and fct_relevel. But nothing works. Below is the code
ggplot(data = dfc, aes(fill=Champions, values=one)) +
  geom_waffle(color = "cornsilk", size=0.25, n_rows=7)+
  facet_wrap(~Champions, nrow = 3, strip.position = "bottom",labeller = label_wrap_gen(6))

And this is the
result I'm looking for.
You can find the entire code here
The dataset looks like
Season    Champions    Team   one
1              a           x     1
2              a           x     1
3              b           y     1
4              a           x     1
5              c           z     1

A: Here's a solution using forcats (also part of the tidyverse package).
fct_infreq() orders factors according to their frequency in the data, and you can use that to specify the ordering of the levels in your data.
dfc$Champions <- factor(dfc$Champions, levels=levels(fct_infreq(dfc$Champions)))

ggplot(data = dfc, aes(fill=Champions, values=one)) +
  geom_waffle(color = "cornsilk", size=0.25, n_rows=7) +
  facet_wrap(~Champions, nrow = 3, strip.position = "bottom", labeller = label_wrap_gen(6))

redpajama_set_name: RedPajamaStackExchange


text:
Q: LinkedIn "share" API not properly using the supplied "content.description" I'm successfully able to POST a new LinkedIn "share" of an image (not an actual article/page) with a comment via the API by making an OAuth-authenticated call like this:
URI: POST https://api.linkedin.com/v1/people/~/shares?format=json
Data:
{
  "comment": "Some comment.",
  "content": {
    "title": "Some title.",
    "description": "My description.",
    "submitted-url": "https://cdn.website.com/images/image.png",
    "submitted-image-url": "https://cdn.website.com/images/image.png"
  },
  "visibility": {
    "code": "connections-only"
  }
}

However, when I view the resulting Share on linkedin.com the description near the image will not show my supplied "My description." and instead will show the host of the supplied image, i.e. cdn.website.com in this example. This is ugly and not desirable. It seems like they try to crawl the image as if it were a page, and are defaulting to the host instead of using my supplied description of "My description.".
Is this a bug? Am I doing something wrong? Any help would be appreciated!

A: You may choose only one of the following:

*

*Show image in LinkedIn share preview.

*Show description in LinkedIn share preview.

Proof: Two weeks fighting LinkedIn Support (Oh the humanity...).  But also look at share previews for sites that follow both of these rules: Wikipedia (has no image, has 1 description) and GitHub (has 1 image, has 1 description).

Wikipedia: Description ONLY -- Works (but no image)!
GitHub: Image ONLY -- Works (but no description)!
I made a test site, with only description, and it behaves according to the rule above-listed.  I'm well aware that the Official Microsoft LinkedIn Share Documentation makes no mention whatsoever of this, but all direct experience seems to disagree.


text:
Q: How to define [bigint] in powershell windows7? We are unable to define data type [bigint] in powershell version 2 in OS win7, also we use [System.Numerics.BigInteger] again not work,
Is there a way to do this?

A: Unfortunately PowerShell version 2 doesn't support this. But in 3.O and later versions you can achieve this.
[bigint]1e20

It will give following output:
100000000000000000000


text:
Q: angularjs route go back to previous filtered state instead of original state I have a table, display a list of items, using dirPagination for filtering data and pagination. Code like this

and the input filter like this
<input ng-model="query" placeholder="Search">

For each item in the results table, i have a 'View Details' button
view details

This button will takes you to the details of the time using angular-route as below. And details controller is as below as well. It has a back function that takes user back to list view.
   $routeProvider.when('/viewDetails/:id/', {
        templateUrl: 'details.html',
        controller: 'detailsCtrl'
    }).when('/listView/', {
        templateUrl: 'list.html',
        controller: 'listCtrl'
    });

app.controller('detailsCtrl', function ($scope, $location, $routeParams) {
    var guid = $routeParams.id;
    $scope.back = function () {
        $location.path('/listView');
    };
}

So my question is, when clicks back, i want to takes me back to the filtered state. For example, in list view, i filter all items that name contains 'test'.
Then I click view details to see details of one item.  When i go back, i want to still apply the filter, only show items that name contains 'test'
The current code i have, will take me back to original state, where no filter gets applied.  Any suggestion?


text:
Q: Capturing further detail in agile Couple of questions about capturing detail in an agile project.
I understand the concept that user stories are not there to capture detail in the first instance but are a placeholder for more detailed conversations with the users.  Where should the detail from such conversations be recorded - in the user story, as a use case or scenarios (or something else)?
Specifically we have a requirement to interface with 'system X'. As a result of detailed analysis I want to record how the interaction of the browser with system X for example:

*

*What triggers the sending of details to system X interface

*The data sent to system X

*the handling of responses from system X

*what happens if system X is not available

and so on.  In waterfall this would be captured in a use case - in the agile world where do I record this detail?
Thanks

A: The typical/old school system is "write them on the back of the card", but in reality you have to consider that said information is fundamentally transient. It is basically only notes for the developer that is going to implement the story.
Citing the agile manifesto

Working software over comprehensive documentation

and

Working software is the primary measure of progress.

In other words, ultimately the requirements are documented in working software. This is to answer to the first part of your question.
In the second part, you mention, basically, documenting an existing system. In that case, I am not sure what the value of doing so is (I don't doubt that it is valuable, but I am not sure on how you plan to use it).
In any case: ask your team and let them self-organize. Do they want to store this kind of information in a wiki? A google doc? Let them choose.
From the point of view of agile, there is no process for this.
This also applies to any documentation you need to produce as part of the deliverable. In one team I worked in, we had a documentation person preparing docs. In another, we used Sharepoint, in another - another wiki. A few years back, all documentation was delivered as MS word documents or in docbook format. It depends on your circumstances.
Defining what constitutes a deliverable is the purpose of a "definition of done" meeting. In there you can decide, if necessary, where the documentation is to be presented.

A: 1.For example if you use Team Foundation Server (Or Service Cloud version, free for < 5 user), you can store historical discuss about user story (Portal Team Web Access)
2.In agile for example we use User Story in order to specify behavior, but user story can be limited to defnie behavior , so you can also use Use Case in order define your functional need.
You can specify with use case on Scrum, it's not error.


text:
Q: Cuando pongo mi metodo a init components me sale error "AWT-EventQueue-0"java.lang.IllegalArgumentException Mi metodo lo que hace es pasar los datos de una tabla de otro frame a la tabla que esta en este frame , pero al correrlo me sale dicho error anteriormente mencionado ,quisiera saber como corregir el problema , lo que quiero es que cuando se ingrese al frame donde se pasen los datos de la tabla ,la tabla ya aparezca con los datos sin tener que usar botones

public class frmRegistroAdmin extends javax.swing.JFrame {
public frmRegistroAdmin() {
initComponents();
pasaTabla1();
}
public void pasaTabla1(){ jTablaMama.setModel(frmRegistro.Mama); }
public void pasaTabla2(){ jTablaMedicamentos.setModel(frmRegistro.Medicamentos); }
public void pasaTabla3(){ jTablaVitaminas.setModel(frmRegistro.Vitaminas); }
public void pasaTabla4(){ jtablaProductosMedicos.setModel(frmRegistro.ProductosMedicos); } public void pasaTabla5(){ jTablaCuidadoP.setModel(frmRegistro.CuidadoPersonal);}```


text:
Q: angularjs bootstrap typeahead return child My input binds to object line.product however typeahead is returning the list of pairs of products and supplier. The current ps.product as ps.product.code for ps in getProductSupplierRefList($viewValue)  does not return the expected product.

<input ng-model="line.product"
                               class=" form-control"
                               typeahead="ps.product as ps.product.code for ps in getProductSupplierRefList($viewValue)"
                               typeahead-loading="isLoading"
                               typeahead-on-select="productSupplierSelected($item, line)"
                               typeahead-template-url="productSupplierRefList.html"/>

getProductSupplierRefList calls webapi and return a list of ProductSupplierRefModel:
public class ProductSupplierRefModel
{

    public ProductRefModel Product { get; set; }

    public SupplierRefModel Supplier { get; set; }

}

The product code is expected in text control:

Any suggestion pls?

A: use typeahead-input-formatter to show the code. looks like ps.product as ps.product.code is not working???
<input ng-model="line.product"
                               type="text"
                               class=" form-control"
                               ng-keyup="getProductSupplierRefList($event)"
                               typeahead="ps.product as ps.product.code for ps in filterProductSuppliers"
                               typeahead-loading="isLoading"
                               typeahead-input-formatter="formatProduct($model)"
                               typeahead-wait-ms=500
                               typeahead-on-select="productSupplierSelected($item, line)"
                               typeahead-template-url="productSupplierRefList.html" />

where the formatter is:
$scope.formatProduct=function(model) {
        return model ? model.code : '';
    }

the product code now appears as expected:

A: Don't use function in typehead. Also be careful about the model properties camel case.
<input ng-model="line.product"
                           class=" form-control"
                           ng-keyup="getProductSupplierRefList($event)"
                           typeahead="ps.Product as ps.Product.Code for ps in productOptions"
                           typeahead-loading="isLoading"
                           typeahead-on-select="productSupplierSelected($item, line)"
                           typeahead-template-url="productSupplierRefList.html"/>

 $scope.productOptions = [];
$scope.getProductSupplierRefList = function(evt){
       var value = angular.element(evt.target).val();
       $http.get('url/' + value).then(funtion(response){
             $scope.productOptions = response.data;
        })
}
//test ps.Product.Code with _tojson(ps.Product.Code)
$scope._tojson= function(obj){
       return angular.toJson(obj);
}


text:
Q: change position to get graph and equation at the same level - RMarkdown / .tex I am creating a presentation in RMarkdown and in the slide below I want to put the graph on the left (with title above "Graph") and the couple of equations on the right, not below (with titte "Equations") - how to do this? Re the couple of questions, M: should appear first in the middle, and then the 4 equations.
Here is the slide with current output:

Here is the code in RMarkdown for that specific slide:
---
title: title

author: name

date: "`r format(Sys.time(), '%d %B %Y')`"

output:
  beamer_presentation:
    theme: Szeged
    slide_level: 2
    includes:
      in_header: header.tex
    keep_tex: true

linkcolor: false
---

## Model

\small
\justify
A line of text goes here:

\begin{tikzpicture}[>=triangle 45, font=\footnotesize]
\node[fill,circle,inner sep=0pt,minimum size=5pt,label={above:{T}}] (T) at (0,0) {};
\node[fill,circle,inner sep=0pt,minimum size=5pt,label={above:{Y}}] (Y) at (4,0) {};
\node[fill,circle,inner sep=0pt,minimum size=5pt,label={below:{X}}] (X) at (2,1) {};
\node[fill,circle,inner sep=0pt,minimum size=5pt,label={above:{W}}] (W) at (0,1.5) {};
\node[fill,circle,inner sep=0pt,minimum size=5pt,label={below:{$U_T$}}] (UT) at (0,-1) {};
\node[fill,circle,inner sep=0pt,minimum size=5pt,label={below:{$U_Y$}}] (UY) at (4,-1) {};
\node[fill,circle,inner sep=0pt,minimum size=5pt,label={above:{$U_X$}}] (UX) at (2,2) {};
\node[fill,circle,inner sep=0pt,minimum size=5pt,label={below:{$U_W$}}] (UW) at (-1,1.5) {};
\draw[->,shorten >= 1pt] (X)--(T);
\draw[->,shorten >= 1pt] (X)--(Y);
\draw[->,shorten >= 1pt] (W)--(X);
\draw[->,shorten >= 1pt] (UT)--(T);
\draw[->,shorten >= 1pt] (UY)--(Y);
\draw[->,shorten >= 1pt] (UX)--(X);
\draw[->,shorten >= 1pt] (UW)--(W);
\end{tikzpicture}

$M:$
$W := f_W (\epsilon_W)$
$X := f_X (W, \epsilon_X)$
$T := f_T (X, \epsilon_T)$
$Y := f_Y (X, \epsilon_Y)$

\small
\justify
A final line of text here.

Here is the code for the header.tex:
\definecolor{mycolorlightblue}{RGB}{103,153,200}
\definecolor{mycolordarkblue}{RGB}{0,70,127}
% add packages
\usepackage{tikz}
\usetikzlibrary{arrows}
\usepackage{tcolorbox}
\usepackage{ragged2e}
% remove 2nd section from header
\makeatletter
\beamer@theme@subsectionfalse
\makeatother
% change colour of lines
\setbeamercolor{separation line}{bg=mycolorlightblue}
% text title
\setbeamercolor{title}{fg=mycolordarkblue}
\setbeamercolor{frametitle}{fg=mycolordarkblue}
% text colour
\setbeamercolor{frametitle}{fg=mycolordarkblue}
% item colour
\setbeamercolor{structure}{fg=mycolordarkblue}
% no header or footer on first page
\thispagestyle{empty}
% remove title slides at beginning of sections
\AtBeginSection{}
% add page counter to the footer
\setbeamertemplate{footline}[frame number]
% logo of my university
\titlegraphic{%
  \begin{picture}(0,0)
    \put(155,0){\makebox(0,0)[rt]{\includegraphics[]{ALL-ICONS.png}}}
  \end{picture}}

A: As you are not using anything markdown specific in your columns, you can use the beamer columns environment:
---
title: title

author: name

date: "`r format(Sys.time(), '%d %B %Y')`"

output:
  beamer_presentation:
    theme: Szeged
    slide_level: 2
    includes:
      in_header: header.tex
    keep_tex: true

linkcolor: false
---

## Model

\small
\justifying
A line of text goes here:

\begin{columns}[T,onlytextwidth]
\begin{column}{.45\textwidth}
\begin{tikzpicture}[>=triangle 45, font=\footnotesize]
\node[fill,circle,inner sep=0pt,minimum size=5pt,label={above:{T}}] (T) at (0,0) {};
\node[fill,circle,inner sep=0pt,minimum size=5pt,label={above:{Y}}] (Y) at (4,0) {};
\node[fill,circle,inner sep=0pt,minimum size=5pt,label={below:{X}}] (X) at (2,1) {};
\node[fill,circle,inner sep=0pt,minimum size=5pt,label={above:{W}}] (W) at (0,1.5) {};
\node[fill,circle,inner sep=0pt,minimum size=5pt,label={below:{$U_T$}}] (UT) at (0,-1) {};
\node[fill,circle,inner sep=0pt,minimum size=5pt,label={below:{$U_Y$}}] (UY) at (4,-1) {};
\node[fill,circle,inner sep=0pt,minimum size=5pt,label={above:{$U_X$}}] (UX) at (2,2) {};
\node[fill,circle,inner sep=0pt,minimum size=5pt,label={below:{$U_W$}}] (UW) at (-1,1.5) {};
\draw[->,shorten >= 1pt] (X)--(T);
\draw[->,shorten >= 1pt] (X)--(Y);
\draw[->,shorten >= 1pt] (W)--(X);
\draw[->,shorten >= 1pt] (UT)--(T);
\draw[->,shorten >= 1pt] (UY)--(Y);
\draw[->,shorten >= 1pt] (UX)--(X);
\draw[->,shorten >= 1pt] (UW)--(W);
\end{tikzpicture}
\end{column}
\begin{column}{.45\textwidth}
$M:$
$W := f_W (\epsilon_W)$
$X := f_X (W, \epsilon_X)$
$T := f_T (X, \epsilon_T)$
$Y := f_Y (X, \epsilon_Y)$
\end{column}
\end{columns}

\small
\justifying
A final line of text here.


text:
Q: incorrect borders in Smart Form Template

I don't have an upper frame and  also ı have a 2 border in the right frame.
You can see more clear in the second screenshot.
I tried Select Pattern -> Displayed Framed Patterns but didn't work


text:
Q: R if ggplot not last in function, it won't plot I discovered that if ggplot is the last thing in a function, then calling the function will result in ggplot creating a plot as expected.
But if ggplot is not the last thing in a function -- say it is followed by an assignment (like x <- t) or a return statement (like return(x)) then ggplot will not create a plot.
What is the work around for this?
P.S. please throw in a comment explaining how to create an inline grey background used to indicate code :-)

A: Use plot for your ggplot object.
func1 <- function() {
  require(ggplot2)
  ggplot(mtcars, aes(mpg, wt)) + geom_point()
}

func1()  # this creates plot

func2 <- function() {
  require(ggplot2)
  ggplot(mtcars, aes(mpg, wt)) + geom_point()
  cat("hey\n")
}

func2()  # this does not create plot

func3 <- function() {
  require(ggplot2)
  plot(ggplot(mtcars, aes(mpg, wt)) + geom_point())
  cat("hey\n")
}

func3()  # use plot to make sure your plot is displayed

By the way, func1 creates plot not because ggplot is the last thing to do in the function.  It creates plot because the function returns the ggplot object and the code func1() invokes the print method of the object.
To see this, If you do a <- func1(), then the plot is not created, but stored in the a variable.
Note: You can use print insted.  print and plot are equivalent for the ggplot object.


text:
Q: subseting in R with for-loop I'm facing some troubles trying to subset data with some criteria. Please, if I could get some help would be wonderful.
Here is my problem....
I have a data frame with variables from X1 to X9. Data stored in this variables are double. I need a for-loop to look through this variables and return the lines that meet the criteria....let's say:
look through the variables from X1 to X9 and
return data where (X1,X2,X3)==(5.2,6.3,7.1) for instance.
Can someone help me?
Thanks.
Sorry, I did not make my self very clear.
As I have variables from X1 to X9 and the values there I'm filtering can occur in any variable, I can find the rows with the code bellow.
But I wouldn't like to perform this task manually replacing any variable combination to extract. That's why I thougth in a for loop to do this but couldn't acomplish. Thanks.
vars <- c("X1", "X2","X3") cond <- c(5.2,6.3, 7.1) databas %>% filter( .data[[vars[[1]]]] == cond[[1]], .data[[vars[[2]]]] == cond[[2]], .data[[vars[[3]]]] == cond[[3]] )

A: The easiest way to do this is to transpose your columns first so that your dataframe is long instead of wide. You can do this by using the tidyr::gather function. After that you can filter your dataframe. You dont necessarily need a loop.
df_filtered <- tidyr::gather(your_df, value = Value, key = ColumnNames,
               dplyr::starts_with('X')) %>%
               dplyr::filter( ColumnNames == "X1" & Value == 5.2 |
                              ColumnNames == "X2" & Value == 6.3 |
                              ColumnNames == "X3" & Value == 7.1 )


text:
Q: Linq with safe cast and null verification Given the code:
from i in this.GridViewFoo.SelectedItems
select new EmployeeEntity
{
    EmployeeID = (i as EmployeeDto).EmployeeID,
    Email = this.GetAllEmail((i as EmployeeDto).Email, (i as EmployeeDto).SecondaryEmails),
    EmployeeNumber = (i as EmployeeDto).EmployeeNumber,
    FirstName = (i as EmployeeDto).FirstName,
    LastName = (i as EmployeeDto).LastName
}

After the safe cast (i as EmployeeDto) may I receive a NullReferenceException. How can I ensure and safety of the code and not overload him with a lot of null checks?
Overview of solutions:
I did some tests to assert if the solutions are working. Both are working well and bring the same result, you can check HERE. After that I did some performance tests with OfTypeSolution and letSolution.
As OfType solution have better times in average, this will be the answer!

A: from si in this.GridViewFoo.SelectedItems
let i = si as EmployeeDto
where i != null
select new EmployeeEntity
{
    EmployeeID = i.EmployeeID,
    Email = this.GetAllEmail(i.Email, i.SecondaryEmails),
    EmployeeNumber = i.EmployeeNumber,
    FirstName = i.FirstName,
    LastName = i.LastName
}

A: You can use OfType before the Select:
from i in this.GridViewFoo.SelectedItems.OfType<EmployeeDto>()
select new EmployeeEntity
{
    EmployeeID = i.EmployeeID,
    Email = this.GetAllEmail(i.Email, i.SecondaryEmails),
    EmployeeNumber = i.EmployeeNumber,
    FirstName = i.FirstName,
    LastName = i.LastName
}

it will provide you only with the EmployeeDto type items from the SelectedItems so there is no need to cast and null checking.


text:
Q: can not access a member of class org.springframework.aop.TruePointcut with modifiers public I am developing a Spring application using Struts and the Struts JSON plugin. When I run the application it gives the following error (in Firebug):
org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: java.lang.IllegalAccessException: Class org.apache.struts2.json.JSONWriter can not access a member of class org.springframework.aop.TruePointcut with modifiers public

This is full stack trace:
org.apache.struts2.json.JSONException:
org.apache.struts2.json.JSONException:
org.apache.struts2.json.JSONException:
org.apache.struts2.json.JSONException:
java.lang.IllegalAccessException: Class
org.apache.struts2.json.JSONWriter can not access a member of class
org.springframework.aop.TruePointcut with modifiers "public"
    org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:238)
    org.apache.struts2.json.JSONWriter.processCustom(JSONWriter.java:171)
    org.apache.struts2.json.JSONWriter.process(JSONWriter.java:161)
    org.apache.struts2.json.JSONWriter.value(JSONWriter.java:127)
    org.apache.struts2.json.JSONWriter.write(JSONWriter.java:95)
    org.apache.struts2.json.JSONUtil.serialize(JSONUtil.java:116)
    org.apache.struts2.json.JSONResult.createJSONString(JSONResult.java:196)
    org.apache.struts2.json.JSONResult.execute(JSONResult.java:170)
    com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:374)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:278)
    org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
    org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:211)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:211)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:90)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:192)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:511)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:432)

Root cause:
org.apache.struts2.json.JSONException:
org.apache.struts2.json.JSONException:
org.apache.struts2.json.JSONException:
java.lang.IllegalAccessException: Class
org.apache.struts2.json.JSONWriter can not access a member of class
org.springframework.aop.TruePointcut with modifiers "public"
    org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:238)
    org.apache.struts2.json.JSONWriter.processCustom(JSONWriter.java:171)
    org.apache.struts2.json.JSONWriter.process(JSONWriter.java:161)
    org.apache.struts2.json.JSONWriter.value(JSONWriter.java:127)
    org.apache.struts2.json.JSONWriter.add(JSONWriter.java:363)
    org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:223)
    org.apache.struts2.json.JSONWriter.processCustom(JSONWriter.java:171)
    org.apache.struts2.json.JSONWriter.process(JSONWriter.java:161)
    org.apache.struts2.json.JSONWriter.value(JSONWriter.java:127)
    org.apache.struts2.json.JSONWriter.write(JSONWriter.java:95)
    org.apache.struts2.json.JSONUtil.serialize(JSONUtil.java:116)
    org.apache.struts2.json.JSONResult.createJSONString(JSONResult.java:196)
    org.apache.struts2.json.JSONResult.execute(JSONResult.java:170)
    com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:374)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:278)
    org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
    org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:211)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:211)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:90)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249

A: This class is not public itself. It is package protected (see here). You have to call setAccessible(true) before access its member exactly as when you access private or protected member.
EDIT.
Unfortunately you have not provided full stack trace. If this exception is result of your activity (I mean you try to access member of Spring class yourself) the solution is above. If however this happened as result of frameworks collision please send more details. Probably your versions of Struts and Spring are not compatible or some additional configuration is required.

A: In my case I was trying to access public constructor of a non public class.
class MyClass {
  public MyClass() {}
}

//...
MyClass c = JsonIterator.deserialize(bytes, MyClass.class)

Throws:
ReflectionMapDecoder can not access a member of class MyClass with modifiers "public"
Added public and it works.
public class MyClass {
  public MyClass() {}
}

HTH

A: For me that message meant I was calling
instance.getClass().getMethod("methodName")
but for some reason because it was actually defined in a parent class (@Override) this worked instead:
instance.getClass().getSuperClass().getMethod("methodName")
ref: How to call a superclass method using Java reflection


text:
Q: Can pubnub be integrated with rails devise for authentication Hi I am wondering if it is possible to generate authentication from devise and log user in their chat session using devise gem?

A: You can generate unique access key for user while he's registering / logging in your system. This key can be used as auth_key in Pubnub Access Manager so you can grant proper rights for given user.


text:
Q: coffeescript inside php file Is it possible to use coffeescript inside .php file, for example :

      <title> use coffeescript inside php file

how to use coffeescript

<?php echo $lorem ?>

If I want to use coffeescript in my php file what should I do to make it work?

A: I see no reason why not.
https://github.com/alxlit/coffeescript-php
Load your coffee in a var, compile it, and stick the resulting JS variable between the


text:
Q: Oracle Client Blob 10K Limitation with NHibernate and Mono? Some details off hand:
NHibernate : 2.1.2.4000
Oracle Instant client : x64 11.2.0.2.0
Mono : Mono JIT compiler version 2.10.2

I'm currently struggling a bit with Oracle and blobs whereby only 10K of the blob is inserted into the database. While this does work on Windows, there seems to be something different on Linux. Looking at the sql, every thing seems fine. Here is the truncated sql statement.
INSERT INTO Voters (Photo) VALUES (:p1);:p1 = 0x424DF627090000000000360000002800000090....

The hibernate mapping look like follows

and the class as follows
public partial class Voter : BusinessBase<long>
{
    #region Declarations
    private byte[] _photo = null;
    #endregion

    public virtual byte[] Photo
    {
        get { return _photo; }
        set { _photo = value; }
    }
}

The code where the voter object is saved look as follows
Voter entityVoter = Voter.copyFrom(record.TRANSACTION);
IVoterManager managerVoter = ManagerFactory.Instace.GetVoterManager(managerBulkImport.Session);
managerVoter.SaveOrUpdate(entityVoter);
File.WriteAllBytes("/home/user/voter" + entityVoter.Id + ".bmp", entityVoter.Photo);

And the image that's written to disk after the object has been save is also correct which makes me think that the problem might be with the oracle client? And as I've said, this code works on windows, except for the paths naturally.
Any help would be greatly appreciated!

A: The Mono Oracle provider is, unfortunately, more or less abandoned right now (just as the Microsoft Oracle provider whose API Mono was tracking). Since you are already paying large amounts of money for the database engine, I'd suggest spending a little bit more and getting a commercially supported Oracle ADO.Net provider. dotConnect for Oracle officially supports Mono (and I had very good experience with it), and DataDirect ADO.NET Data Provider for Oracle is 100% managed code, so it should - in theory - work with Mono as well.


text:
Q: Does the series $\sum_{n=1}^{\infty} \frac{\sqrt{n+1}-\sqrt{n}}{n}$ converge? Consider the series $$\sum_{n=1}^{\infty} \frac{\sqrt{n+1}-\sqrt{n}}{n}$$
Does this series converge or diverge?
I tried all the tests like ratio test, Raabe's test, logarithmic test, comparison test but in vain. In ratio test I got the limit as $1$, so can't do anything with that. Can anybody give some hints?
Thank you!

A: Hint: Write $$\frac{\sqrt{n+1}-\sqrt{n}}{n}=\frac{1}{n(\sqrt{n+1}+\sqrt{n})}$$

A:
Can anybody give some hints?

Hint
$$\frac{\sqrt{n+1}-\sqrt{n}}{n}\color{blue}{\frac{\sqrt{n+1}+\sqrt{n}}{\sqrt{n+1}+\sqrt{n}}}=\frac{1}{n\left(\sqrt{n+1}+\sqrt{n}\right)} \le \frac{1}{2n\sqrt{n}}$$


text:
Q: How to set BackGroundImage to Crystal Reports? I am using Crystal Reports, i want to set a background image to my report and i am aware of that and i set it by using OVERLAY option on section expert. But it comes like this

how do i get the background image for the Next items. All the matter is in DETAIL Section the image is in Page Header Section. how can i do this. Can anybody help me on this.
the above one is a A4 sheet in one page it prints three records. the image is coming for one record only. it is not coming for remaining records

A: hi you can do this thing by inserting GROUP HEADER SECTION for the Field Name then it works.

A: Just Insert Picture.
Crystal Report ----> Right Click -----> Insert Picture


text:
Q: Website source control and big setup binaries Many times website developers need to handle the download of heavy *.exe or *.msi setup files from their website. Today this involves complex hotlinking protection and multiple binaries version management.
The question is: does it worth to include these heavy binaries (in our case ~300MB) to website source control? Is there any workaround to fully test the download locally without including these file - that will never change - to Team Foundation Server source control?

A: if the binaries are external you have two options:
option 1: I prefer to include them in your solution.
option 2: you can create a team project called "Common Binaries" and make it a shared resource of all common binaries.


text:
Q: Nest can't resolve dependencies of the MailerService (?) I'm trying to configure this module.
The full error message reads as follows:
Nest can't resolve dependencies of the MailerService (?). Please make sure that the argument MAILER_OPTIONS at index [0] is available in the AppModule context.
I keep getting this error out of nowhere, what MAILER_OPTIONS? Where are those options? Nothing is said in the documentation in this respect. Absolutely no idea what's going on.
Here is my AppModule:
@Module({
  imports: [
    MailerModule.forRoot({
      defaults: {
        from: '"No Reply" <noreply@example.com>',
      },
      template: {
        dir: path.join(process.env.PWD, 'templates/pages'),
        adapter: new HandlebarsAdapter(),
        options: {
          strict: true,
        },
      },
      options: {
        partials: {
          dir: path.join(process.env.PWD, 'templates/partials'),
          options: {
            strict: true,
          },
        },
      },
    }),
  ],
  controllers: [AppController],
  providers: [
    AppService,
    MailerService,
  ],
})
export class AppModule {}

Any ideas?
Here is the service I'm using:
@Injectable()
export class AppService {
  constructor(
    private readonly mailerService: MailerService,
  ) {}

  public async sendEmail(): Promise<any> {
    const mailDetail: ISendMailOptions = {
      to: 'gutgesagt@yahoo.co.uk',
      from: 'noreply@nestjs.com',
      subject: 'testing Nest MailerModule',
      text: 'test test?!',
      html: '<b>Yahooooo</b>',
    };

    return this.mailerService.sendMail(mailDetail);
  }
}

A: You have to remove the imported MailerService from the providers array of your AppModule. Only declare providers that are part of the module itself; you would never declare an imported provider (service).
  providers: [
    AppService,
  ],

A: If you encountered the same error on unit test, maybe you have defined MailerModule in AppModule instead of a separate module, it will make unit test fails because you normally don't import the whole AppModule in unit test. Make sure you defined all the MailerModule on a separate module, like MailModule, and import this module in the AppModule.
@Module({
  imports: [
    EmailModule
  ],
  controllers: [AppController],
  providers: [
    AppService,
  ],
})
export class AppModule {}

and
imports...
@Module({
  imports: [
    ConfigModule,
    MailerModule.forRoot({
      defaults: {
        from: '"No Reply" <noreply@example.com>',
      },
      template: {
        dir: path.join(process.env.PWD, 'templates/pages'),
        adapter: new HandlebarsAdapter(),
        options: {
          strict: true,
        },
      },
      options: {
        partials: {
          dir: path.join(process.env.PWD, 'templates/partials'),
          options: {
            strict: true,
          },
        },
      },
    }),
  ],
  exports: [NestMailerModule],
})
export class EmailModule {}

Then also import the module to your RootTestModule
const module: TestingModule = await Test.createTestingModule({
      controllers: [...],
      providers: [...],
      imports: [EmailModule],
    }).compile();


text:
Q: Spring security substitute for Node.js Is there a substitute for spring security in Node.js. I know of express and passport, but passport provides authentication only. It does not feature "forgot password", "reset password" or crud operations for User and Role.
In other words, passport lacks of a number of commonly used features that are provided by spring security. Is there any Node.js library that provides these features.

A: I know it's already mentioned in the question but for anyone else brand new to Node coming here from google and skipping right to the answers like I did:
http://www.passportjs.org
Looks like the most widely used free library that is somewhat comparable to Spring Security, although as the original question points out it is only focused on authentication so it doesn't cover every feature Spring Security has (like role based authorization).

A: https://auth0.com
https://stormpath.com
and tons of others. Just google "User Managment" node.js
Or at the end of the day write you own. Writing user management is sails takes about an hour and they have integration with things like Mandril for sending forgotten notices.

A: Although spring security is one of the bests open source security frameworks, the features: "forgot password" and "reset password" aren't implemented by default. You will need to create your views pages and controllers for it. The default User and Role are very basic models of security that are recommended just for a very basic web apps. In most cases you will need to save and manage it in your database and customize all features for reset and forgot password. It can become very complex as you customize your security rules.
For node there are so many options out there, I agree with @KPD the most equivalent of SpringSecurity is passportjs (18.7k stars on github), although it is much simpler than SpringSecurity, sometimes the secret to success lies in simplicity.


text:
Q: how child thread can notify parent thread to terminate all the other child thread java my problem is following
a parent thread create 5 child thread and all the child thread start finding result and the one child thread get the result it have to notify the parent thread that it got the result and terminate all the other child thread

A: That's not a sane way to do it. Just code the child threads to stop doing work that no longer needs to be done. Any time you catch yourself asking "How can I push my code around around from the outside to make it do with I want?", stop and correct yourself. The right question is, "How can I write my code to do what I actually want it to do in the first place so that I don't have to push it around from the outside?"

A: Set the children to update a field in the parent if it isn't null. have the children occasionally check if the field is null or not. if it isn't, they should stop.
Does that work?

A: I feel it would be perfectly acceptable for termination of the other child threads be performed by the child thread. Especially if the child threads are using blocking methods. You just need a parent stop method accessable by the children.
Something like:
public interface Stopable {
  public void stop ();
}

public class Child
    extends Thread {
  final Stopable parent;
  boolean foundAnswer = false;

  Child ( Stopable parent ) {
    this.parent = parent;
  }

  public void run () {
    try {
      while ( !isInterrupted() ) {
        // Do some work.
        work();

        if ( foundAnswer ) {
          // Stop everyone.
          parent.stop();
        }
      }
    } catch ( InterruptedException ie ) {
      // Just exit when interrupted.
    }
  }

  private void work () throws InterruptedException {
    while ( !foundAnswer ) {
      // Do some work.

      // Should we stop now?
      checkForInterrupt ();
    }
  }

  private void checkForInterrupt () throws InterruptedException {
    if ( isInterrupted() ) {
      throw new InterruptedException();
    }
  }

}

public class Mainthread
    implements Stopable {
  ArrayList<Child> children = new ArrayList<Child> ();

  public void go () {
    // Spawn a number of child threads.
    for ( int i = 0; i < 5; i++ ) {
      Child newChild = new Child( this );
      children.add( newChild );
      newChild.start();
    }
  }

  public void stop () {
    // Interrupt/kill all child threads.
    for ( Child c : children ) {
      c.interrupt();
    }
  }
}


text:
Q: cascading relationships in icCube Is it possible to manage a cascading relationship in icCube? For example, if I have the following 3 tables:
(1) NameID, FuelID
(2) FuelID, ScheduleID
(3) ScheduleID, DateTime, Value
Can I tie the NameID from table (1) to Value in table (3)

A: You can do this using a Javascript View. You can check the documentation here how to do this, the idea is that the 'main' table is the big one and the small ones, that should behave as lookup tables, are the 'cached' tables.
hope it helps


text:
Q: Close jQueryUI Dialog from event of ajax loaded content element I load content with .load() passing url.
Inside of the content that is returned and loaded sucessfully into jq ui dialog, is simple link with id cancel123.
I am just trying to close this jqueryUiDialog w ID testDialog from click on the link.
I cannot figure out what im missing, and tried to do it in 48 different ways. Please help
 function InitializeDialog($element, title, url) {

            $element.dialog({
                autoOpen: false,
                width: 500,
                resizable: true,
                draggable: true,
                title: title,
                model: true,
                show: 'slide',
                closeText: 'x',
                //dialogClass: 'alert',
                closeOnEscape: true,
                modal: true,
                open: function (event, ui) {
                    //Load the Partial View Here using Controller and Action
                    $element.load(url);
                    $("#cancel123").bind('click', function (event) {
                        $('#testDialog').dialog('close');
                        alert('close this');
                    });

                },

                close: function () {
                    $(this).dialog('close');
                }
            });

A: You can bind it to the document like this:
$(document).on("click", "#cancel123", function(event) {
    $('#testDialog').dialog('close');
    alert('close this');
});

Another way (I think its even better):
$element.load(url, function() {
    $("#cancel123").bind('click', function (event) {
        $('#testDialog').dialog('close');
        alert('close this');
    });
});


text:
Q: R package: underscores added to RcppExports.R when building I work from different computers on the same R package with Rstudio, but for some reason, whenever I build the package, some of the computers will modify the RcppExports.R and RcppExports.cpp files by adding underscore in front of some functions. For example, this can be found when looking at the dif between the files before and after compiling the package (first line is before, second is after):
    .Call('PkgName_FunctionName', PACKAGE = 'PkgName', arguments)
    .Call('_PkgName_FunctionName', PACKAGE = 'PkgName', arguments)

This bothers me because git sees this as a change.
My questions are:

*

*Why is the underscore included?

*What can I do to have compiling the package not modify any of the files?

A: Make sure you have the same (current) versions of Rcpp on both machines.  Then the RcppExports.{R,cpp} files will be identical.
The change was a requirement from R upstream (around R 3.4.0) and we needed to adjust.
Also note that you probably want registration=TRUE in your NAMESPACE file in which case the form becomes
.Call(`_PkgName_FunctionName`, arguments)


text:
Q: Anyway to reduce bundle size of App in my angular webpack app? I'm newer to this area and following up after getting some more information, Am I wrong in understanding this... but  it looks like my main is loading along with platform-browser-dynamic which bootstraps my App-Module.
Is there anyway to bring these bundles down or optimize them that I can look into?
Currently using webpack with Angular 6.


text:
Q: How can I disable diff in line separators in IntelliJ IDEA? I'm using Intellij IDEA 14 on Windows and Git as VCS on Unix server.
The line separator in Windows is CLRF (\r\n) and LF (\n) in Unix.
In Git, I'm using config --global core.autocrlf input. This will translate all CRLF's to LF's upon commit.
When I'm using "Reformat code" option on well-formatted file, IDEA marks files as changed and shows diff in line separators only.

How can I disable that in IDEA?

A: If you came to this thread like me seeking an answer as to why your unit test (JUnit) fails on comparing generated JSON (or any other structure that contains line separators) with one written by hand, you should replace \n by \r\n (for Windows) in your string. The instructions given above don't work for this case.

A: In the bottom right of your window, change [CRLF] to [LF]

A: I'm also developing on windows and Because our servers are powered by Linux and all the code has to base on Linux I have preferred to change all my files to LF instead of CRLF.
from git command line:
git config --global core.autocrlf false

i'm working with intellij idea so it's quite easy:

1)    File --> settings --> editor --> code style: (for any new file will
  be created)
a.    Scheme : default
b.    Line separator: unix and os x (\n)
2)    mark the root of the project --> file --> line separator --> LF
  unix and os x (\n) (for exist files)

Remark: you can also use apps like dos2unix.exe or some other scripts.
than I did using my command line: (you can do this also from the idea)
git commit -m "bla bla"
git add .
git push origin master

since then, I didn't got those warnings

A: select folder -> File -> File Properties -> Line Separator -> LF
All files will be markd as changed.
Make regular commit with line separator changes ounly.
It will fail but changed marks will disappear.
New files will inherit folder property.

A: In Intellij 17.3, you can select in the "Compare by" combobox in the compare window whether you want to compare 'Binary content' or 'Text'. In the second case CRLF and LF are not shown as "different".

A: Create parser.py in the same dir.
Change the name and run.
Enjoy))

with open('./file_to_fix.py', 'r') as f:
    a = f.read()

with open('./file_to_fix.py', 'w') as f:
    # for i in a.split('\r\n'):
    #     f.write(i)
    aa = a.replace('\r\n', '\n')
    f.write(aa)


text:
Q: Using InternetExplorer.Application object to check a checkbox on a webpage I would like to use...
Dim IE As Object

Set IE = CreateObject("InternetExplorer.Application")

With appropriate code to check a checkbox on a webpage

The HTML Code on the rendered page is...
<form class="form-inline" style="float:right">
    <div class="checkbox">
        <label style="padding-top: 1px">
            <input data-bind="checked: orderBook.showAll" style="top:2px"
             type="checkbox" /> Show All
        </label>
    </div>
</form>

I can't use getElementsByID() as I don't think it has one.
Any suggestions?

A: While your checkbox does not have an ID, it does have a Class. Without seeing more of the HTML code I cannot be entirely sure, but the following code should allow you to set your checkbox to a variable:
Option Explicit

Sub test

    Dim IE As Object
    Set IE = CreateObject("InternetExplorer.Application")

    ' Navigate to desired web page

    ' Code to ensure page is fully loaded

    Dim cBox As Object
    Set cBox = IE.document.getElementsByClassName("checkbox")(0)

End Sub

Then you can use cBox how you need to (possibly like cBox.Click or another method). Notice that I appended (0) to the end of that statement? That means you are assigning the first instance of that class to the variable. If this checkbox is the only object with the class name of checkbox, then this won't be an issue, but you may have to change this number if it's not.


text:
Q: Vector class type changes on editing JTable I have a JTable which has three columns:
String, PropertyItem (Custom class), String
PropertyItem is displayed as a String in the table but type is PropertyItem. Here is a sample row of table:
Value Mask | Format Constraints | Value Mask Rule Sub Type
The table's data is fetched using a Vector:
List<Vector> displayedData = table_propertyDetails.getDataMatrix();

and traversing the table data like this:
for(Vector row : displayedData) { ... }

Now, row.get(index) function is used to fetch the column data with typecasting to String for column 0 and 2. For PropertyItem column, it is done as (PropertyItem) row.get(index). So, far things are good and no problems appear in normal listing/fetching of rows.
Now, when this table's second column (PropertyItem) is edited, it turns into a String and (PropertyItem) row.get(index) returns in an error for that row:

java.lang.String cannot be cast to
  com.abc.xyz.model.PropertyItem

For all other rows in which data is not edited, this casting is done without any error but with the edited row, it results in this error.
Any idea what I can do here to convert the String back to PropertyItem at this time or before this time?

A: Seems, you use DefaultTableModel, in this case I recommend you to write your own  TableCellEditor for editing your custom column. In your implementation you can edit your object as you wish.

A: I tried to understand the explanation and writing answer WRT my past errors.
I think you need to review the TableModel of your JTable, which DataType you are setting while creating the JTable.
If you are using String for all three columns than change it to Object for second column.
Because you are adding a String in first and third column it will work, but you are adding Object of PropertyItem in second column and DataType of second column may be String this will be converted to String and get() method will return a String from table and that Casting error will occurs.
I hope, Changing the Type of second column in TableModel will solve the issue.
Example :
myTable.setModel(new javax.swing.table.DefaultTableModel(
    new Object [][] {
        {null, null, null},
        {null, null, null},
        {null, null, null},
        {null, null, null}
    },
    new String [] {
        "Column 1", "Column 2", "Column 3"
    }
    ) {
    Class[] types = new Class [] {
        java.lang.String.class, java.lang.Object.class, java.lang.String.class
    };

    public Class getColumnClass(int columnIndex) {
        return types [columnIndex];
    }
});


text:
Q: RMarkdown PDF Fatal error : Undefined control sequence (\grffile@filename). Possible Bad Character? I have written a R script to generate 2 RMarkdown PDF reports for a given dataset.
The script runs without error on my main Linux machine with Texlive. I adjusted it for my work laptop with Windows and MiKTeX and it runs perfectly.
However when I installed the program on my coworker's Windows machine (he is the one who needs to be generating the reports every two weeks) RMarkdown fails to compile the second report. The first report runs just fine.
The log file ends with
[5 <D:/Tower_Raw Data/QAQC Reports/HB1ts_RawQAQCReport_20200322_files/figure-la
tex/unnamed-chunk-33-1.pdf>]
! Undefined control sequence.
\grffile@filename ->D:\Tower
                             _Raw Data\QAQC Reports\HB 1ts_RawQAQCReport_202...
l.292 ...22_files/figure-latex/unnamed-chunk-38-1}
                                                   \end{center}
!  ==> Fatal error occurred, no output PDF file produced!

My first thought is that the "_" in the folder name "Tower_Raw Data" is a problem. Since the \grffile@filename line has unusual spacing around it. This doesn't seem to make sense though given that both reports are generated from the same data and written to the same folder with the first report compiling successfully.
Does anyone have a suggestion?
Here is the full log output if anyone is interested:
https://pastebin.com/gFpgyzEc


text:
Q: Time dependent parameter for heat equation :\begin{cases} u_{t}=ku_{xx} & (x, t) \in [0, \infty) \times (0, \infty) \\
u(x,0)=g(x) & IC \\ u(0,t)=0 & BC \end{cases}
What is the solution for $k$ as a function of $t$. I suspect it requires having to integrate $k(t)$ over the time to find the mean value

A: Of course use separation of variables:
Let $u(x,t)=X(x)T(t)$ ,
Then $X(x)T'(t)=k(t)X''(x)T(t)$
$\dfrac{T'(t)}{k(t)T(t)}=\dfrac{X''(x)}{X(x)}=-s^2$
$\begin{cases}\dfrac{T'(t)}{T(t)}=-s^2k(t)\\X''(x)+s^2X(x)=0\end{cases}$
$\begin{cases}T(t)=c_3(s)e^{-s^2\int_0^tk(r)~dr}\\X(x)=\begin{cases}c_1(s)\sin xs+c_2(s)\cos xs&\text{when}~s\neq0\\c_1x+c_2&\text{when}~s=0\end{cases}\end{cases}$
$\therefore u(x,t)=\int_0^\infty C_1(s)e^{-s^2\int_0^tk(r)~dr}\sin xs~ds+\int_0^\infty C_2(s)e^{-s^2\int_0^tk(r)~dr}\cos xs~ds$
$u(0,t)=0$ :
$\int_0^\infty C_2(s)e^{-s^2\int_0^tk(r)~dr}~ds=0$
$C_2(s)=0$
$\therefore u(x,t)=\int_0^\infty C_1(s)e^{-s^2\int_0^tk(r)~dr}\sin xs~ds$
$u(x,0)=g(x)$ :
$\int_0^\infty C_1(s)\sin xs~ds=g(x)$
$\mathcal{F}_{s,s\to x}\{C_1(s)\}=g(x)$
$C_1(s)=\mathcal{F}^{-1}_{s,x\to s}\{g(x)\}$
$\therefore u(x,t)=\int_0^\infty\mathcal{F}^{-1}_{s,x\to s}\{g(x)\}e^{-s^2\int_0^tk(r)~dr}\sin xs~ds$

A: By an odd extension $g(x):=-g(-x)$ for $x<0$, you can solve the heat equation on the whole real line (which I assume you know how to do?). Then restrict this solution to the half line.


text:
Q: ubuntu 14.04.3 bootloader cannot be installed at specified location [retina 15" Macbook Pro 2014, rEFInd, OS X, & Ubuntu 14.04.3]
Installing Ubuntu, I've chosen the 'Other' option from the template menu.  My partitions are setup as follows:
/dev/sda
  free space            0MB
  /dev/sda1    efi      209MB
  /dev/sda2    hfs+     299999MB
  /dev/sda3    hfs+     650MB
  free space            0MB
  /dev/sda4    ext4  /  183031MB
  free space            0MB
  /dev/sda5    swap     16384MB
  free space            2MB

When I click Install Now, I get a message box stating that I need to setup a separate partition for boot loader code and that the partition should be marked as Reserved BIOS boot area.  So I setup the last free space (2MB) as Reserved BIOS boot area and it became /dev/sda6.
For the Device for boot loader installation option, I specify /dev/sda6 andcontinue with Install Now and the installation progresses.  When the installation is about to finish, I'm getting an error message stating:
Executing 'grub-install /dev/sda6' failed.
This is a fatal error.
<OK>

Then, as per the title of this post, I get a message box that states that the boot loader cannot be installed at the specified location and I have three options:
1) Choose a different device
2) Continue without a bootloader
3) Cancel the installation
I've tried selecting another partition (/dev/sda4) but get the same error and I don't want to specify /dev/sda1-/dev/sda3 as they are hfs+ partitions and I don't want to corrupt my OS X install.
I've read the other questions here on the topic but they don't seem to apply to my case, the given answers explain the differences between BIOS and EFI and MBR and GPT, and neither have an accepted answer from the person who posted.
I don't understand why the Installer is forcing me to specify a Reserved BIOS boot area partition, then complains that it can't use it.
Any advice on what I should change about the way I've setup my partitions would be most welcome.

A: The message about the "reserved BIOS boot area" (what the rest of the world calls a BIOS Boot Partition) indicates that your installer has booted in BIOS/CSM/legacy mode. You might do better with an EFI-mode installation, although there's another way around this issue (see below). First, though, I strongly advise you to exercise caution. Installing a BIOS-mode boot loader to a partition that should not hold it can render all data on the partition inaccessible. If you're lucky, you might be able to recover files with advanced data-recovery tools, but you'll waste a lot of time (your own and others') because of a moment's impatience.
In an EFI-mode installation, the boot loader is stored as ordinary files in the EFI System Partition (ESP), which in your case is /dev/sda1. The Ubuntu installer doesn't actually ask where to install GRUB on such systems; it's smart enough to identify the ESP and install GRUB there. If you partition manually, though, the ESP must be appropriately flagged (as an "EFI boot partition" on older versions or as an ESP on newer versions). This should happen automatically, but you should not change that identification. Note that this will happen only if you boot the Ubuntu installer in EFI mode, which you apparently have not done. (The installer sets up a BIOS-mode boot loader if it's booted in BIOS mode and an EFI-mode boot loader if it's booted in EFI mode.)
Finally, to the other way around the issue: You said you're using my rEFInd boot manager. rEFInd doesn't need GRUB -- BIOS-mode or EFI-mode. If you've already installed rEFInd in OS X, and if your Ubuntu installation has completed except for the GRUB installation, you can boot to OS X and install an EFI filesystem driver for ext4fs. See the rEFInd driver documentation and the rEFInd page on booting Linux for lots more details. The mountesp script, which comes with rEFInd, should mount your ESP, enabling you to copy the ext4fs driver, which also comes with rEFInd, to the right location. Alternatively, you can re-run the refind-install script. This is overkill, but the script should detect that Ubuntu is now installed and set up the ext4fs driver automatically. Yet a third option is to use rEFInd on a CD-R or USB flash drive to boot to Ubuntu, then re-install rEFInd via the Debian package or PPA. In any event, once the ext4fs driver is installed, rEFInd should detect your Linux kernels and enable you to boot.


text:
Q: Not able to find "Emulate CSS media" in Google Chrome I'm trying to set the media query in chrome to go to print. I tried to follow this post - Using Chrome's Element Inspector in Print Preview Mode?
However, I can't find the Emulate CSS media option under overrides.

Has it been moved? Where should I look for it?
I tried in the Emulation in the console drawer. It's not in their either -

A: For emulating print CSS, it looks like this now, as of Chrome 49, April 2016.

A: They move it every so often. At the moment it's in the Rendering panel. To find it:

*

*Open the lower panel (press Esc while in the Developer Tools)

*Open the Rendering panel from the dropdown

*Select Emulate print media

A: It's under any of the tabs where you can open the console in the dev tools (pretty much all of them except for the Console tab). For example under Sources, go to the upper right hand of the tools and click the Show Console icon (the icon that looks like a greater than sign with three vertical bars). That should open the console and you should see the Emulation options.


text:
Q: How can I get index of elements which are not integer In the numpy array (data) below, how can I get index positions of the non-integer numbers such as 4.5 and 6.7?
import numpy as np
data = np.array([2.0, 3.0, 4.5, 6.7, 12.0],dtype=float)
print data

Since I am dealing with very large array, faster processing speed is to be considered.

A: For speed you should use np.where. Now one solution to find if an element is an integer is to compare it to its rounded value:
np.where(data != data.round())
(array([2, 3]),)

Another solution is to use nonzero:
(data - data.round()).nonzero()
(array([2, 3]),)

A: You can use a list comprehension combined with the is_integer() method.
float_data = np.array([i for i, v in enumerate(data) if v.is_integer()])

This list comprehension will add the index of each element to the array if the element is an integer and is effectively the same as the following code
float_data = []
for i, v in enumerate(data):
    if v.is_integer():
        float_data.append(i)


text:
Q: Downloading a file from AWS S3 (Amazon Web Services) using SAS and cURL Crossposted from communities.sas.com
Hello all, I'm trying to get SAS to call cURL, to download a file from AWS.
I'm currently getting a "AWS authentication requires a valid Date or x-amz-date header" error, but I have checked the date (Fri, 29 JAN 2016 14:47:15 GMT+1300) and it seems to be in the right format so I'm not sure what is happening. When I was testing yesterday with what I thought was the same code I got an error along the lines of "Problem with your signed signature".
After a good day of attempts I'm hoping someone else may have done something similar and can help. Here's my code I'm using currently. I will mention I'm not an AWS expert so it's possible I've messed something basic up but I haven't been able to figure it out yet.
* cludged from:
http://stackoverflow.com/questions/27658147/download-private-file-from-s3-using-bash
https://communities.sas.com/t5/Base-SAS-Programming/Using-sas-secure-to-generate-hmac-sha1-oauth-signature/td-p/169922 ;

%LET cUrl_exe = C:\Apps\cUrl\cUrl.exe ; * change if yours is in a different place ;
%LET s3Key=<access_key>;* change this line ;
%LET s3Secret=<secret_key>;* change this line ;
%LET out_file = <outfile_path>; * change this line ;
%LET file = test.txt ; * change this line ;
%LET bucket = <bucket name>; * change this line ;
%LET resource = "/&bucket./&file." ;
%PUT Resource = [&Resource.] ;
%LET contentType = 'text/html' ; * this may not matter? ;
*dateValue="`date +'%a, %d %b %Y %H:%M:%S %z'`" ;
PROC FORMAT ;
  PICTURE HTTPTime
    (DEFAULT = 29)
    OTHER = '%a, %0d %b %Y %0H:%0M:%0S'
    (DATATYPE = DATETIME) ;
RUN ;

DATA _NULL_ ;
  CALL SYMPUT("dateValue",  STRIP(PUT(DATETIME(), HTTPTime.)) || " GMT+1300") ; * SHOULD BE ABLE TO USE %Z TO GET UTC OFFSET NEED TO CHANGE TO +1200 WHEN NOT IN DST ;
RUN ;

%PUT dateValue = [&dateValue.] ;

DATA _NULL_ ;
  stringToSign = '"GET' || '0A'X ||
    '0A'X ||
/*    STRIP(SYMGET("contentType")) || '0A'X ||*/
    STRIP(SYMGET("dateValue")) || '0A'X ||
    STRIP(SYMGET("resource")) || '"'  ;
  PUT stringToSign= ;
  CALL SYMPUT("stringToSign", STRIP(TRANWRD(stringToSign, '"', '""'))) ;
RUN ;

proc groovy;
add sasjar="commons_codec" ; *version="1.7.0.0_SAS_20121211183158";*version may differ based on your installation.  Check your SAS Versioned Jar Repository;

submit "&s3secret." "&stringToSign.";
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import org.apache.commons.codec.binary.Base64
def base64hmacsha256(key, message) {
    mac = Mac.getInstance("HmacSHA256")
    mac.init(new SecretKeySpec(key.getBytes(), "HmacSHA256"))
    sha1_bytes = mac.doFinal(message.getBytes())
    base64 = new Base64()
    return new String(base64.encode(sha1_bytes))
}
exports.base64hmacsha256 = base64hmacsha256(args[0], args[1])
endsubmit;
quit;
%put &base64hmacsha256.;

DATA _NULL_ ;
  LENGTH cmd $1024 ;
  cmd = STRIP(SYMGET("cUrl_exe")) ||
    ' -U '||"<user:pass>"||' -x <proxy:port> -k'||' -o "' || STRIP(SYMGET("out_file")) ||
    '" -H "Host: ' || STRIP(SYMGET("bucket")) || '.s3.amazonaws.com' ||
/*    '" -H "Content-Type: ' || STRIP(SYMGET("contentType")) || */
    '" -H "Date: '||"'"|| STRIP(SYMGET("dateValue")) ||"'"||
    '" -H "Authorization: AWS ' || STRIP(SYMGET("s3Key")) || ':' || STRIP(SYMGET("base64hmacsha256")) ||
    '" https://' || STRIP(SYMGET("bucket")) || '.s3.amazonaws.com/' || STRIP(SYMGET("file")) ;

  RC = SYSTEM(cmd) ;
  PUT cmd= RC= ;
RUN ;

The output from this code looks like this:
cmd=C:\Apps\cUrl\cUrl.exe -U <user:pass> -x <proxy:port> -k -o "<outfile_path>" -H "Host: <bucket_name>.s3.amazonaws.com" -H "Date: 'Fri, 29 JAN 2016 14:47:15 GMT+1300'" -H "Authorization: AWS <access_key>:<signed_signature>" https://<bucket_name>.s3.amazonaws.com/test.txt

Cheers for any help!


text:
Q: Query string values with their open and close quotation marks using Caigen CSV reader Good day,
I have a java program which uses Caigen CSV JDBC driver to query a CSV file and return its contents. Unfortunately the string values are returned without their open and close quotation marks. Is there a way for Caigen to query a specific CSV column and return its contents with or without the quotation marks included.
Example
TABLE.CSV
ROW 1.   "APPLE",$1.40
ROW 2.   ORANGE,$1.30
ROW 3.   "LEMON",$1.50

SQL: Select COLUMN1 from TABLE1

Expected results:
ROW 1.   "APPLE"
ROW 2.    ORANGE
ROW 3.   "LEMON"

Edit:
     The purpose of getting the quotation marks is to see if the external program (which I have no control) generated the CSV correctly. Missing quotation marks means that the CSV is incorrect.

A: The quotes in a CSV file are part of the structure of the file and are not part of the field itself. So CAIGEN is correct in removing them, and normally you should not worry for that.
If you need them, that means that you do not them to be processed as the CSV quoting character. IMHO, that means that you should configure CAIGEN to use another character as quote. You should choose another character that will not appear in your file. Assuming that the single quote (') is an acceptable choice, just declare it in you connection string:
con = DriverManager.getConnection("jdbc:csv:[DatabasePath]?_CSV_Quoter='")

A: Quotes around fields in a CSV-file have a meaning and are not part of the field content. This is specified by RFC 4180:

*Each field may or may not be enclosed in double quotes (however some programs, such as Microsoft Excel, do not use double quotes at all). If fields are not enclosed with double quotes, then double quotes may not appear inside the fields. For example:
"aaa","bbb","ccc" CRLF
zzz,yyy,xxx
6. Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes. For example:
"aaa","b CRLF
bb","ccc" CRLF
zzz,yyy,xxx
7. If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double quote. For example:
"aaa","b""bb","ccc"

So, if you want quotes as part of the data the file must look this way:
ROW 1. """APPLE""",$1.40
ROW 2. ORANGE,$1.30
ROW 3. """LEMON""",$1.50

A possible problem is that not all implementations respect RFC 4180. I hope that Caigen does.


text:
Q: How do you get the map to Pan using ui-angiular? I'm using ui-angular but I'm I cant figure out how to get the map to panTo a new location. I understand how it would work it I was just using Leaflet.js but because this is a directive I don't understand what object I'm supposed to use to interactie with map on the page.
Here is my map directive
<leaflet id="owmMap" center="center" markers="markers" layers="layers"></leaflet>

 Here is my code so far.

  $scope.moveTo = function(obj){
        console.log(obj);

      //map.panTo((new L.LatLng(40.737, -73.923));); <--- This is what I need to replicate
 }

A: Okay, like most things the answer was buried in the documentation. For some reason there are actually 3 different sites for this plugin with different set of docs, but I found the answer on the git repo.
https://github.com/tombatossals/angular-leaflet-directive
If anyone else has this question.
There is a data object called "leafletData" that you can pass into your 'Controller' and use to access the map object directly on the page.
Here is some sample code:
 $scope.moveTo = function(obj){
      leafletData.getMap('myMap').then(function(map) {
         map.panTo({lat: obj.lat, lng: obj.lng});
       });
 }


text:
Q: ST3: New Build Systems / SideBarEnhancement: Keyboard shortcut that opens files to different browsers via localhost Using Sublime Text 3 on a mac. I'm currently learning d3.js and would like to be able to preview source codes on different browsers via the localhost, preferably, without using 3rd party browser plugins like Live Reload. It's not hardcore development so I don't really need to autoupdate to diff sized browsers.
What I'd like to do:

*

*Able to open files via localhost http://localhost:8888 NOT file:///Users/USERNAME/Desktop/...

*Have the option to open files on different browsers (Chrome, Firefox, Safari) by just typing a shortcut

I was able to do the following:

*

*set-up a local server via terminal, python -m SimpleHTTPServer 8888 &

*bind a keyboard shortcut to SidebarEnhancement's Open in Browser

*Use this shortcut to open file onto the localhost ie., http://localhost:8888/d3-book/chapter_04

*tried making New Build Systems for each browsers, but I can't seem to get it to open onto the localhost. It instead opens to file:///Users/USERNAME/Desktop/...
Is it possible to get SideBarEnhancements to have the option for:

*

*Open in Chrome + keyshortcut

*Open in Firefox  + keyshortcut

*Open in Safari  + keyshortcut?

OR
Have Build Systems for each browser that opens to the localhost ie., http://localhost:8888/d3-book/chapter_04?
Thanks in advance

A: I think your answer may using SideBarEnhancements "Open With" option as opposed to the "Open in Browser", which is going to load the system default (there may be an override, but I'm not aware of it).
You could look into an OS shortcut to switch default browsers as well.


text:
Q: MySQL: how to count 1 week from a certain date I have the following table:
create table my_table
(
 SubjectID int,
 Date Date,
 Test_Value int
);

insert into my_table(SubjectID, Date, Test_Value)
values
(1, '2014-01-01', 55),
(1, '2014-01-05', 170),
(1, '2014-01-30', 160),
(2, '2014-01-02', 175),
(2, '2014-01-15', 40),
(2, '2014-01-18', 30),
(2, '2014-01-20', 166),
(3, '2014-01-05', 100),
(3, '2014-01-07', 75),
(3, '2014-01-11', 180),
(3, '2014-01-21',90)

I am trying to identify SubjectIDs who had Test_Value >=160 and had 2 or more tests within 7 days from the time s/he scored 160. For example, SubjectID 1 does not meet this condition. When he scored 160 on '2014-1-30', this two prior tests were taken more than one week ago. SubjectID 2 satisfies this condition because he scored 166 on '2014-01-20,' the two prior tests were taken within a week. SubjectID 3 also meets the condition by scoring 180 on '2014-01-11' and having two prior tests within a week.
Just to clarify, the test scores taken twice or more prior to scoring 160 do not matters. They have to be within a week from the date when subjects score 160 in order to satisfy the condition.
So far, I have written this code:
set @test = 0, @id=0, @count=0;

select
 @count := if(SubjectID = @id, @count+1, 0) as count,
 @test :=  if(Test_Value >= 160, 1,  0 ) as Test_Index,
 @id := SubjectID as id
from my_table

I know this code does not give me the answer, but if I could incorporate relative time frame of one week into this code, the problem could be solved. I am not sure the code above is a good starting point. Could you add something to this code or write a completely different set of codes? Thank you for your help in advance.

A: I think this does what you want, without variables:
select s160.*
from my_table s160 join
     my_table sprev
     on s160.test_value >= 160 and
        s160.SubjectId = sprev.SubjectId and
        sprev.Date between s160.Date - interval 7 day and s160.Date
group by s160.SubjectId, s160.Date, s160.Test_Value
having count(*) >= 3;

The count(*) >= 3 is because the count includes the test with the higher score as well.  It would be helpful if this table had an actual id that was unique on all the rows.


text:
Q: How to play .wav files one at a time? I want to create a program that plays one certain .wav file when a certain button is pressed. For example, JButton b1, b2, b3 plays "Music1.wav" , "Music2.wav" , and "Music3.wav" respectively, but only one wav file can only be played at a time. This is what I did, which has problems with stopping the earlier clip and causing two or more wav files to play simultaneously.
...   //imports the important stuff
public class WAVButtons extends JFrame implements ActionListener
{
    private JButtons b1, b2, b3;
    private File[] sounds;

    public WAVButtons()
    {
         try
         {
               sounds = new File[]
                        {new File("Music1.wav"),
                         new File("Music2.wav"),
                         new File("Music3.wav")};
         }catch(Exception e)
         {
         }
         b1 = new JButton("play Music1");
         b2 = new JButton("play Music2");
         b3 = new JButton("play Music3");
         b1.addActionListener(this);
         b2.addActionListener(this);
         b3.addActionListener(this);
         ... //codes for GUI
    }

    public void actionPerformed(ActionEvent ae)
    {
         if(ae.getSource() == b1)
         {
              playMusic1(true);
              playMusic2(false);
              playMusic3(false);
         }
         else if(ae.getSource() == b2)
         {
              playMusic1(false);
              playMusic2(true);
              playMusic3(false);
         }
         else if(ae.getSource() == b3)
         {
              playMusic1(false);
              playMusic2(false);
              playMusic3(true);
         }
    }

    public void playMusic1(boolean action)
    {
        try
        {
            AudioInputStream stream = AudioSystem.getAudioInputStream(sounds[0]);
            AudioFormat format = stream.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);
            Clip clip = (Clip)AudioSystem.getLine(info);
            clip.open(stream);
            if(action)
            {
                clip.start();
                clip.loop(Clip.LOOP_CONTINUOUSLY);
            }
            else
                clip.stop();
        }catch (Exception e)
        {
        }
    }

    ... //playMusic2() and playMusic3() looks exactly the same as playMusic1(), except that the
        //parameter of AudioSystem.getAudioInputStream() is sounds[1] and sounds[2], respectively.
}

A: When you call playMusic1(true) followed by playMusic1(false), the second call is going to create a new instance of a clip and then stop the new instance. The first instance created by the first call is going to keep playing along. You should hang on to a reference to the clip so that it can be stopped. I've also taken the liberty of removing your duplicate code.
Clip clip;

public void actionPerformed(ActionEvent ae)
{
     if(ae.getSource() == b1)
     {
          playMusic(0);
     }
     else if(ae.getSource() == b2)
     {
          playMusic(1);
     }
     else if(ae.getSource() == b3)
     {
          playMusic(2);
     }
}

public void playMusic(int clipNum)
{
    try
    {
        if (clip != null)
            clip.stop();

        if (action)
        {
            AudioInputStream stream = AudioSystem.getAudioInputStream(sounds[clipNum]);
            AudioFormat format = stream.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);
            clip = (Clip)AudioSystem.getLine(info);
            clip.open(stream);
            clip.start();
            clip.loop(Clip.LOOP_CONTINUOUSLY);
        }
    }catch (Exception e)
    {
    }
}


text:
Q: Is it good practice to create convenience delegate methods? Suppose I have design like this:
class Corpus:
    def something1(self):
        pass
    def something2(self):
        pass
    def serialize_to_stream(self, stream):
        _CorpusJsonSerializer().serialize(self, stream)

class _CorpusJsonSerializer:
    def serialize(self, corpus, stream):
        .
        .
        .
    .
    .
    .

I think that the serialization process should be in a separate class for various reasons. That makes the method serialize_to_stream in Corpus unnecessary. I would however like to have it there because I think it makes it easier for the users of the Corpus, because they do not have to know anything about another class CorpusJsonSerializer.
Do you think it is reasonable? Or shall I just expose the CorpusJsonSerializer and let the user do the work?

A: This is a trade-off between ease-of-use and decoupling.
Having a serialize-method part of your Corpus class may make it easier to use, but this way your Corpus class depends on _CorpusJsonSerializer and vice versa, which means you have a cyclic dependency. This is often a sign of bad design, since it makes Corpus harder to test, harder to reuse in a different context, harder to extent etc.
In most cases, I would avoid solutions with cyclic dependencies. Even better would be a design where you don't need a special _CorpusJsonSerializer, but only a general JsonSerializer which takes an arbitrary object (for example, of type Corpus) and determines its type and the serializable attributes of that type at run time. This way, you would eliminate all of the current dependencies.
Another design option, which is not so generic but avoids cyclic dependency, is to inject the dependency from outside. Means, in the Corpus constructor provide a parameter for a "serializer" object which is stored in your Corpus object and used in the serialize_to_stream method. You can pass here an object of _CorpusJsonSerializer in most cases, but also a completely different object following the same interface conventions (i.e. providing a serialize method). This way, when for testing purposes you don't need a serializer, you don't have to provide one; or if you need a different kind of serializer, you can easily exchange it. Of course, this option will imply that _CorpusJsonSerializer is exposed to the user, but you can keep the convenience method in Corpus without the drawbacks of cyclic dependencies.


text:
Q: Conditional testing for existence of specific files and file types in zsh I want to check the current directory for the existence of files with extensions of abc, bak or tmp, or a file named tmpout.wrk. I can't get this (eventually part of a function) to work in zsh. It runs, but fails to detect properly.
if [[ -f *.(abc|bak|tmp) || -f tmpout.wrk ]]; then
    echo 'true';
else
    echo 'false';
fi

A: To test that the glob returns at least one file, you can do:
if ()(($#)) (*.(abc|bak|tmp)|tmpout.wrk)(NY1); then
  echo true
else
  echo false
fi

To check that at least one of them is a regular file after symlink resolution, add the -.  glob qualifier:
if ()(($#)) (*.(abc|bak|tmp)|tmpout.wrk)(NY1-.); then
  echo true
else
  echo false
fi

*

*()(($#)) is an anonymous functions to which we pass the result of the globs. The body of that function ((($#))) just tests that the number of arguments in non-zero.

*N as a glob qualifier turns on nullglob for that glob (makes the glob expand to nothing when it doesn't match any file)

*Y1 limits the expansion to at most one file. It's a performance optimization.

*- makes the next glob qualifier be considered after symlink resolution.

*. considers regular files only (so here regular files or symlinks eventually resolving to a regular file, like the [ -f file ] command does).

A: TL;DR
set -o extendedglob
if [[ -n *.(abc|bak|tmp)(#qN) || -f tmpout.wrk ]]; then

Otherwise, via some testing,
% [[ -f /etc/passwd ]] && echo yea
yea
% echo /etc/passw?
/etc/passwd
% [[ -f /etc/passw? ]] && echo yea
%

Okay, what is zsh doing here?
% set -x
% [[ -f /etc/passw? ]] && echo yes
+zsh:13> [[ -f '/etc/passw?' ]]
%

Them single quotes sure aren't going to glob nothing. Let's search on [[ in man zshall ... and then search on CONDITIONAL EXPRESSIONS ... ah here's something about filename generation:
   Filename  generation is not performed on any form of argument to condi-
   tions.  However, it can be forced in any case where normal shell expan-
   sion  is  valid and when the option EXTENDED_GLOB is in effect by using
   an explicit glob qualifier of the form (#q) at the end of  the  string.
   A  normal  glob qualifier expression may appear between the `q' and the
   closing parenthesis; if none  appears  the  expression  has  no  effect
   beyond causing filename generation.  The results of filename generation
   are joined together to form a single word, as with the results of other
   forms of expansion.

   This  special  use of filename generation is only available with the [[
   syntax.  If the condition occurs within the [ or test builtin  commands
   then  globbing  occurs instead as part of normal command line expansion
   before the condition is evaluated.  In this case it may generate multi-
   ple words which are likely to confuse the syntax of the test command.

   For example,

          [[ -n file*(#qN) ]]

   produces  status  zero if and only if there is at least one file in the
   current directory beginning with the string `file'.  The globbing qual-
   ifier  N  ensures  that the expression is empty if there is no matching
   file.

So with this in mind,
% [[ -f /etc/passw?(#q) ]] && echo yes
+zsh:14> [[ -f /etc/passwd ]]
+zsh:14> echo yes
yes
% exec zsh -l

And to your case, accounting for the case where there may be no files:
% mkdir dir
% cd dir
% touch blah.foo
% [[ -f *.(foo|bar|baz)(#q) ]] && echo yea
yea
% rm blah.foo
% [[ -f *.(foo|bar|baz)(#q) ]] && echo yea
zsh: no matches found: *.(foo|bar|baz)(#q)
% [[ -f *.(foo|bar|baz)(#qN) ]] && echo yea
% touch a.foo b.foo
% [[ -f *.(foo|bar|baz)(#qN) ]] && echo yea
% [[ -n *.(foo|bar|baz)(#qN) ]] && echo yea
yea
%

(though with -n we only check that the globs match, not that the corresponding files are regular files).


text:
Q: How do I achieve O(n^2) complexity for the Gale-Shapley algorithm? The Gale-Shapley Algorithm is meant to solve the stable matching problem with O(n2). In the matching problem, there are n women and n men. Each person has a preference list ranking every member of the opposite sex for marriage. The goal is to create couples such that no one would be better off leaving their marriage for someone else.
The following is pseudocode from Wikipedia:
algorithm stable_matching is
    Initialize all m ∈ M and w ∈ W to free
    while ∃ free man m who still has a woman w to propose to do
        w := first woman on m's list to whom m has not yet proposed
        if w is free then
            (m, w) become engaged
        else some pair (m', w) already exists
            if w prefers m to m' then
                m' becomes free
                (m, w) become engaged
            else
                (m', w) remain engaged
            end if
        end if
    repeat

Every man (n) can propose up to n times in the worst case. That gives the while loop O(n^2). But there's a line in the inner loop which concerns me:
if w prefers m to m' then

Shouldn't this mean we have to iterate through a preference list to find who appears first? Wouldn't that also be O(n), making the algorithm O(n3)?
My preference lists for men and women are both of type int[n][n]. The outer index is the id of the person who owns the inner list. The inner list contains the ids of everyone in the opposite sex, ordered by the owner's preference.

A:
Shouldn't this mean we have to iterate through a preference list to find who appears first? Wouldn't that also be O(n), making the algorithm O(n3)?

Nope.

My preference lists for men and women are both of type int[n][n]. The outer index is the id of the person who owns the inner list. The inner list contains the ids of everyone in the opposite sex, ordered by the owner's preference.

What you need to do with the preferences determines the appropriate data structure to use for them.  You need a woman to be able to compare her preferences for 2 different men in constant time, so you should use a data structure that supports that.  For example you can invert the women's preference lists to create a rank map, so that rank[m] returns the rank of man m in her original list of preferences.
Creating all the rank maps takes O(n2) time (in the number of people), so it doesn't increase the overall complexity of the algorithm.

A: No. You don't need to iterate to find the preference. Because the preference is given in order. Here, the definition of preference is an order over men or women. Hence, you don't need to iterate to find that m is prefered over m' or not.

A: You will store the preference list of n males and females in order in an Array. At the stage where you are saying that we will need another loop to go through n men in woman preference list we can avoid this loop by creating a priority based array and just use O(1) time to access the rank.
Of course to do this we need to create a Ranking Matrix or Map or simply an array of nn size. For each woman array will take n space and since there are n women we need nn space, same for men, they will also have n*n space. So we will have space complexity of O(n^2). By creating this ranking matrix in the beginning we are able to skip the loop you are mentioning and able to get time complexity of O(n^2).
As mentioned by Matt above this is possible only by using appropriate Data Structure for this step. You can use any Data Structures where we can access the ith element in linear time for this.


text:
Q: Комментарии и текст кракозябрами после преобразования проекта в Maven Собственно был проект. После преобразования в maven стал весь вида:
//�������� ���������� ������� � ��, ������� ������ �������
//������� ����, ��� ���� ��������� (� �� � ��������� ��� ����� ��������)
public JButton bInsert = new JButton("��������");
public JButton bUpdate = new JButton("��������");
public JButton bDelete = new JButton("�������");
/**
* ������ ��� ���������� ������� �� ������ ActionListener

Window -> Preferences -> Workspace и в проекте Проект -> Properties стоит text file encoding Cp1251.
Как не меняй, хоть UTF8, все равно как по коду вверху.
Ничего не понимаю...


text:
Q: Console error onClick where ID does not exist I have a click function which sits inside of my main.js.
When I am on the correct page where this ID is located, there are no errors in console and everything works fine. But when I navigate to another page where the main.js is still being loaded and the ID does not exist, my console gives me this error.
main.js?7a2b:51 Uncaught TypeError: Cannot set property 'onclick' of null

Any suggestions would be great
thanks

A: You need to check if the element that you want to select actually exists before you try to add an eventhandler to it. You can check if an element with a certain id exists like so:
var element = document.getElementById('<MY_ID>');
if(element){
    //Add your eventhandling inside this block
    element.addEventListener('click', function {/* ... */})
}


text:
Q: Double Polymorphic Association in Rails I have a join table and I would like both the belongs_to associations to be polymorphic. The relationship would look as follows:

The class structure would look as follows:
Class Tagable1 < ActiveRecord::Base
  has_many :taggings
  has_many :tag_group_1s, :through => :taggings
  has_many :tag_group_2s, :through => :taggings
  ...
end

Class TagGroup1 < ActiveRecord::Base
  has_many :taggings
  has_many :taggable_1s, :through => :taggings
  has_many :taggable_2s, :through => :taggings
  ...
end

Class Tagging < ActiveRecord::Base
  belongs_to :taggable, :polymorphic => true
  belongs_to :tag, :polymorphic => true
end

There's obvious drawbacks to this approach, especially the heavy load on the Taggings table. What I'm trying to achieve is a flexible design which allows me to create new Taggables or TagGroups without creating new join tables. For instance, without the double polymorphic, Taggable1 would need a Taggable1Taggings table to join Taggable1 with the polymorphic TagGroups. Likewise, I would need Taggable2Taggings, Taggable3Taggings, Taggable4Taggings, etc etc.
I would love to be enlightened if there are drawbacks I'm not thinking of.

A: I'm not sure if it's Rails 3 compatible, but you want the has_many_polymorphs gem:
https://github.com/fauna/has_many_polymorphs
this fork claims to be compatible with Rails 3:
https://github.com/jystewart/has_many_polymorphs

A: seems the acts-as-taggable-on gem could make your life easier.


text:
Q: галочка у checkbox неправильно устанавливается при удалении элемента из массива TODOS Всем привет, делаю своё первое приложение  TODOS на реакт и на финальном этапе выскочил неприятный баг со стилями который уже замучился исправлять. В общем при добавлении нового элемента в массив todos и последующим его удалении всё работает хорошо. Так же всё работает при клике на checkbox, а именно устанавливается галочка и зачёркивается текст. Это я реализовал с помощью вот этого кода в компоненте который рендерит li

Переключение completed в элементе todo осуществляется с помощью этого кода:

НО как только я поставлю галочку и удалю любой элемент из списка вылазит вот такой баг.

При том что свойство completed у элементов в консоли выглядит вот так :

A: <input checked={todo.completed} onChange={onChange(todo.title)} type="checkbox"/>


text:
Q: Angular Two different layouts in same app I'm using AngularJS for a store app(using Laravel for back-end as API). But now I want to implement a blog on the same app. For example I'm in the store(this has one layout), I click on the Blog link in the menu and it redirects me to another page that has a totally different layout. Is this possible?
Here is my index.html:

       Ugurt

Post

Blog

Login

Sign up

Logout

Here is my stateProvider config(a portion):
angular.module('Ugurt', ['ngResource', 'ngMessages', 'ngAnimate', 'toastr', 'ui.router', 'satellizer', 'checklist-model', 'ngCart', 'textAngular'])
.config(function($stateProvider, $urlRouterProvider, $authProvider) {
$stateProvider
  .state('home', {
    url: '/',
    controller: 'HomeCtrl',
    templateUrl: 'partials/home.html'
  })
  .state('store', {
    url: '/store',
    controller: 'StoreCtrl',
    templateUrl: 'partials/store.html'
  })

Every link I click on shows a different partial file because of the ui-view attribute. But when I click on the Blog link, I want it to lead to a different file that a completely different layout and menu. I want to put the both in the same app because the register and login is going to be the same for both parts. And when one user is logged in in the store, if he goes to the Blog part, I still want him to be logged in without doing anything.
Any ideas?

A: If you have ui-router like structure, you have route names, so you just need to create new route with different layout and redirect to new route.

A: Well there are already a way to do that, using a proper router like ui-router.
For example:
You have two main states, store and blog. What you can do is configure those two states in te $stateProvider under app.config.
For example:
myApp.config(function ($stateProvider){

    $stateProvider.state('store', {
        url: '/store',
        templateUrl: 'store-layout.html'
    });

    // and then, when it requires to have substate of store you must inherit this state from store state
    // also you'll have to specify a new ui-view inside store-layout.html to be the outlet of the nested states

    $stateProvider.state('store.categories', {
        url: '/store/categories',
        templateUrl: 'store-categories.html'
    });

    $stateProvider.state('blog', {
        url: '/blog',
        templateUrl: 'blog-layout.html'
    });

    $stateProvider.otherwise('/store');
});