text:
Q: un-intersect values in R I have two data sets of at least 420,500 observations each, e.g.
dataset1 <- data.frame(col1=c("microsoft","apple","vmware","delta","microsoft"),
                     col2=paste0(c("a","b","c",4,"asd"),".exe"),
                     col3=rnorm(5))

dataset2 <- data.frame(col1=c("apple","cisco","proactive","dtex","microsoft"),
                     col2=paste0(c("a","b","c",4,"asd"),".exe"),
                     col3=rnorm(5))
> dataset1
       col1    col2 col3
1 microsoft   a.exe    2
2     apple   b.exe    1
3    vmware   c.exe    3
4     delta   4.exe    4
5 microsoft asd.exe    5
> dataset2
       col1    col2 col3
1     apple   a.exe    3
2     cisco   b.exe    4
3    vmware   d.exe    1
4     delta   5.exe    5
5 microsoft asd.exe    2

I would like to print all the observations in dataset1 that do not intersect one in dataset2 (comparing both col1 and col2 in each), which in this case would print everything except the last observation - observations 1 & 2 match on col2 but not col1 and observation 3 & 4 match on col1 but not col2, i.e.:
        col1  col2 col3
1:     apple b.exe    1
2:     delta 4.exe    4
3: microsoft a.exe    2
4:    vmware c.exe    3

A: You could use anti_join from dplyr
 library(dplyr)
 anti_join(df1, df2, by = c('col1', 'col2'))
 #      col1  col2       col3
 #1     delta 4.exe -0.5836272
 #2    vmware c.exe  0.4196231
 #3     apple b.exe  0.5365853
 #4 microsoft a.exe -0.5458808

data
 set.seed(24)
 df1 <- data.frame(col1 = c('microsoft', 'apple', 'vmware', 'delta',
 'microsoft'), col2= c('a.exe', 'b.exe', 'c.exe', '4.exe', 'asd.exe'),
    col3=rnorm(5), stringsAsFactors=FALSE)
 set.seed(22)
 df2 <- data.frame(col1 = c( 'apple', 'cisco', 'proactive', 'dtex',
 'microsoft'), col2= c('a.exe', 'b.exe', 'c.exe', '4.exe', 'asd.exe'),
  col3=rnorm(5), stringsAsFactors=FALSE)

A: data.table solution inspired by this:
library(data.table) #1.9.5+
setDT(dataset1,key=c("col1","col2"))
setDT(dataset2,key=key(dataset1))
dataset1[!dataset2]

        col1  col2 col3
1:     apple b.exe    1
2:     delta 4.exe    4
3: microsoft a.exe    2
4:    vmware c.exe    3

You could also try without keying:
library(data.table) #1.9.5+
setDT(dataset1); setDT(dataset2)
dataset1[!dataset2,on=c("col1","col2")]


text:
Q: SharePoint 2010 Designer workflow throwing error I have created a SharePoint 2010 Designer workflow which sends an email to a user when an item is created and it has approval and decline if approved it will go back to the initiator but am facing a weird error here when the Initiator creates the item it is not sending emails the error shows the following

"The workflow could not update the item, possibly because one or more
  columns for the item require a different type of information"

Any help would be appreciated thanks in advance.

A: Just added a column  to the list called status as choice yes/no depending on status I am sending the mails now. But could not rectify what is the issue on the error I am getting. I have tried several options provided in different sources from google but could not solve this except adding the new column did the job for me.Thanks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL Compare and filter multiple columns into rows Ok so I have a table(MyTable) that looks like this:
value1 | value2 | value3 | value4  | value5  | date
---------------------------------------------------------
   1   |    4   |   6    |    25   |   35    | 2011-10-07
---------------------------------------------------------
   2   |    3   |   6    |    25   |   14    | 2011-10-01
---------------------------------------------------------

My end goal is to get one column with every unique number and latest asocciated date like:
combinedValues  | date
----------------------------
       1        | 2011-10-07
----------------------------
       4        | 2011-10-07
----------------------------
       6        | 2011-10-07
----------------------------
       25       | 2011-10-07
----------------------------
       35       | 2011-10-07
----------------------------
       2        | 2011-10-01
----------------------------
       3        | 2011-10-01
----------------------------
       14       | 2011-10-01
----------------------------

So far I've gotten it to work with this query, but with one column only:
SELECT t.value1, t.date
FROM MyTable t
INNER JOIN (
  SELECT value1, MAX( date ) AS LatestDate
  FROM MyTable
  GROUP BY value1
)tm ON t.value1= tm.value1
AND t.date = tm.LatestDate
GROUP BY value1
ORDER BY date DESC

So how would I go about this to accomplish the table with combinedValues? Is it even possible?

A: Try this query:
Select val,Max(date) date From
(Select value1 as val,date From MyTable
Union All
Select value2 as val,date From MyTable
Union All
Select value3 as val,date From MyTable
Union All
Select value4 as val,date From MyTable
Union All
Select value5 as val,date From MyTable)tab
Group by val order by date desc,val;

 SQL Fiddle


text:
Q: Is it possible to apply country specific masking in Dynamics CRM 2016? Up through MS CRM 2015 we have been successfully using jquery.ui to set input and view masks for common address data based on the country of the address.  We store these masks with a custom country entity.  The default CRM field is hidden.  Using JQuery we create a simple textbox and apply the mask to the value in the field based on the country value submitted.
Is there a way to add phone masking to CRM Forms in 2016?  Any help is greatly appreciated!

A: I'm not sure why you say that CRM 2016 does not allow DOM manipulation.  It doesn't allow it any more than any other version of CRM.  No DOM manipulation is supported, although nothing is preventing you from doing so, except that Microsoft may completely change the DOM and break everything you customized.
Actually 2016 happens to be the only version of CRM that this actually is possible in a supported manner without using an iFramed Web Resource.  Your basic setup with be as follows
In the OnLoad of the form

*

*Retrieve the Country Phone Number Mask

*Apply the mask to the field.

*Add an OnKeyPress function to the field that removes the mask as the user types.

A: Use a web resource for that. Is the supported alternative version. Manipulating the DOM directly is bad practice as it might change across versions.


text:
Q: Show that $f$ is Riemann integrable and that $\int_a^b f (x)dx = 0$ Let $k \in \mathbb{R}$, $x_0 \in [a, b]$, and define $f:[a, b] \to \mathbb{R}$ via
$$
\begin{cases}
    0 & x \ne x_0\\
    k & x= x_0
\end{cases}
$$
Show that $f$ is  Riemann integrable and that $\int_a^b f (x)dx = 0$.
I know that I need to show that the lower and upper Riemann sums must be equal, but in my mind they are not equal, because at the point $x=x_0$, it will have an upper sum of $k$ but a lower sum of $0$. However, I understand and can visualize how the entire integral is equal to $0$.
Edit: I find the upper Riemann sum by
$$
U(f,P_n)=\sum_{i=1}^n M_i\Delta x_i.
$$
I know that $\Delta x_i =\frac{1}{n}$, but I don't know how to write $M_i$ because the function will suddenly jump up to $k$ at a certain point.

A: I don't see what I consider the salient points in the other answers, so here we go.

*

*What I always called the convenient criterion for integrability in my teaching is this: $f$ is integrable on $[a,b]$ if and only if for every $\epsilon>0$, there is a partition $P$ with $U(f,P)-L(f,P)<\epsilon$.

*Create a partition as follows. I will suppose $a<x_0<b$. You can take care of the other cases. If $k=0$, the function is the zero function and there's nothing to do (I hope).
Given $\epsilon>0$, let $P$ be the partition $t_0=a$, $t_1=x_0-\delta$, $t_2=x_0+\delta$, $t_3=b$. We choose $\delta>0$ small enough so that $t_0<t_1<t_2<t_3$ and then small enough so that $2|k|\delta<\epsilon$. If $k>0$, we have $U(f,P) = 2k\delta$ and $L(f,P)=0$. If $k<0$, we have $U(f,P) = 0$ and $L(f,P) = 2k\delta$. In either event, we have $U(f,P)-L(f,P)<\epsilon$. [You should draw pictures to see what's going on here. I'm leaving it to you to write out explicitly the formulas for $U(f,P)$ and $L(f,P)$.]
Combining 1 and 2, we have shown $f$ is integrable on $[a,b]$. A very important point is that we do not always need to use a partition into subintervals of equal length.

A: You make upper and lower sums by partitioning the interval $[a,b]$ into subintervals. The final upper and lower sums are the limits you approach as these subintervals get narrower and narrower.
Assuming $k\geq0$, the upper sum is $k$ when the subintervals are $1$ wide (for $k\leq0$ it is the lower sum that equals $k$ while the upper sum is $0$). What happens to the upper sum when the subintervals are narrower than $1$?

A: The upper and lower sums will not be equal, but the upper and lower integrals will be. I'm not sure what notation you use, so I will use the one I am most familiar with. For a partition $P=\{x_0,x_1,\ldots,x_n\}$, the upper and lower sums are respectively \begin{align*}
U(f,P) &= \sum^n_{i=1} \left(\sup_{x\in[x_{i-1},x_i]} f(x)\right)(x_i-x_{i-1}), \\
L(f,P) &= \sum^n_{i=1} \left(\inf_{x\in[x_{i-1},x_i]} f(x)\right)(x_i-x_{i-1}).
\end{align*} Note that the width of the intervals come into play here. You are right that the supremum or infimum of $f$ will take the value $k$ for one (or maybe two) of those intervals, but the width of those intervals could be very small so that contribution can be made as small as you like.


text:
Q: An item with the same key has already been added in Dictionary I am working on sql clr application, after integrating with sql, I am getting this error (for English it's working but problems while adding Unicodes to dictionory):
**Msg 6522, Level 16, State 2, Line 1
A .NET Framework error occurred during execution of user-defined routine or     aggregate "SqlCompare":
System.ArgumentException: An item with the same key has already been added.
System.ArgumentException:
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value,      Boolean add)
   at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
   at Translate_Class_NUM..ctor()
   at StringPercentageCompare..ctor()
   at UserDefinedFunctions.SqlComparison()**

 here is my code in c#
private   Dictionary<string, string> MyDictionary;
//private string[,] MyArray;

public Translate_Class_NUM()
{
    MyDictionary.Add("?", "01");
    MyDictionary.Add("?", "02");
    MyDictionary.Add("?", "03");
    MyDictionary.Add("?", "04");
    MyDictionary.Add("?", "05")
}

and in sql server code is
    CREATE ASSEMBLY DBDB_DeDuplication
AUTHORIZATION dbo
from 'E:\Projects\DBDB_DeDuplication\DBDB_DeDuplication\obj\Debug\DBDB_DeDuplication.dll'
WITH PERMISSION_SET = SAFE
GO
CREATE FUNCTION SqlCompare() RETURNS nvarchar(50)
AS EXTERNAL NAME DBDB_DeDuplication.UserDefinedFunctions.SqlComparison;
GO
SELECT dbo.SqlCompare();
GO
thanks in advance

A: This code works just fine for me:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("ಅ","01");
dict.Add("ಇ","02");

As I tried to explain before in the comments, your Unicode string must not be passing through to the compiler in the way you expect. Sometimes this can be due to the C# source file being saved with ASCII encoding or other non-Unicode supporting encoding. To guarantee results, use the C# Unicode literal encoding (U+0000 to U+FFFF).
If you don't know how to get the equivalent Unicode escape sequence, you can use this code:
static string EncodeNonAsciiCharacters( string value )
{
    StringBuilder sb = new StringBuilder();
    foreach( char c in value ) {
        if( c > 127 ) {
            // This character is too big for ASCII
            string encodedValue = "\\u" + ((int) c).ToString( "x4" );
            sb.Append( encodedValue );
        }
        else {
            sb.Append( c );
        }
    }
    return sb.ToString();
}

Console.WriteLine(EncodeNonAsciiCharacters("ಅ"));
\u0c85
Console.WriteLine(EncodeNonAsciiCharacters("ಇ"));
\u0c87

So then you can write the safer version of the source code as:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("\u0c85","01");
dict.Add("\u0c87","02");


text:
Q: Can't query names from a table that does not exist in another table I have two tables that are identical in fields. I want to query names in table2 that are not in table1. Both tables have name field as unique (primary key).
Here are the info. of my database design:
My query is:
SELECT `table2`.`name` FROM `mydatabase`.`table2`, `mydatabase`.`table1`
WHERE `table2`.`name` NOT IN (SELECT  `table1`.`name` FROM `mydatabase`.`table1`)
AND table2`.`name` NOT LIKE 'xyz%';

The output of SHOW CREATE TABLE <table name>:
For table1:
table1, CREATE TABLE `table1` (
  `name` varchar(500) NOT NULL,
  `ip` varchar(500) DEFAULT NULL,
  `type` varchar(500) DEFAULT NULL,
  `grade` varchar(500) DEFAULT NULL,
  `extended_ip` text,
  PRIMARY KEY (`name`),
  UNIQUE KEY `mydatabase_name_UNIQUE` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

And table2:
tabl2, CREATE TABLE `table2` (
  `name` varchar(500) NOT NULL,
  `ip` varchar(500) DEFAULT NULL,
  `type` varchar(500) DEFAULT NULL,
  `grade` varchar(500) DEFAULT NULL,
  `extended_ip` text,
  PRIMARY KEY (`name`),
  UNIQUE KEY `mydatabase_name_UNIQUE` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

The output of EXPLAIN <my query>:
# id, select_type, table, partitions, type, possible_keys, key, key_len, ref, rows, filtered, Extra
1, PRIMARY, table1, , index, , mydatabase_name_UNIQUE, 502, , 17584, 100.00, Using index
1, PRIMARY, table2, , index, , mydatabase_name_UNIQUE, 502, , 46264, 100.00, Using where; Using index; Using join buffer (Block Nested Loop)
2, SUBQUERY, table1 , index, PRIMARY,mydatabase_name_UNIQUE, mydatabase_name_UNIQUE, 502, , 17584, 100.00, Using index

EDIT:
And I forgot to mention what happens is that the databse just crashes with my query. i am using mysql-workbench in Ubuntu 18. When I perform this query the whole workbench closes and I have to restart opening it again.

A: Just do a LEFT JOIN on name, with table2 as your starting table, since you want to consider all the names from table2 which do not exist in table1. Names which don't exist in table1 will have a null value post the join. Note that this join based solution will be significantly faster than any subquery based approach.
Also, you should avoid comma (,) based implicit joins. It is old syntax, and you should use explicit JOIN based syntax. Read: Explicit vs implicit SQL joins
Also, it is a good habit to use Aliasing for better readability
Try the following:
SELECT t2.name
FROM `mydatabase`.`table2` AS t2
LEFT JOIN `mydatabase`.`table1` AS t1 ON t1.name = t2.name
WHERE t1.name IS NULL
  AND t2.name NOT LIKE 'xyz%';

A: Try a subquery:
SELECT `table2`.`name` FROM `mydatabase`.`table2` WHERE `table2`.`name` NOT IN (SELECT `table1`.`name` FROM `mydatabase`.`table1`);


text:
Q: Typeorm MySql search by "column like %var%" How to search in MySql using typeorm by using "column like".
 async findAll({
    page,
    count,
    ...where
  }: CategorySelectFilter): Promise<Category[]> {
    return this.categoryRepository.find({
      where,
      take: count,
      skip: (page - 1) * count,
      order: {
        createdAt: 'DESC',
      },
    });
  }

When "where" contains name it shoild search it by "name like %var_name%" and not just "name = var_name".
I need something like hook @BeforeLoad to override the name prop in entity.
I tried using @Index({fullText: false}) on name column, but it does not work.

A: Here is my solution that I always use in my projects.
I use conditional spread syntax (...) to "build" the query dynamically. See this for more information.
async findAll({
    page,
    count,
    whereConditions
}: CategorySelectFilter): Promise<Category[]> {
    return this.categoryRepository.find({
        ...whereConditions,
        take: count,
        skip: (page - 1) * count,
        order: {
            createdAt: 'DESC',
        },
        where: {
            ...(whereConditions.name !== undefined && { name: ILike(`%${whereConditions.name}%`) }),
        }
    });
}

The where condition name: "%VARIABLE%" is added only if name is present in whereConditions object.
PS: I prefer using ILike: can be used instead of Like to make the match case-insensitive according to the active locale.


text:
Q: How can I compile C on Linux that will work on any distro? If I compile a self-contained project with gcc and statically link the C run-time library, will this work on any Linux distro? I don't care about any static link disadvantages (such as big file size) so long as it works. It is a closed-source project and this is beyond my control. The architecture of the PCs is the same.

A: If you can guarantee that all of the code it will execute is self-contained in the binary you ship, then theoretically (emphasis on theoretically) it should work on any linux distribution.  In this process there are an enormous number of pitfalls. My personal opinion is that it is pretty much impossible to make this work due to changing interfaces across versions. Interfacing with other libraries is a fragile nightmare.
Most companies that I'm familiar with (including my own) produce builds made for different distributions. There are some complications that result from having to make a build for SLES, Redhat, etc., but I'm confident that providing a few different builds ultimately is simpler and causes less problems than attempting to statically link everything.


text:
Q: Broke default button's InputBinding to the Enter key My WPF application has a form for performing searches of the database.  It has a Button that starts the search whose IsDefault property is set to true.  Normally, this allows the Button's Click event to fire when you press the enter key on the form.
The results of the search are shown in a Telerik RadGridViewcontrol.  Originally, if you double clicked on a row in the results, the program would take you to another tab and show you the details of the row you'd clicked on.  My boss asked me to modify the RadGridView so that when you press Enter, the control does the same thing.
I was able to achieve this by adding a custom command for displaying the details to my program and adding a CommandBindings section to the search control's XAML.I then added an InputBindings section to the RadGridView's XAML and everything works.  Except that pressing enter no longer raises the default Button's Click event:
<UserControl x:Class="CarSystem.CustomControls.Searcher"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
             xmlns:cs="clr-namespace:CarSystem.CustomControls"
             xmlns:vm="clr-namespace:CarSystem.ServiceModel;assembly=ViewModels"
             xmlns:sys="clr-namespace:System;assembly=mscorlib"
             mc:Ignorable="d"
             Height="620"
             IsVisibleChanged="Searcher_IsVisibleChanged"
             Loaded="Searcher_Loaded"
             Width="990">

    <UserControl.CommandBindings>
        <CommandBinding CanExecute="DisplayEditHotListEntry_CanExecute"  Command="cs:CarSystemCommands.DisplayEditHotListEntry"  Executed="DisplayEditHotListEntry_Executed" />
        <CommandBinding CanExecute="DisplayEditRecordDetails_CanExecute" Command="cs:CarSystemCommands.DisplayEditRecordDetails" Executed="DisplayEditRecordDetails_Executed" />
    </UserControl.CommandBindings>

    <Grid Background="{DynamicResource ContentBackground}"
              Name="LayoutRoot">

        . . .

        <telerik:RadGridView . . .>
            . . .
            <telerik:RadGridView.InputBindings>
                <KeyBinding Key="Enter" Command="{x:Static cs:CarSystemCommands.DisplayEditHotListEntry}" />
            </telerik:RadGridView.InputBindings>
        </telerik:RadGridView>

        <Button IsDefault="true" . . . />

    </Grid>
</UserControl>

The top of the form has a number of controls where search criteria are specified.  I'd like pressing the enter key while the focus is in one of these controls to fire off the default Button's Click event, and the new action when the focus is in the RadGridView.  How do I get this to work?


text:
Q: Sync Windows folders with remote server and log changes that are made I work remotely as part of a distributed team working on a project.  Our project files are stored on a server share that I access via a VPN.
Currently I use Offline Files to maintain a local copy of the current project state.  However it appears I can't get a list of changes that have occurred between syncs.  But that is crucial for me.
Case in point, yesterday I spent several hours comparing lists of Bills of Materials with equipment that was specified on the project drawings and discovered lots of discrepancies.  So I wrote up an email listing the differences and sent it out.  Today I find out (by accident) that the BOM files I referred to yesterday have now moved around and newer ones had magically appeared in a new sub-directory.  Obviously someone (working remotely in a different location) realized that the newer files were not on the server and "cleaned" things up overnight.
How can I keep copies of these files offline, be able to sync them, and have a history of all changes made by each sync? I would like the sync to work like the built-in Offline Files/Windows Sync Center.
As for the log history, I am looking for a simple list of files/directories that have been added/deleted/changed. This is critical.
I don't have control over the server. I can only make software changes on my end. I'm running Windows 10 on my machine.

BTW suggesting some sort of repository system on the server side is not an option.  Don't even ask why not.


text:
Q: capistrano: sudo error after after it had been working fine before I recently started using capistrano in my rails application deployment.  It was working fine for me and then all of a sudden, I started getting this error
sorry, you must have a tty to run sudo

after every gem it tried to install.  I know this problem can typically be solved by putting in set :use_sudo, false in the deploy.rb file but I already have that in there.  And the strangest thing is that I reverted my ENTIRE directory back to when I know for sure capistrano was working and it's still giving me the same error.
My server is running CentOS
So what could the problem possibly be caused by?  Any ideas?

A: You can tell cap to create a pty for each process, by adding this line:
default_run_options[:pty] = true
to Capfile

A: For Capistrano 3 you need to add:
set :pty, true
to the file config/deploy.rb


text:
Q: Resolve JDBC Oracle Index Column Names Hi is there a possibility to resolve the real column names from a index?
I use:
java.sql.DatabaseMetaData.getIndexInfo(String, String, String, boolean, boolean)

But i get somthing like this:
[table=LOG_EMAIL, name=LOG_EMAIL_USERS_ID, columns=[SYS_NC00011$ A], unique=false]

How can i resolve the: SYS_NC00011$
I use ojdbc6-11.2.0.4

A: That index is a function based (expression) index.
The expression that is referenced by that name is stored in the system view user_ind_expressions:
select column_expression
from user_ind_expressions
where index_name = 'LOG_EMAIL_USERS_ID'
  and column_position = 1;

If you have more than one expression in the index you have multiple rows in user_ind_expressions with different values for column_position (the first expression is 1, the second is 2 and so on). The name SYS_NC00011$ will not show up in that view.

A: I would use the ResultSetMetadata -
ResultSetMetaData rsmd = rs.getMetaData();

for (int i = 1; i <= rsmd.getColumnCount(); i++) {
  System.out.println(rsMetaData.getColumnName(i));

}


text:
Q: Is this matrix differentiation derivation correct? I am trying to find derivative of this quantity but in my result the dimensions don't match. Any inputs will be helpful.
$$\frac{\partial}{\partial w}\left(\left\|F(w)-\beta D^{\top} Z\right\|_{F}^{2}\right)$$
$$
\begin{equation}
 \begin{split}
\frac{\partial}{\partial w}\left(\left\|F(w)-\beta D^{\top} Z\right\|_{F}^{2}\right)
=& \, \frac{\partial}{\partial w}\left(\left\|F(w)-\beta D^{\top} Z\right\|_{F}^{2}\right)\\
  =& \, \frac{\partial}{\partial w}\left(Tr\left[ (F(w)-\beta D^{\top} Z) \, (F(w)-\beta D^{\top} Z)^{\top}\right] \right)\\
  =& \, \frac{\partial}{\partial w}\left(Tr\left[ \left(F(w)\,F(w)^{\top}\right)- 2\,F(w)\left( \beta D^{\top} Z\right)^{\top} + \left(\beta D^{\top} Z Z^{\top} D \beta^{\top} \right) \right] \right) \\
  =& \, \frac{\partial}{\partial w}Tr\left[ F(w)\,F(w)^{\top}\right] - 2 \, C_1 \frac{\partial}{\partial w} Tr\left[\,F(w)\left( \beta D^{\top} Z\right)^{\top} \right]\\
  =& \, \left(\frac{\partial}{\partial w}F(w)\right)\,F(w)^{\top} - 2 \, C_1 \left(\frac{\partial}{\partial w} \,F(w) \right)\left( \beta D^{\top} Z\right)^{\top} \\
  =& \, \left(\frac{\partial}{\partial w}F(w)\right)\, \left(F(w) -  \left( \beta D^{\top} Z\right)\right)^{\top} \\
  =& \, \left(\frac{\partial}{\partial w}F(w)\right)\, \left(F(w)^{T} -   Z^{\top}D \beta^{T}\right)
 \end{split}
\end{equation} $$
Is the above derivation correct ? I think dimensionality of gradient doesn't match !!!
$$ D_{d \times m}, Z_{d \times l}, F(w)_{n \times l}, w_{d \times n}, \beta_{n \times m} $$
Gradient of "w" should be of same dimension as "w" which is (d X n) but the resultant is coming out to be tensor. Note that "F(w)" has soft-max probabilities for "Z"  predicted using  "w"

A: $\def\p#1#2{\frac{\partial #1}{\partial #2}}$For
typing convenience, define the matrix variables
$$\eqalign{
M &= \beta D^TZ \\
W &= w &&\big({\rm Uppercase\,for\,matrices}\big) \\
A &= (F-M) \quad&\implies\quad&dA = dF \\
}$$
You haven't told us anything about the function $F(W)$,
so I'll assume you don't need help calculating its fourth-order tensor gradient
$$\eqalign{
\Gamma_{ijk\ell} &= \p{F_{ij}}{W_{k\ell}} \\
}$$
The double-dot product notation for the trace of matrices
$$\eqalign{
A:B &= \sum_{i=1}^m \sum_{j=1}^n A_{ij}B_{ij} \;=\; {\rm Tr}(AB^T) \\
A:A &= \big\|A\big\|_F^2 \\
}$$
is easily extended to higher-order tensors, i.e.
$$\eqalign{
Y &= \Gamma:X \quad&\implies\quad Y_{ij} = \sum_{k=1}^p \sum_{\ell=1}^q \Gamma_{ijk\ell}X_{k\ell} \\
Z &= Y:\Gamma \quad&\implies\quad Z_{k\ell} = \sum_{i=1}^m \sum_{j=1}^n Y_{ij}\Gamma_{ijk\ell} \\
}$$
Write the trace using the above notation, then calculate its differential and gradient.
$$\eqalign{
\phi &= A:A \\
d\phi &= 2A:dA = 2A:dF = 2A:\Gamma:dW \\
\p{\phi}{W} &= 2A:\Gamma \\
}$$
It's easy to see that the gradient of the trace (with respect to $W$) has the same dimensions as $W$.


text:
Q: virtual clock speed throttling on linux Throttling at will the execution and display speed of a particular process, for example, a game, a flash game, or an OpenGL game. I want to be able to slow it down to 20% or 0.5%. This is simply not possible on host space in linux.
But linux supports two kernel-level virtualisation environments: KVM and lxc.
Question: Is it possible to provide a fake system clock to a virtual lxc or KVM machine so that a flash game running in the guest will not run faster than what is set to run?

A: Some choices:

*

*Qemu brake patch (will require work to apply no doubt.)

*Bochs has ips=NNNN to define CPU "Instructions Per Second".

*cpulimit a tool for limiting the CPU usage of a process (does not require virtualization.)

Update: You want this: https://superuser.com/questions/454534/how-can-i-slow-down-the-framerate-of-a-flash-game

A: I found a prototype version of the CheatEngine speed hack that works for linux.
http://forum.cheatengine.org/viewtopic.php?t=533437&sid=1a83d81ee08f8479eb8b190939b2e1aa
http://code.google.com/p/xeat-engine/source/checkout
http://pastebin.com/ZLryd20D
Basically it replaces gettimeofday with a hacked version using LD_PRELOAD magic. It works perfectly!
thanks lilezek! wherever you are!


text:
Q: Compare two CSV files for differences python New to python. I have around 70 CSV files in a folder. I would like to compare those files in pair of two like 1and 2, 2 and 3, 3 and 4 in that format. Now my files have same name though they have a suffix rev with a number like thin Cars*rev1, cars_rev2, cars_rev3, cars rev4*. I have tried this code but it gives an error :
# your directory path here
path = r'path'

# get all files
file_, pat = [], re.compile('.csv')
for root, dirs, files in os.walk(path):
    file_ = [os.path.join(root, f) for f in files if pat.search(f)]

# you may want to filter here, this line is just an example
# filter for all csv files containing 'rev'
file_ = [f for f in file_ if 'rev' in f]

temp =[]

for i in range(len(file_)-1):
    file1="cars_rev{}.csv".format(str(i+1))
    file2="cars_rev{}.csv".format(str(i+2))

    df1 = pd.read_csv(file1)
    df2 = pd.read_csv(file2)
    comparison_values = df1.fillna(0).isin(df2.fillna(0))
    #print (comparison_values)

    rows, cols = np.where(comparison_values==False)

    for item in zip(rows,cols):
        # do calculation
        for item in zip(rows,cols):
            df1.iloc[item[0], item[1]] = '{} --> {}'.format(df1.iloc[item[0], item[1]],df2.iloc[item[0], item[1]])
            #print(df1)

            temp.append(df1)

is there a possible way I can user the suffix rev1, rev2,rev3,rev4  to read those files and compare in pairs of two

A: Using itertools.tee() addresses the need  "I would like to compare those files in pair of two like 1and 2, 2 and 3, 3 and 4 in that format."
There is recipe provided in Itertools Recipes
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

A: Here is a bash solution according to the author's request:
$ cat compare.sh
#!/bin/bash
for ((i=1;i<=7;i++));
do
    for ((j=i+1;j<=7;j++));
    do
        diff ./cars_rev$i.csv ./cars_rev$j.csv 1>/dev/null
        printf 'diff %s %s = %s\n' cars_rev$i.csv cars_rev$j.csv $?
    done
done

Just change the 7 to 70 or whatever else you need ...


text:
Q: How to create crashlytics binding for Xamarin.iOS? I've downloaded Crashlytics app that integrates Crashlytics.framework into XCode project, and it works great for XCode. But as far as I know, to build Xamarin.iOS binding I need static library, and I can't find it neither in framework nor in Crashlytics.app contents. There is only "run" executable and header. I don't know how to use it under Xamarin.iOS. Btw, AndrewReed on Xamarin forum managed to build dll somehow, so it's possible.
So, how to create crashlytics binding for Xamarin?

A: AndrewReed answered this question on Xamarin forum:

As with quite a few sdk's, sometimes they bundle a folder instead of the static lib,which essentially is the static library. There will be a sizeable file that maybe doesnt have an extension(this is your .a file) so you can rename that to be .a and then include that in a xamarin bindings project. Run the sharpie marker on the header file in the folder which will generate your necessary files. Watch out for one gotcha, delegate is a reserved word in c#, so you may need to go around and change this by adding an @ symbol(to the name) to allow you to use the reserved word.
So what I actually did was, created a project in xcode and ran the crashlytics programme, this then added the crashlytics framework to the project. In finder locate that and you will have a structure like so: - run - /Versions --/A ---Crashlytics ---/Headers ----Crashlytics.h
So the /A folder is essentially your static lib, use this and create your binding from that, or in this particular case, just download it from the mono bindings || my repo.

A: If you're looking for an officially supported crash reporting plugin, Crittercism just released one (Full disclosure: I'm one of the co-founders).  You can download the bindings from the Xamarin store here: http://components.xamarin.com/view/crittercism

A: The latest version of Xamarin seems to have it build in.
Here are the steps that I followed
1.) In the Xamarin Studio , go to the main app, and add the Crashlytics API key in the Build -> Crash reporting section. Build and run that app. The evidence suggests that is enough to get data sent to Crashlytics. I saw that it knew about older versions of the app I had built and ran weeks ago with the API key already in.
2.) Go to Xcode and create a new project with the same name as the Xamarin project, com.{company}.{appname}. (You probably need to have that profile downloaded.) I did it in Swift by the way with no issues.
3.) Go to crashlytics.com com and go to settings -> Apps (or https://www.crashlytics.com/onboard)
4.) You will get an app to download and run. The app walks through the steps of adding
A.) A build phase run script
B.) Code to the application main Crashlytics.startWithAPIKey("nnnn")
5.) Run your Xcode version of the app
The Crashlytics web page popped up immediately.


text:
Q: Is it safe to change to the HTML5 DOCTYPE? My site is currently using:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

However, things like Facebook plugins are only valid in HTML5. So, is it safe to change my DOCTYPE to <!DOCTYPE html>? Will this affect anything?

A: Yes you can change your DOCTYPE,it will not affect anything that you have already done.In HTML 5 you will get some new features which you can use for your future purpose.Just check this link and you will get some idea about the features present in  HTML 5

A: You can change it. Almost all browsers just look for html in the doctype to ensure they are parsing HTML. It will also remain the same with new versions of HTML.
You might want to do the following quick changes to the head element:

*

*Change the meta element to <meta charset="utf-8">.

*Drop type="text/css" when linking stylesheets and drop type="text/javascript" in script elements as these are the default values.

A: Change your DOCTYPE as you said, it shouldn't affect what you've already done in HTML4, but it does give you options of some of the new HTML5 features in future.

A: The only thing that such a doctype change will affect is validation. Other than that, the doctype declaration only affects browser mode (quirks / almost standard / standard), and XHTML 1.0 and HTML5 doctype have the same effect in this respect.
If you don't use a validator, there is no reason to change. If you do, you should select the doctype according to which HTML version your document is closer to. Besides, HTML5 validation is completely different from XHTML 1.0 validation (heuristic mixed-strategy checking vs. formal well-defined but limited checking).

A: It shouldn't affect anything, but it's considered good markup to leave it as it is. HTML5 should work anyway.


text:
Q: vsts How do I add columns to task boards I have looked at various articles and can see how to add columns to story boards, however we are working in sprints using the task boards and I cannot find any way of adding another column to the task board. Could someone please help me?

A: Go to the admin for your project. Click the "Process" that you're currently using. Find "Task" in the "Work Item Types" tab. Click the "States" tab and add a new State. This new state will appear as a column on the task board.


text:
Q: Where to insert comma(s)? Compare these:

*

*She tried, and, as expected, failed.

*She tried, and as expected, failed.

*She tried and, as expected, failed.

*She tried and as expected, failed.

*She tried and (as expected) failed.

The first seems most correct, while the last seems most elegant. Is it all a matter of taste/style?
I'm also curious of these:

 6. She tried, and failed.
   7. She tried and failed.

Is there ever a need for the first form?

A: I usually follow Strunk & White and only deviate from their rules if strict adherence would result in something that breaks the flow of reading/thought.

*

*Enclose parenthetic expressions between commas.

*Place a comma before and or but introducing an independent clause.

*Do not join independent clauses by a comma.

This points to number 3 being the correct sentence. As for the last two, I definitely prefer number 7 as well. However:
She tried, and she failed.

And finally
She tried; she failed.

As commonplace as it may sound, I would add: never judge any sentence as it stands by itself. Depending on the mood and style you want to set, anything might be OK in the right context.

A: I'm always struggling with over-comma-fication, meaning my own inclination to put in too many. [en- and em-dashes are one (lazy) way around this proclivity, as is paying close attention to how the expository pieces in The New Yorker are punctuated.]
I'd choose sentence #3 in your first sampling. It segregates "as expected" (which is incidental to the main event) but otherwise keeps tried and and together, drawing the reader forward and so letting the sentence flow.
By the same token, I think sentence #7 in the second set is preferable. It's a straight-forward exposition wherein the comma's extraneous. If you really wanted to build up tension, use ellipses or an en-dash -before or after the "and"- to signal as much instead.

A: In regards to example 6, the comma would be more appropriate if the next word was "but":

She tried, but failed.

In your example "She tried and failed", if the sentence continues after the "and failed" you very often see parentheses around the "and failed" also:

She tried (and failed) to...

A: It depends on the style, complexity, mood/insinuation/stress and standard of the whole thing. My use (colloquially, semi-formal and formal) would be 2 or 5 or 2 without the second comma.
Same with the second choice, it depends if you are insinuating/stressing that she was expected to try, or expected to fail, or it is just noted.


text:
Q: How to use Sage to find irreducible representation of symmetric group I am not sure if Sage can be used to find the irreducible representations of the symmetric group.
For example:
For $g = (123)$, we have $$D(a)=\begin{bmatrix}0&0&1\\ 1 & 0 & 0\\0 & 1 & 0\end{bmatrix}$$
One decomposition is the following:
$$D(a)=\begin{bmatrix}1&0&0\\ 0 & -\frac{1}{2} & -\frac{\sqrt{3}}{2}\\0 & \frac{\sqrt{3}}{2} & -\frac{1}{2}\end{bmatrix}$$
so we get two irreducible representations: $$1,\ \  \begin{bmatrix}  -\frac{1}{2} & -\frac{\sqrt{3}}{2}\\ \frac{\sqrt{3}}{2} & -\frac{1}{2}\end{bmatrix}$$
The answer is not unique since we can pick another similar transformation with different basis.
Can Sage be used to do this for the general case $S_n$? If not, any software can make it?

A: Symmetric group representations are implemented in Sage.
See the documentation:

*

*Sage documentation: symmetric group representations


text:
Q: Reproduction of Stata design of a national multi-staged sample in R survey package I have a 3-stage stratified sampling design of a national survey. I have code in Stata to do the weighting, but I struggle to reproduce it with the R survey package.
Sampling design is the following. The sampling universe is stratified into 49 strata. Within each stratum, sampling is done in three stages. (1) PPS selection of a precinct. (2) Random systematic selection of a household using random route technique, basically. (3) Random systematic selection of a respondent within a household using some Kish technique modification.
There is a Stata weighting code that is assumed to perform well:
svyset precinct [pweight=indwt], strata(strt) fpc(npsu) singleunit(certainty) || qnum, fpc(nhh) || _n, fpc(nhhm)
Here, precinct are precinct numbers, strt are strata codes. Population sizes used for FPC are npsu - number of PSUs (i.e. precincts) per stratum, nhh - numbers of households in PSUs, nhhm - number of eligible members in a household. qnum - questionnaire unique numbers, which are the same for both selected households and respondents.
I try to reproduce it with the following R code.
library(survey)
options("survey.lonely.psu" = "certainty")
svy_data <- svydesign(ids = ~precinct + qnum,
                      strata = ~strt,
                      weights = ~indwt,
                      fpc = ~npsu + nhh,
                      data = data)

I can't do fpc = ~npsu + nhh + nhhm, because then I get an error:

Error in popsize < sampsize : non-conformable arrays.

Resulting confidence intervals through confint(svymean(...)) in R don't match  Stata confidence intervals through tabout ado package. They are close, but shifted a bit in R.
My assumption is that I should do something that Stata's _n term does, and get a 3-stage design instead of a 2-stage one. How could I do that?
Or is there anything else I can try to improve in my R code to match Stata?


text:
Q: Backup sqlite to external storage and make it unaccesible/encrypt it on Android I have found examples on how to backup and restore and app's sqlite database from the external storage.
Since the file is a sqlite database, copying it to a computer and using a sqlite browser app, allows to view its content.
My question is: is there a way to do something with the database backup file in order to not have it accessible to other apps?


text:
Q: How can I serialize this JSON using Jackson annotations? I have the following JSON :
{
    fields : {
            "foo" : "foovalue",
            "bar" : "barvalue"
    }
}

I wrote a pojo as follows :
public class MyPojo {

    @JsonProperty("fields")
    private List<Field> fields;

    static class Field {
        @JsonProperty("foo") private String foo;
        @JsonProperty("bar") private String bar;

        //Getters and setters for those 2
}

This fails obviously, because my json field "fields" is a hashmap, and not a list.
My question is : is there any "magic" annotation that can make Jackson recognize the map keys as pojo property names, and assign the map values to the pojo property values ?
P.S.: I really don't want to have my fields object as a...
private Map<String, String> fields;

...because in my real-world json I have complex objects in the map values, not just strings...
Thanks ;-)
Philippe

A: Ok, for that JSON, you would just modify your example slightly, like:
public class MyPojo {
  public Fields fields;
}

public class Fields {
  public String foo;
  public String bar;
}

since structure of objects needs to align with structure of JSON. You could use setters and getters instead of public fields of course (and even constructors instead of setters or fields), this is just the simplest example.
Your original class would produce/consume JSON more like:
{
  "fields" : [
    {
      "foo" : "foovalue",
      "bar" : "barvalue"
    }
  ]
}

because Lists map to JSON arrays.


text:
Q: How to make a background server request? I need to make an android app which can request some data from the server and post that again to another server. I want to perform all this even when app is closed.

A: you can run your app in Background using Services
For data sending you can study about AsyncTask Here


text:
Q: Why kivy changes all widgets at once I create a subclass of the Button widget. While handling on_touch_down event I want to change button text for debugging purpose. When I click a single button, all the buttons of this type got their text changed. Why? How to change text on a clicked button only?
Button class:
class FigureButton(Button):
    def on_touch_down(self, touch):
        super(FigureButton, self).on_touch_down(touch)
        self.text = 'Clicked'

.kv file portion:
FigureButton:
    text: '1'
FigureButton:
    text: '2'

Thanks!

A: on_touch_down doesn't do collision checking, so that widgets can interact with touches outside their area. You can add 'if self.collide_point(*touch.pos): ... before your code (and indent your additions into the if statement) to have this work as you expect.
As you have discovered, the on_press event/method does do collision checking. This is normally a better way to interact with buttons anyway.


text:
Q: Weird memory leak with core data Instruments detect a memory leak:
(Leaked Object= "__NSCFString")

This is my code:
-(NSArray*)loadAllPages{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"Page" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
                                        initWithKey:@"date" ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    [sortDescriptor release];

    NSError *error = nil;
    myArray = [[NSArray alloc ]initWithArray:[[context executeFetchRequest:fetchRequest error:&error]autorelease]];

    [fetchRequest release];
    if (myArray == nil)
        NSLog(@"%@",error);
    return myArray;
}

The line where leak is pointed at is initialization of myArray.
If I do not return myArray, this leak doesn't occur, so this is strange for me.

A: If you are not using ARC.
Change return myArray; with return [myArray autorelease];
You are returning an allocated object from your method, the ownership of that object is still with the method, in such scenarios you should return an auroreleased object and retain it on the receiving side. Then the ownership of that object will be with the calling method.

A: In this line
myArray = [[NSArray alloc ]initWithArray:[[context executeFetchRequest:fetchRequest error:&error]autorelease]];

the square brackets are slightly wrong.
The autorelease is sent to the result of [context executeFetchRequest:...], not to the allocated array.
[context executeFetchRequest:...] returns an autoreleased array. Sending autorelease to that array is an error. And myArray is allocated, but not released in your code.
The Xcode static analyzer also reports this as an error:

I assume that you meant
myArray = [[[NSArray alloc] initWithArray:[context executeFetchRequest:fetchRequest error:&error]] autorelease];

which would result in an autoreleased array myArray.


text:
Q: Gradient of Rayleigh's Quotient in complex case Giving the Rayleigh's Quotient in the real case ($x\in\mathbb{R}^n$, $A\in M_n(\mathbb{R})$): $$R_A(x)=\frac{^t{x}Ax}{^t{x}x}$$ I know how to obtain the gradient, which is: $$\nabla R_A(x)=\frac{2}{^t{x}x}(Ax-R_A(x)x)$$
This involves calculating such things as: $$\frac{\partial}{\partial{x_i}}(x_1,...,x_i,...,x_n)$$
But now, in a complex case ($x\in\mathbb{C}^n$, $A\in M_n(\mathbb{C})$), we have: $$R_A(x)=\frac{^t{\overline{x}}Ax}{^t{\overline{x}}x}$$
So, this would involve calculating: $$\frac{\partial}{\partial{x_i}}(\overline{x_1},...,\overline{x_i},...,\overline{x_n})$$
and, as far as I remember, an expression such as $\frac{\partial{\overline{z}}}{\partial{z}}$ doesn't exist... Does it mean that the gradient of Rayleigh' Quotient doesn't exist in the complex case ? Or, am I missing something ?


text:
Q: How to Update VS2019 to a version other than latest? On March 09, 2021 Microsoft released VS2019 16.8.7 and 16.9.1
https://learn.microsoft.com/en-us/visualstudio/releases/2019/release-notes-v16.8#16.8.7
https://learn.microsoft.com/en-us/visualstudio/releases/2019/release-notes#16.9.1
I have currently installed 16.8.6 and would like to upgrade to 16.8.7, but the installer only offers the upgrade to 16.9.1!
How can I upgrade to 16.8.7 ?

A: Just use that link - https://learn.microsoft.com/en-us/visualstudio/releases/2019/history#release-dates-and-build-numbers
There you can choose specific installer for any version VS 2019 as you want .


text:
Q: Filtering an object array with another array I am having a filtering problem..
objArray is the array that needs to be filtered.
selectedNames is an array that contains the values that I want to find in objArray.
I need to fetch all objects that have one or more values from selectedNames in their "names" property (an array) .
The output I am trying to get is :
let result = [{names:["A","B","C","D"]},
              {names:["A","B"]},
              {names:["A","D"]}
             ]

Here is a simplified version of my code:
let objArray = [{names:["A","B","C","D"]},
                {names:["C","D"]},
                {names:["C","D","E"]},
                {names:["A","B"]},
                {names:["A","D"]}
               ]

let selectedNames = ["A","B"]

result = this.objArray .filter(obj => {
   return this.selectedNames.includes(obj.names)
}

My code seems to work fine if names attribute was a single value and not an array. But I can't figure out how to make it work on an array.
Any help is more than welcome

A: You could do something like this. Filtering the array based on the names property having 'some' value be included in the selectedNames array.
...
objArray.filter(obj => obj.names.some(name => selectedNames.includes(name)));

[Edit] As @RadicalTurnip pointed out, this is not performant if the selectedNames is too large. I would suggest that you use an object. E.x
...
const selectedNamesMap = selectedNames.reduce((p,c) => ({...p, [c]: true}), {});
objArray.filter(obj => obj.names.some(name => selelectedNamesMap[name]));

Overkill, but if the arrays are really large (millions of elements) then you are better of using regular for loop and not array methods.

A: This result is not performant scaled up, but I don't know that there is any way to ensure that it will be performant unless you know more information (like the names are already sorted).  That being said, you just missed one more piece of logic.
result = this.objArray.filter(obj => {
  let toReturn = false;
  obj.names.forEach(name => {
    if (this.selectedNames.includes(name))
      toReturn = true;
    };
  };
  return toReturn;
};


text:
Q: How can I use periods in MailMerge Field Names? I have a List of Merge Field names passed into my application, along with a Word Document. The Merge Fields include periods and underscores, in the form "Here.Is.An.Example.Merge_Field". These separators are required - the characters may be able to be changed, but they cannot be removed altogether.
Several of these Merge Fields are contained within a datasource that is created for the document. The datasource has no data save for the merge field names - the merge itself takes place elsewhere in the process.
I attach the document to the datasource as below:
WordApplication.MailMerge.OpenDataSource(DataFilePath);

This loads the Merge Fields into the menu as desired, but all the periods have gone. I now have "HereIsAnExampleMerge_Field", which causes issues at other points in my application.
How can I prevent Word from removing these characters?

A: I don't think you can, because AFAIK the merge field names are modified to be valid bookmark names, which have certain restrictions
(See, e.g. What are the limitations for bookmark names in Microsoft Word? for a discussion, except in this case I think Word will insert an "M" before an initial "_". Plus, names over 40 characters long are mangled to produce unique names.)
So what to do really depends on what issues you are facing.
You can retrieve the fieldnames that Word actually uses (i.e. its mangled names) from either ActiveDocument.MailMerge.DataSource.DataFields or .FieldNames. AFAIK these are in the same sequence as the fields in the data source, even though Word sometimes rearranges fields for display in the Edit Recipients dialog (e.g., it sorts field names that it considers to be address field names in a certain sequence). So that should allow you to match its field names with the originals.
Alternatively, if your code needs to insert { MERGEFIELD } fields in a Mail Merge Main Document and knows the sequence of the fields in the data source, you can use field numbers (1 for the first field retrieved by Word etc.), e.g. { MERGEFIELD 1 }. But beware, as I have never seen that facility documented anywhere by Microsoft.


text:
Q: Do I have to hard code the values adjusted by an IBInspectable property? If I use IBInspectable to adjust the properties and get live updates on Xcode, do I then I have to hard code the values I chose or will the adjusted values be compiled with the final version?
I mean, suppose I use IBInspectable to adjust the border of a view to 10. Should I hardcode that border to 10 or will this value adjusted on a box on Interface Builder be the value that will be compiled for that border?
For a moment the nave IBInspectable got me as something just for inspection...

A: The values you set in Interface Builder for the IBInspectable properties will be saved in the storyboard and will be set on your object when it is instantiated by the storyboard process.  You don't need to set those values through code.
This is one of the benefits of IBInspectable - you can manipulate and configure your own custom objects in Interface Builder in the same was as you can with the 'in-built' objects such as UILabel and UITextField


text:
Q: Get min and max elements for 2 corresponding series in pandas Suppose I have 2 Series in pandas:
from datetime import datetime, timedelta
import pandas as pd
d = datetime.now()
index = [d + timedelta(seconds = i) for i in range(5)]
a = pd.Series([1,4,5,7,8], index = index)
b = pd.Series([2,3,6,7,8], index = index)

What is the best way to get min/max values for corresponding index elements.
Like:
min_func(a, b): [1,3,5,7,8] (for given index)
max_func(a, b): [2,4,6,7,8]

The only functions I could find in the documentation are min/max functions that return min/max within the series, while .apply function doesn't take the index argument.
Is there a better way to implement that without manual series iteration or some arithmetic magic (like min_func: a * (a < b) + b * (b <= a), max_func: a * (a > b) + b * (b >= a) )
Thanks

A: Combine the series into a frame which automatically aligns by the index
In [51]: index
Out[51]:
[datetime.datetime(2013, 8, 26, 18, 33, 48, 990974),
 datetime.datetime(2013, 8, 26, 18, 33, 49, 990974),
 datetime.datetime(2013, 8, 26, 18, 33, 50, 990974),
 datetime.datetime(2013, 8, 26, 18, 33, 51, 990974),
 datetime.datetime(2013, 8, 26, 18, 33, 52, 990974)]

In [52]: a = pd.Series([1,4,5,7,8], index = index)

In [53]: b = pd.Series([2,3,6,7,8], index = index)

In [54]: a
Out[54]:
2013-08-26 18:33:48.990974    1
2013-08-26 18:33:49.990974    4
2013-08-26 18:33:50.990974    5
2013-08-26 18:33:51.990974    7
2013-08-26 18:33:52.990974    8
dtype: int64

In [55]: b
Out[55]:
2013-08-26 18:33:48.990974    2
2013-08-26 18:33:49.990974    3
2013-08-26 18:33:50.990974    6
2013-08-26 18:33:51.990974    7
2013-08-26 18:33:52.990974    8
dtype: int64

In [56]: df = DataFrame({ 'a' : a, 'b' : b })

In [57]: df
Out[57]:
                            a  b
2013-08-26 18:33:48.990974  1  2
2013-08-26 18:33:49.990974  4  3
2013-08-26 18:33:50.990974  5  6
2013-08-26 18:33:51.990974  7  7
2013-08-26 18:33:52.990974  8  8

Min/Max
In [9]: df.max(1)
Out[9]:
2013-08-26 18:33:48.990974    2
2013-08-26 18:33:49.990974    4
2013-08-26 18:33:50.990974    6
2013-08-26 18:33:51.990974    7
2013-08-26 18:33:52.990974    8
Freq: S, dtype: int64

In [10]: df.min(1)
Out[10]:
2013-08-26 18:33:48.990974    1
2013-08-26 18:33:49.990974    3
2013-08-26 18:33:50.990974    5
2013-08-26 18:33:51.990974    7
2013-08-26 18:33:52.990974    8
Freq: S, dtype: int64

Index of min/max
In [11]: df.idxmax(1)
Out[11]:
2013-08-26 18:33:48.990974    b
2013-08-26 18:33:49.990974    a
2013-08-26 18:33:50.990974    b
2013-08-26 18:33:51.990974    a
2013-08-26 18:33:52.990974    a
Freq: S, dtype: object

In [12]: df.idxmin(1)
Out[12]:
2013-08-26 18:33:48.990974    a
2013-08-26 18:33:49.990974    b
2013-08-26 18:33:50.990974    a
2013-08-26 18:33:51.990974    a
2013-08-26 18:33:52.990974    a
Freq: S, dtype: object


text:
Q: Trimmed input value displayed in div I have an unknown number of input boxes with unknown IDs. I would like to be able to click on an input box and have a trimmed version of the value populate a div.
JSFiddle
My code all works as expected once the input field is edited, but I want to have the value displayed on first click/focus.
This is the JS function I wrote.
JS
$('input').each(function() {
        var $tthis = $(this),
            defaultValue = $tthis.val();

 defaultValue = defaultValue.substring(keyed.indexOf("|") + 1);
 defaultValue = defaultValue.substring(0, defaultValue.length - 2)
        $("#target").html(defaultValue);

});

HTML
<input
id='thistext$index'
type='text'
onclick='this.select();'
onfocus="
document.getElementById('show_hide').style.display='block';
document.getElementById('show_hide2').innerHTML = 'Copy this text into the wiki, it will display as: ';"
onblur="document.getElementById('show_hide').style.display='none';" value='&#91[http://www.example.com/$dirArray[$index]|$dirArray[$index]]]' />

A: I restructured your code a bit from the first fiddle.
I threw out all inline javascript and it's handlers, the onFocus, onBlur, onClick and replaced with jQuery equivalents and I think I got what you wanted.
I used jQuery's on() method to do the same thing which cleaned up the HTML a lot.
Then I used a function within show() to trigger a few other functions.
This could be more procedural but I thought it was nice and clean.
And lastly I extracted out the trimming and substringing to it's own function so that you can reuse it later on.
A fiddle here and the code below:
$('input').on('click', function() {
    var $input = $(this);
    $('#show_hide').show(function(){
        $('#show_hide2').text('Copy this text into the wiki, it will display as:');
        var text = trimInputValue($input);
        $('#target').text(text);
    });
});

function trimInputValue($input) {
    var text = $input.val();
    text = text.substring(text.indexOf("|") + 1);
    text = text.substring(0, text.length - 2);
    return text;
}

$('input').on('focusout', function() {
    $('#show_hide').hide();
});

Now you might wonder where your select() went off to.
Don't worry, just include it in your on('click', function(){ select(); }); and it should execute.


text:
Q: Use Groovy to Sort XML File Is there a way I can sort an xml file base on certain attributes with Groovy?
Here's my xml
<List>
    <Person name="fff"/>
    <Person name="ggg">
        <PhoneNum>
            <AreaCode>555</AreaCode>
            <Number>1234567</Number>
        </PhoneNum>
    </Person>
    <Person name="eee"/>
    <Person name="ccc"/>
    <Person name="jjj"/>
    <Person name="ddd">
        <PhoneNum>
            <AreaCode>555</AreaCode>
            <Number>7654321</Number>
        </PhoneNum>
    </Person>
    <Person name="aaa"/>
    <Person name="bbb"/>
    <Person name="ttt"/>
</List>

and I want the output to be
<List>
    <Person name="aaa"/>
    <Person name="bbb"/>
    <Person name="ccc"/>
    <Person name="ddd">
        <PhoneNum>
            <AreaCode>555</AreaCode>
            <Number>7654321</Number>
        </PhoneNum>
    </Person>
    <Person name="eee"/>
    <Person name="fff"/>
    <Person name="ggg">
        <PhoneNum>
            <AreaCode>555</AreaCode>
            <Number>1234567</Number>
        </PhoneNum>
    </Person>
    <Person name="jjj"/>
    <Person name="ttt"/>
</List>

I've looked into XMLSlurper but I can't quite seem to figure out how to do this.

A: Here's a modification to @dmahapatro's answer that preserves the nested node structure.
import groovy.xml.MarkupBuilder

String xml = '''
<List>
    <Person name="fff"/>
    <Person name="ggg">
        <PhoneNum>
            <AreaCode>555</AreaCode>
            <Number>1234567</Number>
        </PhoneNum>
    </Person>
    <Person name="eee"/>
    <Person name="ccc"/>
    <Person name="jjj"/>
    <Person name="ddd">
        <PhoneNum>
            <AreaCode>555</AreaCode>
            <Number>7654321</Number>
        </PhoneNum>
    </Person>
    <Person name="aaa"/>
    <Person name="bbb"/>
    <Person name="ttt"/>
</List>
'''

def rootNode = new XmlParser().parseText(xml)
rootNode.children().sort(true) {it.attribute('name')}
new XmlNodePrinter().print(rootNode)

Here's what's going on:

*

*Using XmlParser instead of XmlSlurper generates nodes that can be printed using XmlNodePrinter.

*The children of the node are sorted by name using sort {it.attribute('name')}

*The true attribute to sort mutates the underlying list, which reorders the child nodes.

*The XmlNodePrinter prints the re-sorted xml document to standard out.

A: I think there can be a groovier way than this. But this should work on a Friday. :-)
import groovy.xml.MarkupBuilder

def xml = '''<List>
    <Person name="fff"/>
    <Person name="eee"/>
    <Person name="ccc"/>
    <Person name="jjj"/>
    <Person name="aaa"/>
    <Person name="bbb"/>
    <Person name="ttt"/>
</List>'''

def rootNode = new XmlSlurper().parseText(xml)

def writer = new StringWriter()
def mkp = new MarkupBuilder(writer)
mkp.List{
    rootNode.Person.@name.list()*.toString().sort().each{
        Person(name: it)
    }
}

println writer


text:
Q: Why is such function continuous? Can anyone help me see why the function $f: \bar{\mathbb{Q}} \to \mathbb{Q} $ where $\bar{\mathbb{Q}}$ denotes the set of algebraic numbers,
$$f(x)=\begin{cases}1,&\ \text{if the real part of $x$ is greater than $\pi$, and}\\
0,&\ \text{otherwise.}\end{cases}$$
is continuous?

A: Note that $z \in \mathbb C$ is algebraic over $\mathbb Q$ if and only if $Re(z), Im(z)$ are algebraic over $\mathbb Q$. Now, to show that $f$ is continuous we need only show that $f^{-1}[0]$ and $f^{-1}[1]$ are closed. Indeed, $f^{-1}[1]$ is precisely those $z \in \overline{\mathbb Q}$ such that $Re(z) > \pi$. Since $Re(z)$ is algebraic and $\pi$ is transcendental, $Re(z) > \pi$ iff $Re(z) \geq \pi$. Now, let $S \subseteq \mathbb C$ be defined as $\{z \in \mathbb C : Re(z) \geq \pi\}$. The map $Re: \mathbb C \longrightarrow \mathbb R$ is just projection, so it is continuous. Thus, $S = Re^{-1}[[\pi, \infty)]$ is closed. Furthermore, as discussed, $S \cap \overline{\mathbb Q} = f^{-1}[1]$. Then as $S$ is closed in $\mathbb C$, $S \cap \overline{\mathbb Q} = f^{-1}[1]$ is closed in the subspace topology.
$f^{-1}[0]$ consists of $Re(z) \leq \pi$ so essentially the same argument shows $f^{-1}[0]$ is closed. Hence, $f$ is continuous.


text:
Q: CreateMethodInfo : Could not load file or assembly Previously in a loop I had a working call to CreateMethodInfo, and the method signature had no parameters.
Now I've changed this (for performance reasons) so that the method in question has parameters, and it's failing with the following error message now:

Could not load file or assembly
  'file:///C:\Users\me\AppData\Local\Temp\qz5wsaeb.dll' or one of
  its dependencies.

I'm calling this:
var method = CreateMethodInfo(script, "Methods", "GetValue");
method.Invoke(null, new object[] { control });

The value of script:
public class Methods
{
    public static void GetValue(Control control)
    {
        // During runtime this part is dynamic and can change
        control.Location = new System.Drawing.Point(165, 70);
        control.Size = new System.Drawing.Size(204, 107);
    }
}

I can't see what I'm doing wrong. Basically I want to invoke the method and pass a parameter, in this case a Control.
Edit
CreateMethodInfo:
public static MethodInfo CreateMethodInfo(string script, string className, string methodName)
{
    using (var compiler = new CSharpCodeProvider())
    {
        var parms = new CompilerParameters
        {
           GenerateExecutable = false,
           GenerateInMemory = true,
           ReferencedAssemblies = { "System.Drawing.dll","System.Windows.Forms.dll" }
        };
        return compiler.CompileAssemblyFromSource(parms, script)
            .CompiledAssembly.GetType(className)
            .GetMethod(methodName);
    }
}

A: Adding the names of referenced assemblies to the CompilerParameters structure, as you are correctly doing, is not enough for the compiler to be able to resolve the reference to Control in
public static void GetValue(Control control)

You must either add the referenced assembly name with a using statement to the script, like this:
    using System.Drawing;
    using System.Windows.Forms;

    public class Methods
    {
        public static void GetValue(Control control)
        {
    ...

or else, if you prefer, qualify symbol references with the defining namespace:
    public class Methods
    {
        public static void GetValue(System.Windows.Forms.Control control)
        {
    ...

Incidentally, you can troubleshoot this kind of issue yourself by inspecting the Errors property on the object that CompileAssemblyFromSource returns.


text:
Q: People content varies from Contacts I have Outlook 2013 as one of my work installed applications.
I have two issues with my People and my Contacts list (that is available under Address Book)

*

*The two lists have differences, even after I deleted all the content under People(which also cleansed Contacts) and started again. I presume these lists should always be the same?

*I am also unable to add the details of particular people from the GAL by the normal methods I use (but most people do work).

*

*right clicking a person in an address field and selecting Add to Outlook Contacts.

*right clicking a person in the Address Book in the GAL, and selecting Add to Contacts.

I would like to provide more details, but there isn't anything else I can think of other than my Outlook Connectivity settings below.


text:
Q: Valgrind is not showing line numbers despite of providing -g flag in make file I have a postgresql extension shared library to test under valgrind. I have added the -g option in the make file which creates this shared library after compiling the functions involved in it.
CC = gcc
override CFLAGS += -g -Wall

After make and make install, I run make installcheck under valgrind server which tests my shared library through sql commands written in the test script. This is my valgrind command:
valgrind -s --suppressions=postgresql-11.2/src/tools/valgrind.supp --leak-check=full --trace-children=yes --track-origins=yes --read-var-info=yes postgres -D /usr/local/pgsql/data --config-file=/usr/local/pgsql/data/postgresql.conf

The output which I am getting from valgrind is :
==11903== Syscall param socketcall.sendto(msg) points to uninitialised byte(s)
==11903==    at 0x4E4EBAD: send (in /usr/lib64/libpthread-2.26.so)
==11903==    by 0x6AF914: pgstat_send.part.4 (in /usr/bin/postgres)
==11903==    by 0x6B2022: pgstat_report_stat (in /usr/bin/postgres)
==11903==    by 0x6B23AB: pgstat_beshutdown_hook (in /usr/bin/postgres)
==11903==    by 0x702894: shmem_exit (in /usr/bin/postgres)
==11903==    by 0x70290D: proc_exit_prepare (in /usr/bin/postgres)
==11903==    by 0x702987: proc_exit (in /usr/bin/postgres)
==11903==    by 0x722F0F: PostgresMain (in /usr/bin/postgres)
==11903==    by 0x6B9004: ServerLoop (in /usr/bin/postgres)
==11903==    by 0x6B9E35: PostmasterMain (in /usr/bin/postgres)
==11903==    by 0x47F051: main (in /usr/bin/postgres)
==11903==  Address 0x1ffeffe7dc is on thread 1's stack
==11903==  in frame #2, created by pgstat_report_stat (???:)
==11903==  Uninitialised value was created by a stack allocation
==11903==    at 0x6B1ED0: pgstat_report_stat (in /usr/bin/postgres)

==11903== HEAP SUMMARY:
==11903==     in use at exit: 1,256,022 bytes in 437 blocks
==11903==   total heap usage: 1,287 allocs, 850 frees, 6,189,096 bytes allocated
==11903==
==11903== 22 bytes in 1 blocks are definitely lost in loss record 65 of 194
==11903==    at 0x4C2FDFB: malloc (vg_replace_malloc.c:309)
==11903==    by 0x5855BD9: strdup (in /usr/lib64/libc-2.26.so)
==11903==    by 0x6B9610: PostmasterMain (in /usr/bin/postgres)
==11903==    by 0x47F051: main (in /usr/bin/postgres)
==11903==
==11903== 29 bytes in 1 blocks are definitely lost in loss record 69 of 194
==11903==    at 0x4C2FDFB: malloc (vg_replace_malloc.c:309)
==11903==    by 0x5855BD9: strdup (in /usr/lib64/libc-2.26.so)
==11903==    by 0x85EFB4: set_pglocale_pgservice (in /usr/bin/postgres)
==11903==    by 0x47ECF4: main (in /usr/bin/postgres)
==11903==

As you can see, I am not getting proper line numbers in the stack trace. Why is that? What am I missing?
Any help would be greatly appreciated.
The postgres version which I am using is :
PostgreSQL 11.2 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 7.2.1 20170915 (Red Hat 7.2.1-2), 64-bit


text:
Q: Unable to cast object of type 'System.Collections.Generic.List`1[Item]' to type 'ItemList' For some reason, my boss likes to create custom types to represent a generic list  (even in most cases where his custom type has no members!  I think he's just lazy and doesn't like to type the List or something but to me this is lame and is causing me many headaches per the issue below.
Point in case:
public class ItemnList : List<Item>
{
    public Personalization FindById(int id)
    {
        ...blahblah blah, this is really an extension method that should be elsewhere
    }

}

Consequently, when I'm using a standard List (mabye I hate his custom class and like to use plain .NET types like they should be used), OR maybe I'm using a LINQ expression like below, I always run into casting problems even though the custom type is inheriting from that List
private ItemList someMethod(ItemList itemList)
{
    ...
    itemList = (ItemList)items.Where(x => x.ItemType != ItemType.Car && x.ItemType != ItemType.Truck).ToList();

    return itemList;
    ....
}

A: As Grzenio points out, you can't use ToList() and cast, however you could create your own extension method to create an instance of the derived type from a sequence:
public static TDerived CreateFromEnumerable<TDerived, T>(this IEnumerable<T> seq) where TDerived : List<T>, new()
        {
            TDerived outList = new TDerived();
            outList.AddRange(seq);
            return outList;
        }

So for your example you would do:
ItemList outList = itemList
    .Where(x => x.ItemType != ItemType.Car && x.ItemType != ItemType.Truck)
    .CreateFromEnumerable<ItemList, Item>();

A: Unfortunately ToList() will return a normal list, and not ItemnList, so you can't cast it. I don't really see a reasonable workaround, it would probably be better to encapsulate the List in ItemnList, instead deriving from it.


text:
Q: How to extract data from postgresql jsonb object in multiple levels I have a table that contains json data with an 'signatures' array occurring multiple levels:
{
  "packet": "data"
  "signatures": [
    { "packet": "data" },
    { "packet": "data" }
  ]
  "userIds": [
    {
      "packet": "data",
      "signatures": [
        { "packet": "data" },
      ]
    }
  ]
}

I know how to get all the signatures that occur on one level, i.e. all the signatures directly on the "packet" or all the signatures on all "userIDs":
select string_agg(signature->'packet'->>'data', ',')
from keys,
jsonb_array_elements(doc->'userIDs') userID,
jsonb_array_elements(userID->'signatures') signature

But is there a way to extract all the signatures without knowing on which level they are?


text:
Q: Dell bluetooth keyboard stops working for a couple of seconds on Ubuntu 20.04 I have Ubuntu 20.04.3 LTS and Bluetooth keyboard Dell WK717, the problem is that it stops working from time to time. It happens when the keyboard is idle for some short amount of time, it doesn't type immediately after I press a button but it requires me to press several times a button to make it work again.
I had a similar problem with the Dell mouse but than I've got a logitech one and this problem doesn't occur any longer.
UPD the problem persists also with dells' universal usb
UPD2 The problem is due to low charge of batteries.However, keyboard didn't signal low charge.

A: In terminal do
echo "options btusb enable_autosuspend=N" | sudo tee /etc/modprobe.d/btusb.conf
Reboot and see if disabling autosuspend fixes the issue


text:
Q: 4 standard type of objects in JSF This is a question that I saw in some interview.
Which are the 4 standard type of objects in JSF ?
Three are under the direct control of the JSF programmer, one is under the control of JSF – but under the indirect control of the JSF programmer.
Any idea which they are ?
Thanks
JK

A: There are 4 scopes in JSF 2

*

*Request: The bean is created on every request-response action.

*View: The bean is alive while you keep in the same view in the navigator.

*Session: The bean is alive since its creation until the browser session expires (HTTP session).

*Application: The bean is alive since the application is deployed until the application is undeployed.

More info:

*

*How to choose the right bean scope?


text:
Q: Module category I am currently reading about module categories and have been not very successful. In this case a module category is a category with an action of a monoidal category. (more information on nLab)
In specific my task is to find a module category $M$ over $G$-vect ($G$-graded vector spaces), s.th. the Functor category $Fun(M, M) \cong G$-rep (representations of $G$), where G is a group.
Unfortunately I don't have any clue how that could look like.
It would already be helpful if someone knew any example of a module category! (So that I can get a feeling for what this category could look like)
If anyone knows more about this specific example, it would be of course even better!
Thanks in advance!


text:
Q: PHP: How to check the season of the year and set a class accordingly I have a website which uses 4 different background images for the header area which visually corresponds to the season of the ear (summer, autumn etc.) – for the summer timeframe I use one image, for the autumn – another one and so on. The problem is that I have to manually change those images once the season of the year changes.
Maybe someone could show how would it be possible to check the current time / season of the year and then print the corresponding classes to the header element (.summer, .autumn etc.)?
I assume using PHP would be the way.

A: As I stated in the comments, this is an interesting challenge because the dates of seasons are always changing and different depending what part of the world you live in. Your server time and the website visitor's local time are also a factor.
Since you've stated you're just interested in a simple example based on server time and you're not concerned with it being exact, this should get you rolling:
// get today's date
$today = new DateTime();
echo 'Today is: ' . $today->format('m-d-Y') . '<br />';

// get the season dates
$spring = new DateTime('March 20');
$summer = new DateTime('June 20');
$fall = new DateTime('September 22');
$winter = new DateTime('December 21');

switch(true) {
    case $today >= $spring && $today < $summer:
        echo 'It\'s Spring!';
        break;

    case $today >= $summer && $today < $fall:
        echo 'It\'s Summer!';
        break;

    case $today >= $fall && $today < $winter:
        echo 'It\'s Fall!';
        break;

    default:
        echo 'It must be Winter!';
}

This will output:
Today is: 11-30-2016
It's Fall!

A: One might consider this necromancy, Yet when I was looking for ready to use method that does this I've got here.
Mister Martin answer was good assuming the year will not changes, here is my snippet, might be useful for someone in future:
private function timestampToSeason(\DateTime $dateTime): string{
    $dayOfTheYear = $dateTime->format('z');
    if($dayOfTheYear < 80 || $dayOfTheYear > 356){
        return 'Winter';
    }
    if($dayOfTheYear < 173){
        return 'Spring';
    }
    if($dayOfTheYear < 266){
        return 'Summer';
    }
    return 'Fall';
}

cheers!

A: I know this question is quite old, but none of the answers on this or any of the other questions that ask this question account for timezones, hemispheres, and different calendars in the same function, and since this came up first when I Googled for this, here's what I ended up writing myself.
If you want to get fancier you could calculate the actual Astronomical dates, geolocate the user, internationalize the season name output, etc., but that's beyond the scope of this question anyway.
function get_season( string $date = '', string $timezone = 'Europe/London', string $hemisphere = 'northern', string $calendar = 'meteorological' ): string {

    // Create the calendars that you want to use for each hemisphere.
    $seasons = array(
        'northern' => array(
            'astronomical'   => array(
                'spring' => '03-20', // mm-dd
                'summer' => '06-21',
                'autumn' => '09-22',
                'winter' => '12-21',
            ),
            'meteorological' => array(
                'spring' => '03-01',
                'summer' => '06-01',
                'autumn' => '09-01',
                'winter' => '12-01',
            ),
        ),
        'southern' => array(
            'astronomical'   => array(
                'spring' => '09-22',
                'summer' => '12-21',
                'autumn' => '03-20',
                'winter' => '06-21',
            ),
            'meteorological' => array(
                'spring' => '09-01',
                'summer' => '12-01',
                'autumn' => '03-01',
                'winter' => '06-01',
            ),
        ),
    );

    // Set $date to today if no date specified.
    if ( empty( $date ) ) {
        $date = new \DateTimeImmutable( 'now', new \DateTimeZone( $timezone ) );
    } else {
        $date = new \DateTimeImmutable( $date, new \DateTimeZone( $timezone ) );
    }

    // Set the relevant defaults.
    $seasons        = $seasons[ strtolower( $hemisphere ) ][ strtolower( $calendar ) ];
    $current_season = array_key_last( $seasons );
    $year           = $date->format( 'Y' );

    // Return the season based on whether its date has passed $date.
    foreach ( $seasons as $season => $start_date ) {

        $start_date = new \DateTimeImmutable( $year . '-' . $start_date, new \DateTimeZone( $timezone ) );

        if ( $date < $start_date ) {
            return $current_season;
        }

        $current_season = $season;
    }

    return $current_season;
}

Usage
// Pass nothing to get current meteorological season in the Northern hemisphere.
echo get_season();

// Pre-PHP 8.0, though I've only tested it on 7.4.
echo get_season( 'December 18', 'Europe/London', 'northern', 'astronomical' );

// After PHP 8.0 you can use named arguments to skip the defaults.
echo get_season( 'December 18', calendar: 'astronomical' );

Outputs
winter // Current season.
autumn
autumn // If PHP 8.0, otherwise error.

I personally like that it lets me add calendars if I discover something unique, like for example, the beginning of Summer is always the first Thursday after April 18th in Iceland.


text:
Q: Processing all existing data of a single collection in Cloud Firestore using Firestore Triggers In Firebase RTDB when adding a child_added listener, it gets called for every child that already exists, which is handy if you want to migrate data out of Firebase or do some schema migration. I can't find find evidence you can do the same using Firestore triggers. What's the recommended way to process all existing documents and any new documents in a Firestore collection?
I can think of two ways:

*

*Try out whether attaching a Firestore trigger works, so you can do a live migration on some data.

*Create some manually triggered Cloud Function that iterates over a collection and invokes another function for each collection.

If this question is too general, we have one collection that is structured in some way and needs to be written to PostgreSQL in a differently structured way at some point.

A: On the client side or some node process you can set a observer for the collection and also check what type of changes did happen on it. Here is an example:
const observer = db.collection('cities')
  .onSnapshot(querySnapshot => {
    querySnapshot.docChanges().forEach(change => {
      if (change.type === 'added') {
        console.log('New city: ', change.doc.data());
      }
      if (change.type === 'modified') {
        console.log('Modified city: ', change.doc.data());
      }
      if (change.type === 'removed') {
        console.log('Removed city: ', change.doc.data());
      }
    });
  });

The first query snapshot contains added events for all existing documents that match the query.
With using Firebase cloud functions you can use onWrite to be notice about every change in the collection:
const functions = require('firebase-functions');

exports.myFunction = functions.firestore
  .document('my-collection/{docId}')
  .onWrite((change, context) => { /* ... */ });

And if you would like to get only elements that are added you can use the onCreated trigger:
exports.createUser = functions.firestore
    .document('users/{userId}')
    .onCreate((snap, context) => {
      // Get an object representing the document
      // e.g. {'name': 'Marie', 'age': 66}
      const newValue = snap.data();

      // access a particular field as you would any JS property
      const name = newValue.name;

      // perform desired operations ...
    });

Using the Firebase cloud functions you get noticed only in real time. Everything that is already in the collection would not appear on the onCreate and in onWrite only if it gets changed or deleted.


text:
Q: Widget wrong grid size I've written a widget which is supposed to be 4x2 homescreen blocks. It's minheight and minwidth, with accordance to the current "App Widget Design Guidelines" page are
android:minWidth="250dp"
android:minHeight="110dp"

And a padding is applied from dimens.xml if the system version is below Ice Cream Sandwich
On my Nexus 4 (xhdpi, Jellybean 4.2.1), this widget is 4x2. On an emulator (hdpi, Gingerbread 2.3.3), this widget is 4x2. On my Nexus 7 however (hdpi, Jellybean 4.2.1), the widget is 3x2. I can't for the life of me figure out why or how to fix it. Any thoughts?

A: Lars Vogel writes in this Home Screen Widget tutorial that:

As a calculation rule you should define the size of the widget with the formula: ((Number of columns / rows)* 74) - 2. These are device independent pixels and the -2 is used to avoid rounding issues.

Edit: apparently Vogel got it from the old Widget API documentation (scroll down past mid page to see reference).
Based on this measurement, for a 4 cells width and 2 cells height, use 294 x 146 dip:
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="294dip" android:minHeight="146dip"
    android:updatePeriodMillis="0" android:initialLayout="@layout/some_layout" />


text:
Q: HTML mail using vb net will show as plain text and attachments are also ignored I'm building a windows forms app on vb .net, one of them send a HTML email. I can send the email and the html tags and css wont show which means the program "Knows" it is html and not just a string. BUT I'm only getting the chunks of text (on any p, h or a tag) as plane text with no format one after another.
I tried to use EASendmail from Nuget packages with the same result.
I searched on google and here for the problem without any success.
Here is what I have
 Dim message As New MailMessage()
 Dim fromAdd As MailAddress = New MailAddress("my mail here")

With message

            .[To].Add("somebody email here")
            .Subject = "TEST"
            .From = fromAdd
            .Priority = MailPriority.Normal
            .IsBodyHtml = True
            .BodyEncoding = System.Text.Encoding.UTF8
            .Body = " <!DocType HTML>....the rest of the html code with the css..."

end with

Dim smtpClient As New SmtpClient("smtp.live.com")
            With smtpClient
                .EnableSsl = True
                .Port = 587
                .UseDefaultCredentials = False
                .Credentials = New System.Net.NetworkCredential("mymail@somewhere.com", "password")
                .DeliveryMethod = SmtpDeliveryMethod.Network
                .Send(message)
                .Dispose()
            End With
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

now I expected a nice looking html email, which I saved as a html page and it shows just fine when opened in chrome.
for some reason I only getting the text paragraphs on it as plane text without any formatting, any attachment is also ignored, the image files attached to the email but the mail just wont show them neither.

A: Here's how you can go about the HTML email
Dim mensaje01 As String = "<!docType HTML><html> ...and the rest of your html code here...</html>

Now, be sure to replace any quote marks with ' (DO NOT USE WORD OR WORPAD OR NOTEPAD TO DO IT... It will make some funny version of it and it won't work... took me 2 days to realize that. By the way notepad+ can replace all at once and it fine)
 Dim VISTAHTML As AlternateView = AlternateView.CreateAlternateViewFromString(mensaje01, Nothing, System.Net.Mime.MediaTypeNames.Text.Html)
 Dim VISTATEXT As AlternateView = AlternateView.CreateAlternateViewFromString(mensaje01, Nothing, System.Net.Mime.MediaTypeNames.Text.RichText)

    Try

        Dim MENSAJE As MailMessage = New MailMessage
        MENSAJE.AlternateViews.Add(VISTAHTML)
        MENSAJE.AlternateViews.Add(VISTATEXT)

        MENSAJE.From = New MailAddress("your email address here")
        MENSAJE.To.Add("the recipient email")
        MENSAJE.Subject = "SUBJECT"
        Dim MISMTP As SmtpClient = New SmtpClient("the smptp client you are using")
        MISMTP.EnableSsl = True
        MISMTP.Port = "587"
        MISMTP.Credentials = New Net.NetworkCredential("yor email address", "your password")

        MISMT.Send(MENSAJE)

        MsgBox("ENVIADO")
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

If you need to add images to the email you can do it like this:
Dim image As LinkedResource = New LinkedResource("image.jpg", System.Net.Mime.MediaTypeNames.Image.Jpeg)
Image.ContentId = "TEMP1"
VISTAHTML.LinkedResources.Add(image)

Then you use the CID on your img tag to bring the image and you are done!


text:
Q: MongoDB Aggregate Facet & Group I have the following dataset which I am looking to summarize within a report. Basically I am looking for status count (by status) and group for each key. I have tried several ways to completing this to no avail.
[
  {
    "_id": ObjectId("635f808302d5f6cb7c293298"),
    "key": "scientific",
    "custom_properties": [
      {
        "namespace": "common metadata",
        "key": "status",
        "scope": "public",
        "value": "To be uploaded",
        "inherited": null
      },
      {
        "namespace": "common metadata",
        "key": "version",
        "scope": "public",
        "value": "1.0",
        "inherited": null
      },
      {
        "namespace": "common metadata",
        "key": "start date",
        "scope": "public",
        "value": "1642550400000",
        "inherited": null
      },
    ]
  },
  {
    "_id": ObjectId("635f809d02d5f6cb7c29353c"),
    "key": "contracts",
    "custom_properties": [
      {
        "namespace": "common metadata",
        "key": "status",
        "scope": "public",
        "value": "To be reviewed",
        "inherited": null
      },
      {
        "namespace": "common metadata",
        "key": "version",
        "scope": "public",
        "value": "",
        "inherited": null
      },
      {
        "namespace": "contracts",
        "key": "expiry date",
        "scope": "public",
        "value": "",
        "inherited": null
      },
      {
        "namespace": "common metadata",
        "key": "start date",
        "scope": "public",
        "value": "",
        "inherited": null
      },
    ]
  },
  {
    "_id": ObjectId("635f80a002d5f6cb7c293588"),
    "key": "contracts",
    "custom_properties": [
      {
        "namespace": "common metadata",
        "key": "status",
        "scope": "public",
        "value": "To be uploaded",
        "inherited": null
      },
      {
        "namespace": "common metadata",
        "key": "version",
        "scope": "public",
        "value": "",
        "inherited": null
      },
    ]
  }
]

and I am looking to Group and Facet, I am uncertain as to which to complete first.
The desired output should summarize the status count and group by key, and should look similar to the following...
[
 {
  scientific: [{
    'To be reviewed': 0,
    'To be uploaded': 1
  }],
  contracts: [{
    'To be reviewed': 1,
    'To be uploaded': 1
  }],
}
]

NOTE: both the keys and status values are dynamic. I.e. we could introduce a new status, and there will be several keys introduced over time.

A: You can do this with the following pipeline:
All this requires is a couple of $group stages to count, then some structure manipulation to get the required output
db.collection.aggregate([
  {
    $group: {
      _id: {
        key: "$key",
        statusVal: {
          "$getField": {
            "field": "value",
            "input": {
              "$arrayElemAt": [
                {
                  $filter: {
                    input: "$custom_properties",
                    cond: {
                      $eq: [
                        "$$this.key",
                        "status"
                      ]
                    }
                  }
                },
                0
              ]
            },

          }
        }
      },
      sum: {
        $sum: 1
      }
    }
  },
  {
    $group: {
      _id: "$_id.key",
      types: {
        $push: {
          k: "$_id.statusVal",
          v: "$sum"
        }
      }
    }
  },
  {
    $group: {
      _id: null,
      root: {
        $push: {
          k: "$_id",
          v: {
            "$arrayToObject": "$types"
          }
        }
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: {
        "$arrayToObject": "$root"
      }
    }
  }
])

Mongo Playground


text:
Q: create anonymous token API GITHUB I search how I can have a anonymous token for github API. I have found the personnel API, and my script work, but my script is in Javascript for a website ( so very unsecure for my account ).
Do you Know, how I can have an anonymous token, or if I need create a new account on github just for this ?
( i have a student account on github, and I can access to the developer program )

A: I spoke with a human github API, and I understand how it's work .
For make an anonymous token, you need just a token scopelless, in the scope list of this token, don't select any scope.
For test go https://api.github.com/user/keys?access_token=
without scope "read:public_key", you see an error, with scope, you see all your public key, with details
Edit ( thx jasonrudolph ) : it's not really an anonymous token, if we check : https://api.github.com/user/?access_token= , you can see master account information for this token


text:
Q: Is it possible to choose an arbitrary target class when moving instance method in IntelliJ IDEA? IntelliJ Idea allows to move method of class to another class (Refactor -> Move or F6). But it seems that a target class can be chosen only from a limited subset of classes whose objects are encapsulated into a source class.
E.g.
Source class:
    private ProductRepository productRepository;
    private UserService userService;
    private GooglePlayManager googlePlayManager;
    private AndroidPurchasesDBService db;
    private Analytics analytics;

Move Instance Method popup:

Is there a way to pick up an arbitraty target class?


text:
Q: filter html by span tag inside td in datatables I have an external dropdown form which have a values of correct and incorrect, whenever incorrect is chosen a ajax post will run and will generate a span inside td for incorrect values. What I need is that datatables should filter out incorrect by checking span inside td.
HTML:
<select id="filter">
 <option value="correct">Correct</option>
 <option value="incorrect">Incorrect</option>
</select>

//Data Tables

Word

Cat

Dog

Dogr

JS:
$(document).ready(function(){
   var dtTable = $('#data').dataTable( {
    "sDom": '<"H"lr>t<"F"ip>',
    "bSort": false,
    "bAutoWidth": false,
    "iDisplayStart": 0,
    "iDisplayLength": 25,
    "bProcessing": true,
    "sPaginationType": "full_numbers",
    "bJQueryUI": true,
            "aoColumns": [
                     {"sType": "string"},
         {"sType": "string"},
                     {"sType": "string"}
        ]
});

  $("#filter").change(function(){
     //Ajax Post request to check spelling and will insert span on misspelled words
     dtTable.fnFilter('span');
  });
});

On #filter change, when incorrect is chosen it should only filter rows with span class wrong-spelling


text:
Q: React-Bootstrap Form.Label opens file explorer when clicked on Good afternoon, hopefully everyone is doing fine. My application has a couple of forms that show up in popup modals.
I'm using React-Bootstrap for just about everything and I just realized today that every time you click on a <Form.Label> that my "Windows File Explorer" opens up as if I was trying to INPUT a file. Obviously I am NOT trying to input a file, here's an example of my code:
<Form.Group controlId="formCreate">
  <Row>
    <Col>
      <Form.Label>Enter a Description</Form.Label>
    </Col>
    <Col>
      <Form.Control type="text" className="description" placeholder="Enter a Description (Optional)" />
    </Col>
  </Row>
</Form.Group>

As you can see here, it's a simple form group, on my application if I actually CLICK "Enter a Description" the file explorer pops up. I'm confused how that's a thing, considering it's NOT a:
<Form.File
   className="position-relative"
   required
   name="file"
   label="File"
   onChange={handleChange}
   isInvalid={!!errors.file}
   feedback={errors.file}
   id="validationFormik107"
   feedbackTooltip
/>

Has anyone seen this bug before? It happens for literally every <Form.Label> on my entire application and while it's not the end of the world (the user isn't clicking the label consistently), it is a bug and is annoying. I would appreciate any guidance with this issue.
Here is my package information:
"react-bootstrap": {
  "version": "1.0.0",
  "resolved": "https://registry.npmjs.org/react-bootstrap/-/react-bootstrap-1.0.0.tgz",
  "integrity": "sha512-Ep6ZNH6wL5m9bytOS6T9mjSz0YE1bEkc+uHItvenRcA3amr5ApkpKYzAWgdglhRPZHPvm+pnqs1z5IPwv/2UZw==",
  "requires": {
    "@babel/runtime": "^7.4.2",
    "@restart/context": "^2.1.4",
    "@restart/hooks": "^0.3.21",
    "@types/react": "^16.9.23",
    "classnames": "^2.2.6",
    "dom-helpers": "^5.1.2",
    "invariant": "^2.2.4",
    "prop-types": "^15.7.2",
    "prop-types-extra": "^1.1.0",
    "react-overlays": "^3.0.1",
    "react-transition-group": "^4.0.0",
    "uncontrollable": "^7.0.0",
    "warning": "^4.0.3"
  }

A: know am a late to this.
Replace your code with the below.
<Form.File
 className="position-relative"
 required
 name="file"
 label="File"
 onChange={(e) => handleChange(e)} <------make note of the change//
 isInvalid={!!errors.file}
 feedback={errors.file}
 id="validationFormik107"
 feedbackTooltip
/>


text:
Q: Why is my MySQL Full Text search not working? I'm using MySQL FullText search and It works, but I can't get the following result.
Ex:
SELECT * FROM countries WHERE MATCH (name)
     AGAINST ("Chinese*" IN BOOLEAN MODE);

It should give me the country record "China", but it doesn't work, any advice to make this function better/work?
My Full Code:
 protected function fullTextWildcards($term)
    {

        // removing symbols used by MySQL
        $reservedSymbols = ['-', '+', '<', '>', '@', '(', ')', '~'];
        $term = str_replace($reservedSymbols, '', $term);

        $words = explode(' ', $term);

        foreach($words as $key => $word) {
            /*
             * applying + operator (required word) only big words
             * because smaller ones are not indexed by MySQL
             */

            if(strlen($word) >= 3) {

                $words[$key] = '' . $word . '*';
            }
        }

        $searchTerm = implode( ' ', $words);

        return $searchTerm;
    }

    /**
     * Scope a query that matches a full text search of term.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param string $term
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeSearch($query, $term)
    {
        $columns = implode(',',$this->searchable);

        $query->whereRaw("MATCH ({$columns}) AGAINST (? IN BOOLEAN MODE)" , $this->fullTextWildcards($term));
        return $query;
    }

A: My Solution was breaking the words smaller:
if(strlen($word) >= 7){
                    $split_string = str_split($word, 4);

                    $join = implode( '*', $split_string);

                    $words[$key] = '' . $join . '*';
                }else{
                    $words[$key] = '' . $word . '*';
                }