text:
Q: Migrate a digital ID from Windows XP Our company has been issued circa 2012-2014 some confidential PDF documents that are locked with a "digital ID" (also called certificates, perhaps improperly). AFAIK only Adobe software knows how to decipher these documents when opened. That still works fine on the Windows XP machine that originally was used to view these documents. The doc opens normally (no password is asked) with Adobe Acrobat Reader XI under that XP machine, now virtualized. But when that's attempted on a modern machine without the digital ID installed, I get

A digital ID was used to encrypt this document but no digital ID is present to decrypt it

Even though I have a working method to view the documents on a modern machine thru virtualization, I'd want to extract the "digital IDs" on that machine and bring them to a modern one.
I used the MMC snap-in to view user certificates, found one, migrated it, and that solved the issue for a batch of documents issued 2014. But I could not find the "digital ID" for earlier documents. I think there is a certificate attribute to make it (conventionally) un-exportable, but my issue is I can't even find it.
Where/how should I look?

Update: Thanks to this answer and some dichotomy, I found that the three files C:\Documents and Settings\user\Application Data\Adobe\Acrobat\11.0\Security\lb.dat, lbi.dat, and lbk.dat (and no other file in that folder) are instrumental in the ability to open the documents that depend on the certificate that I'm trying to find. When one is removed, Acrobat Reader 11.0.23 prompts me with with a "Digital ID Authentication" dialog, showing the characteristics of the certificate necessary to open the document, when I dismiss that, I get the error message at the begining of that answer. When I open the same doc in a fresh install of Acrobat Reader 11.0.23 in another machine, I get the error message directly. And transporting the lb*.dat files does not cut it.
I tentatively conclude the certificate is somewhere else, and the lb*.dat contain some enabler/key rather than the certificate itself.

A: According to this document Digital ID's exist as file on your disk so you can try to find them, transfer to new machine, import and check if they work. Here is important part from the answer:

If you originally created the signature as a  PKCS#12 file, then it
should be easy to find that .pfx file in this location on Windows:
Local Disk>Users>username>AppData>Roaming>Adobe>Acrobat>DC>Security
Once that file is transferred, then use the Add ID function


text:
Q: Create dummy variable in R excluding certain cases as NA I have data that looks like this:
V1 V2
A  0
B  1
C  2
D  3
E  4
F  5
G  9

I want to create a dummy variable in R where 0 = {1},  1 = {2,3,4} and NA = {0,5,9}
Should be simple - can anyone help?

A: You can use dplyr::recode on a vector:
> V2
[1] 0 1 2 3 4 5 9

Specify the mapping, use a default for everything else:
> dplyr::recode(V2,`1` = 0, `2`=1, `3`=1, `4`=1, .default=NA_real_)
[1] NA  0  1  1  1 NA NA

A: We can convert V2 into a factor and adjust the levels according to our need.
df$dummy <- factor(df$V2)
levels(df$dummy) <- list(`0`=1, `1`=c(2, 3, 4), `NA` = c(0,5,9))

df
#  V1 V2 dummy
#1  A  0    NA
#2  B  1     0
#3  C  2     1
#4  D  3     1
#5  E  4     1
#6  F  5    NA
#7  G  9    NA

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to test and compare multiple versions of R functions for a package? I use unit tests via testthat for many of my simpler functions in R but where I have more complex functions combining simple functions and business logic.  I'd like to test the cumulative impact via a before and after view for a sample of inputs. Ideally, I'd like to do this for a variety of candidate changes.
At the moment I'm:

*

*Using Rmarkdown documents

*Loading the package as-is

*Getting my sample

*Running my sample through the package as-is and outputting table of results

*sourceing new copies of functions

*Running my sample again and outputting table of results

*Reloading package and sourceing different copies of functions as required

This has proven difficult due to some functions that sit in the package namespace still running the package versions of functions, making results unreliable unless I thoroughly reload all downstream dependencies of functions. Additionally, the mechanism is complex to manage and difficult to reuse.
Is there a better strategy for testing candidate changes in R packages?

A: I've reduced this issue by creating a sub-package in my impact analysis folder that contains the amended functions.
I then use devtools::load_all to load these new function versions up.
I can then compare and contrast results by accessing the originals via the namespace e.g. myoriginalpackage:::testfunction whilst looking at the new ones with testfunction

A: Maybe you can replace steps 5 and 7 with "Rcmd build YourPackage" on each version. Then with
install.packages("Path/To/MyPackage_1.1.tar.gz", type="source")

test the old version, and then replace 1.1 with 1.2


text:
Q: pixel perfect wordwrapping from hashmap that contains pixel width of characters I'm writing a plugin for an application that uses a custom font, i made a hashmap containing each character as the key and the width in pixels as value(including 1 extra pixel for between characters). but i'm still having trouble finding a solution that doesn't feel like i don't know what i'm doing :P i tried checking other questions, but they all seem to be about length of the line in characters, or using external jars to handle standard fonts.

*

*trailing whitespaces may be trimmed (optional).

*words that don't fit the line need to go to the next line.

*words that are bigger then an entire line should be split after the last character that can be on a line. (with only 112 pixels wide as linelength this should take in account that - a word might need to be splitted multiple times).

*splits should be joined with linebreaks in between.

*the input is a string with some existing linefeed characters.

*the max line length in pixels = 112.

if there is a better way to aproach this then a hashmap please don't mind ignoring that.
thanks for the help.

A: If you need to support only ASCII or ISO-8859-1 then a simple array of widths indexed by the binary character value would be a better choice. If you need to support Unicode then a Map is better since an array would be quite large and sparse (i.e. mostly empty).
Give the 112 pixel width, you must be writing this for an embedded display, so you probably don't care about hyphenation, splitting on syllables, and such niceties.  Depending on how many lines your display has you might want to consider setting a minimum threshold for splitting a word, say 25% of its width.  I.e. if you can't get at least 25% of the letters on the line, break the entire word to the next line and leave whitespace at the end of the previous line.  But that's an aesthetic decision that may not be a consideration given the limited space.


text:
Q: How to connect to remote weblogic JMS server? I have a jms server running on weblogic and I need another application running on another server (weblogic as well) to listen to JMS topics sent by the JMS server mentioned before. The fact is that I don't know how to do that. I mean, what do I need on the consumer application side? Thansk in advance.

A: I know it´s a little old, but could help other people trying to achieve the same.
First you need to enable Cross-Domain Security on both domains envolved on your JMS communication. Please see specific documentation here: https://docs.oracle.com/middleware/1221/wls/SECMG/domain.htm#SECMG402
For reading a message from a JMS resource, there are a ton of examples you can search online, but basically you should rely on Weblogic´s t3 protocol. Here is a relativelly recent example using Spring Boot: Connect to remote jms queue with Spring Boot


text:
Q: When pexpect.spawn is called, does execution of the spawned program start immediately? Are pexpect.spawn objects inactive until expect (or interact, send, etc) is called, or does the invoked process start immediately? For example:
import pexpect
process = pexpect.spawn("echo HELLO")
print ("Process created? Or run?")
process.expect("HELLO")

When the print statement occurs, has pexpect already run the echo command under the covers and is just holding off on letting it return until the expect call is processed? Or has nothing happened (echo hasn't run) until the first call to expect or similar?
Cheers

A: When passed a command, pexpect.spawn() forks and invokes the command immediately. The echo command in your example would have been run already.
This is implied in the spawn constructor documentation:

This is the constructor. The command parameter may be a string that
  includes a command and any arguments to the command. For example::
child = pexpect.spawn ('/usr/bin/ftp')
child = pexpect.spawn ('/usr/bin/ssh user@example.com')
child = pexpect.spawn ('ls -latr /tmp')

You may also construct it with a list of arguments like so::
child = pexpect.spawn ('/usr/bin/ftp', [])
child = pexpect.spawn ('/usr/bin/ssh', ['user@example.com'])
child = pexpect.spawn ('ls', ['-latr', '/tmp'])

After this the child application will be created and will be ready to
  talk to.

I've confirmed this by looking at the source code; the constructor calls _spawn() which is documented as follows:

This starts the given command in a child process. This does all the
  fork/exec type of stuff for a pty. This is called by __init__. If args
  is empty then command will be parsed (split on spaces) and args will be
  set to parsed arguments.


text:
Q: MySQL Query with Distinct on Two Different Columns I'm trying to build a query that will give me results that are distinct in two separate columns, user_name and year_taken.
If I have results of my current query that look like this. These are basically all of the tests taken.

user_name
test_taken
score
year_taken

Bob Smith
101
85
2020

Jan Jones
101
99
2020

Mike Jackson
101
54
2021

Bob Smith
201
74
2020

Mike Jackson
201
70
2020

Jan Jones
300
75
2020

Mike Jackson
300
55
2021

Bob Smith
301
95
2021

Mike Jackson
301
97
2022

I need to narrow it down to just one test per year, per user. So, the results I'd like to get look like this:

user_name
test_taken
score
year_taken

Bob Smith
101
85
2020

Jan Jones
101
99
2020

Mike Jackson
101
54
2021

Mike Jackson
201
70
2020

Bob Smith
301
95
2021

Mike Jackson
301
97
2022

So, I need one test per one user per year.
My query draws from a few different tables, but it boils down to
select user_name, test_taken, score, year_taken from ....

I'm just not sure how to base a distinct on another column as well.

A: You can use ROW_NUMBER(), as in:
select *
from (
  select *, row_number() over(partition by user_name, year_taken
                              order by score desc) as rn
  from t
) x
where rn = 1


text:
Q: Maximum number of integral roots in degree $d$ polynomial? Given $f(x_1,\dots,x_n)\in\mathbb Z[x_1,\dots,x_n]$ such that

*

*Each coefficient is bound in absolute value by $B$

*Degree of each variable in any monomial is bound by $d$

*Total degree is $d'$

*$f(x_1,\dots,x_n)$ is irreducible in $\mathbb Z[x_1,\dots,x_n]$
then what is the maximum number integral roots $(y_1,\dots,y_n)\in\mathbb Z^n$ it can have such that in a $\ell$ length cube?


text:
Q: Thin, non-resizable window borders are displayed incorrectly On my PC with Windows 7 SP 1, the borders of all non-resizable windows (for example all dialog boxes or the calculator) look like the left of the two images below. The border is far too thin and overlaps itself (look closely at the circled areas). The right image shows how it should look like, based on a web search.
All windows that have a resizable border look correct. Further research showed that the problem appears on all windows that lack the WS_BORDER window style. Adding that style manually on a window (with the SetWindowLongPtr function) makes the problem go away, although that window is then resizable, which is generally undesirable.
Has anyone ever seen this problem before or has any idea where to search for the problem?

A: Looks like your Border Padding setting has been turned WAY down.

Note in this picture it's set to "1", and the corners look exactly like your problematic ones.  By default this setting would be "4".
To get to the above window:

*

*Right-click desktop.

*Click Personalize.

*Click Window Color.

*Click Advanced Appearance Settings...


text:
Q: Reading and saving the full HTML contents of a URL to a text file Requirement:

To read HTML from any website say "http://www.twitter.com ".
Print the retrived HTML
Save it to a text file on local machine .

Code:
import java.net.*;

import java.io.*;

public class oddless {
    public static void main(String[] args) throws Exception {

        URL oracle = new URL("http://www.fetagracollege.org");
        BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));

        OutputStream os = new FileOutputStream("/Users/Rohan/new_sourcee.txt");

        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
    }
}

Code above retrieves the data, prints it on console and saves it to a text file but mostly it retrieves only half code (because of line space in html code). It does not save the code further.
Questions:

How can I save the full html code?
Are there any other alternatives?

A: I have used different approach but I received same output like you. Is not there problem on server side of this URL?
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://www.fetagracollege.org");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try {
    System.out.println(response1.getStatusLine());
    HttpEntity entity1 = response1.getEntity();
    String content = EntityUtils.toString(entity1);
    System.out.println(content);
} finally {
    response1.close();
}

It finishes with:

UPDATE: This Faculty of Engineering and Technology does not have well formed home page. This content is complete, your code works well. But commentators have right, you shall use try/catch/finally block.

A: I use this code whenever connecting to a website through Java
import java.io.*;
import java.net.*;

public class Connection
{
    public static void main(String[] args) throws Exception
    {
        new Connection();
    }
    public Connection() throws Exception
    {
        URL url = new URL("http://www.fetagracollege.org"); //The URL
        HttpURLConnection huc = connect(url); //Connects to the website
        huc.connect(); //Opens the connection
        String str = readBody(huc); //Reads the response
        huc.disconnect(); //Closes
        System.out.println(str); //Prints all output to the console
    }

    private String readBody(HttpURLConnection huc) throws Exception //Reads the response
    {
        InputStream is = huc.getInputStream(); //Inputstream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is)); //BufferedReader
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null)
        {
            response.append(line); //Append the line
            response.append('\n'); //and a new line
        }
        rd.close();
        return response.toString();
    }

    private HttpURLConnection connect(URL url) throws Exception //Connect to the URL
    {
        HttpURLConnection huc = (HttpURLConnection) url.openConnection(); //Opens connection to the website
        huc.setReadTimeout(15000); //Read timeout - 15 seconds
        huc.setConnectTimeout(15000); //Connecting timeout - 15 seconds
        huc.setUseCaches(false); //Don't use cache
        HttpURLConnection.setFollowRedirects(true); //Follow redirects if there are any
        huc.addRequestProperty("Host", "www.fetagracollege.org"); //www.fetagracollege.org is the host
        huc.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36"); //Chrome user agent
        return huc;
    }
}

The website ended with this, so I think the problem is server-side, as other websites work with this code (tested with twitter and google):
                            © fetaca 2011

A: for reading contents from an URL, you can use jsoup and then you can wright the contents using file handling concept(OutputStream out =....), so for reading by using jsoup:
String url = "URL"; // getting URL
Document doc = Jsoup.connect(url).get(); // getting content as document type
String line = input.toString(); // getting contents as String type

Now after having the content in string u can easily flush it into a file.
For this - you will require jsoup jars.
         - import 3(three) classes:
               import org.jsoup.Jsoup;
               import org.jsoup.nodes.Document;
               import org.jsoup.select.Elements;


text:
Q: java: package com.amazonaws.regions does not exist I am new to spring boot and aws java sdk. I am trying to use spring boot to send an email. Currently when i import any of these
import com.amazonaws.regions.Regions;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder;
import com.amazonaws.services.simpleemail.model.Body;
import com.amazonaws.services.simpleemail.model.Content;
import com.amazonaws.services.simpleemail.model.Destination;
import com.amazonaws.services.simpleemail.model.Message;
import com.amazonaws.services.simpleemail.model.SendEmailRequest;

I always get java: package com.amazonaws.regions does not exist error. I actually get a similar error for each of my imports.
Here is a sample of my dependencies in pom.xml file
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.temporal</groupId>
        <artifactId>temporal-sdk</artifactId>
        <version>1.0.7</version>
    </dependency>
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk-ses</artifactId>
        <version>1.12.98</version>
    </dependency>
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk-core</artifactId>
        <version>1.12.98</version>
    </dependency>
</dependencies>

I am currently using java sdk version is 17.0.1
Any suggestions would be really appreciated.

A: Both of those classes are contained in the aws-lambda-java-core jar, which is distributed separately from the AWS SDK. You can download it from maven central at the link above if you're not using maven/gradle/some other build system that can natively pull from maven central.


text:
Q: Code to delete a row in one Sub works but the other doesn't. "Delete Method of Range class failed" I have several sub's that use this exact same code, but this one returns
Run-time error '1004':
Delete method of Range class failed
drill.Range("48:48").Delete

in the others it works just fine, but in this one it does not
Sub Drill_Log_Undo()
'
'takes the last submited drill log and places it back into the submission     line
'

'Unprotects Drill Log
    Worksheets("Drill Log").Unprotect "Welcome1"

'Declares Variables
    Dim drill As Worksheet: Set drill = Worksheets("Drill Log")
    Dim start_joint As Range: Set start_joint = drill.Range("C48")

    Dim start_time As Range: Set start_time = drill.Range("F48")
    Dim info As Range: Set info = drill.Range("G48:S48")
    Dim tool_used As Range: Set tool_used = drill.Range("E48")
    Dim pass_type As Range: Set pass_type = drill.Range("D48")

    Dim x As Integer
        x = 0

'coppies the data to the submission line
        drill.Range("G37:S37").Value = drill.Range("G48:S48").Value 'to Multi
        drill.Range("G35:S35").Value = drill.Range("G48:S48").Value 'to Single

'changes the pass type to the previously entered pass type
        drill.Range("K10").Value = pass_type.Value

'determins whether the pass was multiple or single
    If drill.Range("F48") = Null Or drill.Range("F48") = "" Then

    'adds the end joint to the end joint submission cell
        drill.Range("C37").Value = drill.Range("C48")

    'counts the number of joints and removes them as it goes
        Do Until drill.Range("A59").Value = Null

            If start_time.Value = "" Or Null Then

Here is the line that throws the code
                drill.Range("48:48").Delete

End line
                x = x + 1
                Set start_time = drill.Range("F48")

            Else
                drill.Range("F37").Value = drill.Range("F48").Value

                Exit Do

            End If

        Loop

    'adds the last joint to the joint count and removes the joint row
        drill.Range("B37") = drill.Range("C48")
        x = x + 1
        drill.Range("48:48").Delete

Else

End If

'protects Drill Log
    Worksheets("Drill Log").Protect "Welcome1"

End Sub

I have tried different ways of declaring the variables, I have even tried specifically calling the code by calling the workbook and worksheet in the line.

A: Replace drill.Range("48:48").Delete with drill.Rows("48").EntireRow.Delete


text:
Q: $R$ is Noetherian/Artinian iff $I$ and $R/I$ are Let $R$ be any (i.e. not necessarily commutative or unital) associative ring, and let $I$ be a (two sided) ideal of $R$. Hence $I$ is a (nonunital) ring.
How can I prove: $R$ is a Noetherian/Artinian ring iff $I$ and $R/I$ are N/A rings?
We know (Atiyah & MacDonald, p.75, prp.6.3, the proof is the same for the noncommutative nonunital case) that if $0\rightarrow M'\rightarrow M \rightarrow M'' \rightarrow 0$ is an exact sequence of left $R$-modules, then $M$ is N/A iff $M'$ and $M''$ are N/A.
We have an exact sequence $0\rightarrow I\rightarrow R \rightarrow R/I \rightarrow 0$ of left $R$-modules, so $R$ is N/A iff $I$ and $R/I$ are N/A as $R$-modules. Now, since every $R$-submodule of $R/I$ is a $R/I$-submodule of $R/I$, and vice versa, we know that $R/I$ is N/A as a $R$-module iff it is such as an $R/I$-module, i.e. as a ring.
How can I prove that $I$ is N/A as a $R$-module iff it is such as an $I$-module?

A: What you claim isn't true. Consider the ring $R=\mathbb{R}^{\mathbb{N}}$ of sequences of real numbers, with component-wise operations. This ring isn't Artinian, since the ideals $$I_n=\{(a_i)_i\in R;\forall i\leq n\colon a_i=0\}$$ form a descending chain which doesn't stabilize. It also isn't Noetherian, since the ascending chain of ideals $$J_n=\{(a_i)_i)\in R;\forall i\geq n\colon a_i=0\}$$ also doesn't stabilize.
Now consider the ideal $J_1$. It is a field, since it is isomorphic as a ring to the reals, and is as such both Noetherian and Artinian.


text:
Q: How to delete the entire row in table using PHP? How to add a delete button to make the entire delete in Mysql DB. ?Below is the code and how can i delete the row using ID which is a primary key..
<?php
mysql_connect( 'localhost', 'off', 'off') or die(mysql_error());
mysql_select_db( 'myDB') or die(mysql_error());
$query=mysql_query( "select * from test") or die(mysql_error());
echo '
ID
                        First Name
                        Lsat Name
                        Email
                        Mobile
                        Gender
                        Action	';
while($row=mysql_fetch_array($query)) {
        echo '
'.$row[ 'id']. '	'.$row[ 'firstname']. '
                  '.$row[ 'lastname']. '	'.$row[ 'email']. '
                  '.$row[ 'mobile']. '	'.$row[ 'gender']. '
                  Delete
'; }
echo '
';
?>

A: Your link has to point to your php script with the id attached like this:
Delete

Everything after update.php? are GET-Parameters, search how to use $_GET in PHP and check for the action
Afterwards write a sql command that will delete the entry with the ID you've send via $_GET
Good luck, if you get stuck just edit your question with your aproach.

A: you could make the href a link to the same page with the id parameter (and a delete paremeter, if you want) passed in, then alter the page so that it checks to see if such a parameter has been passed and if so runs a query to delete that row before continuing and loading the page.

A: link your delete anchor to new page
Delete

and on delete.php
if(!empty($_GET['id'])) {
  $id= trim($_GET['id']);
  $query = mysql_query( "delete from test where id= '$id'");
  if($query) {
    // success redirect back to another page
  }
}


text:
Q: Using RANK in LOD: level of detail expressions cannot contain table calculations or the attr function in Tableau IF {FIXED [Customer Name]: (RANK(SUM(IF DATETRUNC('month', [Period])=#6/1/2019# THEN [Sales] END)))}<=10  THEN "Top 10"

ELSE "Others"

END

I want to find the Rank of each customer based on sum of sales for Jun 2019. I tried the above but got
level of detail expressions cannot contain table calculations or the attr function in Tableau
I need this Calculated Field to use as a Color Mark in a Stacked Bar Chart. In the Stacked Bar Chart, I want 1 color for the Top 10 Group of customers and another color for Other.
Thank you


text:
Q: RegExp for a comma-separated list of terms that finds terms not ending or starting with a character I have a String containing a comma-separated list of terms, like this:
term1, term2* ,term3*,term 4 , *term5, *term 6 , term 7*,* term 8

Each term may have leading or trailing whitespaces. These should be ignored. Each term may have whitespaces inside it.
I want to find all terms not starting or ending in an asterisk. In the list above, that would be "term1" and "term 4".
My failed attempts only led to me finding every term (just dropping the asterisks rather than ignoring the term) like in this example: https://regex101.com/r/9QjjJ5/1.
I've also tried achieving this with lookahead expressions and borders, but must be using them wrongly, as the found term is then just shortened or excluding spaces inside the term.

A: You can use the conventional method in Oracle to split the string and then use REGEXP_LIKE to filter.
WITH tab ( terms ) AS (
    SELECT
        'term1, term2* ,term3*,term 4 , *term5, *term 6 , term 7*,* term 8'
    FROM
        dual
) SELECT * FROM
(
SELECT DISTINCT
    TRIM(regexp_substr(terms,'[^,]+',1,level) ) term
  FROM
    tab
CONNECT BY
    regexp_substr(terms,'[^,]+',1,level) IS NOT NULL
    ) WHERE NOT REGEXP_LIKE (term,'^\*|\*$');


text:
Q: unable to use wifi on sony vaio duo 13 SVD13215CGB I'm new to linux and I've recently installed ubuntu 15.04 onto my 16GB thumbdrive. The issue is that it has no wifi capability.
lspci shows:
00:00.0 Host bridge: Intel Corporation Haswell-ULT DRAM Controller (rev 09)
00:02.0 VGA compatible controller: Intel Corporation Haswell-ULT Integrated Graphics Controller (rev 09)
00:03.0 Audio device: Intel Corporation Haswell-ULT HD Audio Controller (rev 09)
00:14.0 USB controller: Intel Corporation 8 Series USB xHCI HC (rev 04)
00:16.0 Communication controller: Intel Corporation 8 Series HECI #0 (rev 04)
00:1b.0 Audio device: Intel Corporation 8 Series HD Audio Controller (rev 04)
00:1f.0 ISA bridge: Intel Corporation 8 Series LPC Controller (rev 04)
00:1f.2 SATA controller: Intel Corporation 8 Series SATA Controller 1 [AHCI mode] (rev 04)
00:1f.3 SMBus: Intel Corporation 8 Series SMBus Controller (rev 04)

lshw:
  *-network DISABLED
       description: Ethernet interface
       physical id: 1
       logical name: wwan0
       serial: f2:71:5c:26:ae:cf
       capabilities: ethernet physical
       configuration: broadcast=yes driver=qmi_wwan driverversion=22-Aug-2005 firmware=WWAN/QMI device link=no multicast=yes

On my windows, I see that it uses a broadcom driver. I've tried the solution from cannot use wifi broadcom 802.11 alternative driver in ubuntu 15.04 , to no avail. There were no error message, it appears as if nothing has changed.
Btw, I have no internet access on my linux since it cannot connect to wifi, and I'm also using an ethernet to usb adapter for ethernet connection, which I do not have the driver (QF9700).
Would appreciate any help to get my wifi working.

A: Go to system > Administration > Additional Drivers/Hardware Drivers.
It will fetch the Broadcom drivers for your wifi. Select and install it. And Reboot the system

A: Not a solution for 15.04, but I've installed 14.04 instead and followed the answer from https://askubuntu.com/a/465502/424825 and got the wireless working.
Note: I mentioned that it's not a solution for 15.04 because none of the answers from the link that I've posted worked when I was still on 15.04.


text:
Q: Prove the norm property of random variables Let $X$ is a random variable. Then prove this inequality.
$$
\|X\|_{L^2} \leq \|X\|_{L^1}^{\frac{1}{4}}\|X\|_{L^3}^{\frac{3}{4}}
$$
I think maybe using Caushy-Schwarz is effective but was stucked on this proposition.
I'll give a great appropriciate you!

A: Write
$X^2=\lvert X\rvert^{1/2}\lvert X\rvert^{3/2}$ and apply Cauchy-Schwarz inequality in order to bound $\mathbb E\left[X^2\right]$. Then rearrange everything in terms of norms.


text:
Q: Landscape dimensiones being ignored I have an app where I enforce portrait on the Manifest:
<activity
            android:name=".MyActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:screenOrientation="portrait"
            android:label="@string/launcher_name"
            android:launchMode="singleTop"
            android:windowSoftInputMode="adjustPan">

</activity>

I do go landscape manually on certain conditions using:
 private fun triggerPortrait() {
        this@DashboardListActivity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
    }

    private fun triggerLandscape() {
        this@DashboardListActivity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
    }

Now I want certain elements to change their size when the orientation is landscape, so i have these two dimens.xml
dimens-land.xml
<resources>
    <dimen name="scoreboard_height">24dp</dimen>
</resources>

dimens-port.xml
<resources>

    <dimen name="scoreboard_height">16dp</dimen>
</resources>

However the switch between one and the other is not working at all, only the landscape one is being used. I guess this has to do with me enforcing portrait, but is there a way to fix this?

A: You could remove android:configChanges="orientation" from your manifest entry for MyActivity. But since that is not desirable and declaring a configuration with this attribute will prevent the activity from being restarted and instead, the activity remains running and its onConfigurationChanged() method is called and you are expected to note the configuration change and apply the logic that you would like instead in an override of onConfigurationChanged().
So here is how to accomplish doing it manually,
Copy those dimen values to one values/dimens.xml file that is globally available
values/dimens.xml
<resources>
    <dimen name="scoreboard_height_land">24dp</dimen>
    <dimen name="scoreboard_height_port">16dp</dimen>
</resources>

Update the orientation dimens to point to those values by its key (just in case you are re-using them else where in your app w/o all this logic and those areas do not break)
values-land/dimens.xml
<resources>
    <dimen name="scoreboard_height">@dimen/scoreboard_height_land</dimen>
</resources>

values-port/dimens.xml
<resources>
    <dimen name="scoreboard_height">@dimen/scoreboard_height_port</dimen>
</resources>

Override onConfigurationChanged to set the new height of the scoreboard
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    setHeightOfScoreboardViewBasedOnOrientation(newConfig.orientation);
}

public void setHeightOfScoreboardViewBasedOnOrientation(int orientation) {

    // change the id to match what you have in your xml (since i dont know it at the time of writing this)
    View myScoreboardView = findViewById(R.id.myScoreboardView);

    // get the layout params and set a new height, then set it back n the view
    ViewGroup.LayoutParams myScoreboardViewLayoutParams = myScoreboardView.getLayoutParams();
    if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
        myScoreboardViewLayoutParams.height = getResources().getDimensionPixelSize(R.dimen.scoreboard_height_land);
    } else if (orientation == Configuration.ORIENTATION_PORTRAIT) {
        myScoreboardViewLayoutParams.height = getResources().getDimensionPixelSize(R.dimen.scoreboard_height_port);
    }
    myScoreboardView.setLayoutParams(myScoreboardViewLayoutParams);

}

Note:
You could likely call the setHeightOfScoreboardViewBasedOnOrientation method from triggerPortrait and triggerLandscape methods with Configuration.ORIENTATION_PORTRAIT or Configuration.ORIENTATION_LANDSCAPE. But handling configChanges are more fun to learn, especially when your the activity is in the back stack and the orientation changes!!!


text:
Q: Custom tick is not displaying on edge/ie for checkbox I have tried several attempts to make the ticks the same as other browsers, but it is never the same for edge. Here is my fiddle:
http://jsfiddle.net/skb643ez/
This is the structure of my HTML:

Test
Somewhere (link)

<input type="checkbox" id="test">Test label

 Test
Somewhere (link)

the images on chrome is like this

meanwhile on Edge

I tried ms-checked or ms-expand display none, but this does nothing. I think it's because the webkit-appearance is not working. Is there any solution without using js or jquery? Thank you

A: i found the answer, we set the background and border-color to transparent for ::-ms-checked. https://jsfiddle.net/ycbvz4tl
input[type=checkbox]:checked {
   background-color: transparent;
   border-color: transparent;
   color: white;
}


text:
Q: Error when mapping dictionary values to dataframe I am trying to map some values from a dictionary to a dataframe. There is a column in the dataframe titled month where the values are from 1-12. My dictionary equates the numeric month value to its name, e.g. 1: January...
When I try in the code below I get NaN's and am not sure why.
dataframe
month_dict = {"1" : "January", "2" : "February", "3" : "March", "4" : "April", "5" : "May" , "6" : "June", "7" : "July", "8" : "August", "9" : "September", "10" : "October" ,"11" : "November","12" : "December"}

df['month'] = df['month'].map(month_dict)

I expect to have the month names substituted for the numerical equivalents but only return NaN's. Can anyone help please?

A: You need same type of data in column and in keys of dictionary.

Solution for matching strings:
Cast column to strings, because strings in keys in dictionary:
month_dict = {"1" : "January", "2" : "February", "3" : "March", "4" : "April",
              "5" : "May" , "6" : "June", "7" : "July", "8" : "August",
              "9" : "September", "10" : "October" ,"11" : "November","12" : "December"}

df['month'] = df['month'].astype(str).map(month_dict)

Solution for matching integers:
Convert keys in dictionary to integers:
month_dict = {int(k):v for k, v in month_dict.items()}
print (month_dict)
{1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June',
 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'}

df['month'] = df['month'].map(month_dict)


text:
Q: vue js paginating css not as expected in documentation I am implementing this paginator in vue:
https://github.com/lokyoung/vuejs-paginate
For some weird reason the layout doesn't work, this is what my paginator looks like:

I imported and used it:
import Paginate from 'vuejs-paginate'
Vue.component('paginate', Paginate);

I did this in my html page where I use the component:
<script src="https://unpkg.com/vuejs-paginate@latest"></script>

In my component I did:
<paginate
  :page-count="31"
  :page-range="10"
  :maring-pages="5"
  :click-handler="pageClickCallback"
  :container-class="'pagination'"
/>

Everything as the documentation stated, but no layout.
What is going wrong here?

A: It seems, like this package is not providing CSS at all, you need to style it by yourself - or - use bootstrap.css. See their demo -https://jsfiddle.net/lokyoung/u3u3nzns/ if you remove boostrap.css (in resources tab) - you will see, that there are no styles applied.
You can see classes used here - https://github.com/lokyoung/vuejs-paginate/blob/master/src/components/Paginate.vue

A: Current implementation of paginate expects classes from bootstrap.
Import css from bootstrap somewhere on the page
Then write below code to implement the paginate

<paginate
    v-model="page"
    :click-handler="changePage"
    :container-class="'pagination'"
    :page-count="10"
    :page-class="'page-item'"
    :next-class="'page-item'"
    :prev-class="'page-item'"
    :page-link-class="'page-link'"
    :prev-link-class="'page-link'"
    :next-link-class="'page-link'">
</paginate>

A: <paginate
   v-model="page"
   :page-count="20"
   :prev-text="'Prev'"
   :next-text="'Next'"
   :container-class="'pagination'"
>
</paginate>

.pagination {
  display: inline-block;
  padding-left: 0;
  margin: 20px 0;
  border-radius: 4px;
}
.pagination > li {
  display: inline;
}
.pagination > li > a,
.pagination > li > span {
  position: relative;
  float: left;
  padding: 6px 12px;
  margin-left: -1px;
  line-height: 1.42857143;
  color: #337ab7;
  text-decoration: none;
  background-color: #fff;
  border: 1px solid #ddd;
}
.pagination > li:first-child > a,
.pagination > li:first-child > span {
  margin-left: 0;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
}
.pagination > li:last-child > a,
.pagination > li:last-child > span {
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}
.pagination > li > a:hover,
.pagination > li > span:hover,
.pagination > li > a:focus,
.pagination > li > span:focus {
  z-index: 3;
  color: #23527c;
  background-color: #eee;
  border-color: #ddd;
}
.pagination > .active > a,
.pagination > .active > span,
.pagination > .active > a:hover,
.pagination > .active > span:hover,
.pagination > .active > a:focus,
.pagination > .active > span:focus {
  z-index: 2;
  color: #fff;
  cursor: default;
  background-color: #337ab7;
  border-color: #337ab7;
}
.pagination > .disabled > span,
.pagination > .disabled > span:hover,
.pagination > .disabled > span:focus,
.pagination > .disabled > a,
.pagination > .disabled > a:hover,
.pagination > .disabled > a:focus {
  color: #777;
  cursor: not-allowed;
  background-color: #fff;
  border-color: #ddd;
}
.pagination-lg > li > a,
.pagination-lg > li > span {
  padding: 10px 16px;
  font-size: 18px;
  line-height: 1.3333333;
}
.pagination-lg > li:first-child > a,
.pagination-lg > li:first-child > span {
  border-top-left-radius: 6px;
  border-bottom-left-radius: 6px;
}
.pagination-lg > li:last-child > a,
.pagination-lg > li:last-child > span {
  border-top-right-radius: 6px;
  border-bottom-right-radius: 6px;
}
.pagination-sm > li > a,
.pagination-sm > li > span {
  padding: 5px 10px;
  font-size: 12px;
  line-height: 1.5;
}
.pagination-sm > li:first-child > a,
.pagination-sm > li:first-child > span {
  border-top-left-radius: 3px;
  border-bottom-left-radius: 3px;
}
.pagination-sm > li:last-child > a,
.pagination-sm > li:last-child > span {
  border-top-right-radius: 3px;
  border-bottom-right-radius: 3px;
}


text:
Q: Push Notification, Reminder Calendar, EventKit implementation I have a TableViewController app in Xcode and I would like to add a remember calendar, a push notification functionality and alarms like the built-in Reminders app. Could you help me with the implementation and five me some tips?
I hope you could help me!

A: To implement EventKit the tutorial of Ray Wenderlich might be a starting point http://www.raywenderlich.com/64513/cookbook-making-calendar-reminder


text:
Q: Certificate verification failed. While docker image build in nodejs I am trying to create a docker image but getting error. it's failing on RUN apt-get update. code sample is given below.
# Update packages
RUN apt-get update
RUN apt-get install -y --no-install-recommends software-properties-common make g++
RUN apt-get install -y sudo
RUN apt-get install -y curl
RUN apt-get install -y git

Certificate verification failed: The certificate is NOT trusted. The certificate issuer is unknown.  Could not handshake: Error in the certificate verification.
I am also tried to put below code but facing same issue.
sudo apt-get clean

sudo apt-get install -y ca-certificates

sudo update-ca-certificates

sudo apt-get update

Anyone can help on this.


text:
Q: Grab the first snippet of php code with RegEx I have several files with 2 php snippets nested with
<? php code code code ?> <? php code code code ?>
How can I just grab the first snippet including tags with RegEx?
Thanks!

A: Let's say a.php has this:
<?php code code code ?> <?php mocode mocode mocode ?>

Now we can get the first result using this answer
<?php

function get_string_between($string, $start, $end){
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}

$fullstring = file_get_contents('a.php');

$tag1 = '<?php';
$tag2 = '?>';

echo $tag1.get_string_between($fullstring, $tag1, $tag2).$tag2;

It won't be visible in the regular browser window since it will be rendered as an invisible HTML tag, but the output will be visible in source as:

<?php code code code ?>

A: How about this?
$re = "/<\\?php(.+?)\\?>/i";
$str = "<?php some code in here ?> <?php some other code in here ?>";

preg_match($re, $str, $matches);
print_r($matches);

Results in this:

Array
(
    [0] => <?php some code in here ?>
    [1] =>  some code in here
)

You also should search and try by your own please!


text:
Q: Advanced SQL - how can I show running sum across multiple columns in a table in Oracle There is a need to generate a report, I did it using union but that is not the requirement.
Here is the problem statement:
The table contains sale information for items on some stores for year 2010 and 2011. I just want to display the sum of sales aggregated at item level, then store level then year level then grand total.
You can create sample data using these SQL statements:
create table item_sto_year_sale_t
(
     itemno integer,
     store varchar2(10),
     year integer,
     sale integer
);

insert into item_sto_year_sale_t values(1,'A',2010,100);
insert into item_sto_year_sale_t values(2,'A',2010,200);
insert into item_sto_year_sale_t values(3,'A',2010,300);

insert into item_sto_year_sale_t values(1,'B',2010,105);
insert into item_sto_year_sale_t values(2,'B',2010,205);

insert into item_sto_year_sale_t values(1,'A',2011,110);
insert into item_sto_year_sale_t values(2,'A',2011,220);
insert into item_sto_year_sale_t values(3,'A',2011,330);

insert into item_sto_year_sale_t values(1,'B',2011,115);
insert into item_sto_year_sale_t values(2,'B',2011,225);

commit;

Desired output is
    ITEMNO STORE            YEAR        SUM
---------- ---------- ---------- ----------
         1                              430   ---- sum(sales) in all stores for all years where itemno = 1
         2                              850   ---- sum(sales) in all stores for all years where itemno = 2
         3                              630   ---- sum(sales) in all stores for all years where itemno = 3
           A                           1260   ---- sum(sales) for all items for all years in store = 'A'
           B                            650   ---- sum(sales) for all items for all years in store = 'A'
                            2010        910   ---- sum(sales) for all items in all stores where year = 2010
                            2011       1000   ---- sum(sales) for all items in all stores where year = 2011

Any help on this is highly appreciated

A: You could use GROUPING SETS - It is pretty simple and straightforward than using multiple UNION
SELECT itemno
    ,store
    ,year
    ,SUM(SALE)
FROM item_sto_year_sale_t
GROUP BY GROUPING SETS((itemno), (store), (year));

Demo

A: select distinct to_char(itemno) , '' as STORE ,'' as YEAR,sum(sale)over(partition by itemno) as SUM from item_sto_year_sale_t
union
select distinct '', STORE, '',sum(sale)over(partition by STORE) from item_sto_year_sale_t
union
select distinct '', '', TO_CHAR(YEAR) ,sum(sale)over(partition by YEAR) from item_sto_year_sale_t


text:
Q: Calculated properties in pipeline expressions return null in jobs when passed using a PSObject I am trying to pass a hashtable of calculated properties in to a query, for use with Select-Object. It works when run in the console. I can confirm that the job is reading the hashtable as it lists the selected properties in the result, yet all of their values are null.
Note: I understand that I do not need to type cast these properties. I just demonstrating my issue.
If I run the following code (it looks weird, but there's actually a use case for this) the output contains my selected properties (from $globalConfig.SystemState.Processors.SelectProperties) but the calculated properties have a value of null, the only property that returns the correct value is name:
$globalConfig = @{
    PingAddress = '8.8.8.8';
    SystemState = @{
        Processors = @{
            Namespace = 'root\cimv2';
            ClassName = 'Win32_Processor';
            SelectProperties = 'name', @{ n = 'CpuStatus'; e = { [int]$_.CpuStatus }}, @{ n = 'CurrentVoltage'; e = { [int]$_.CurrentVoltage }};
        }
    }
}

$job = Start-Job -Name Processors -ArgumentList $globalConfig.SystemState.Processors -ScriptBlock {
    Try{
        $Response = @{
            State   = @();
            Error   = $Null
        }
        $Response.State = Get-CimInstance -ClassName $Args[0].ClassName | Select-Object $Args[0].SelectProperties -ErrorAction Stop
    }Catch{
        $Response.Error = @{Id = 2; Message = "$($Args[0].Target) query failed: $($_.Exception.Message)"}
    }

    Return $Response
}

$job | Wait-Job
$job | Receive-Job | ConvertTo-Json -Depth 3

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
119    Processors      BackgroundJob   Completed     True            localhost            ...

{
    "Error":  null,
    "State":  {
                  "name":  "Intel(R) Core(TM) i7-4710MQ CPU @ 2.50GHz",
                  "CpuStatus":  null,
                  "CurrentVoltage":  null
              }
}

Yet if I run the same job but with the same calculated properties hard coded (not passed to Select-Object using a PSObject), it works as expected (the values 1 and 12 are returned in the output):
$job = Start-Job -Name Processors -ArgumentList $globalConfig.SystemState.Processors -ScriptBlock {
    Try{
        $Response = @{
            State   = @();
            Error   = $Null
        }
        $Response.State = Get-CimInstance -ClassName $Args[0].ClassName | Select-Object Name, @{ n = 'CpuStatus'; e = { [int]$_.CpuStatus }},@{ n = 'CurrentVoltage'; e = { [int]$_.CurrentVoltage }}
    }Catch{
        $Response.Error = @{Id = 2; Message = "$($Args[0].Target) query failed: $($_.Exception.Message)"}
    }

    Return $Response
}

$job | Wait-Job
$job | Receive-Job | ConvertTo-Json -Depth 3

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
121    Processors      BackgroundJob   Completed     True            localhost            ...

{
    "Error":  null,
    "State":  {
                  "Name":  "Intel(R) Core(TM) i7-4710MQ CPU @ 2.50GHz",
                  "CpuStatus":  1,
                  "CurrentVoltage":  12
              }
}

How can I pass an object of calculated properties in-line to Select-Object while inside of a job?

A: It's a hashtable, not a psobject.  It looks like you can't pass scriptblocks into jobs.  They get turned into strings.
$globalConfig = @{
  PingAddress = '8.8.8.8'
  SystemState = @{
    Processors = @{
      Namespace = 'root\cimv2'
      ClassName = 'Win32_Processor'
      SelectProperties = 'name',
        @{ n = 'CpuStatus'; e = { [int]$_.CpuStatus }},
        @{ n = 'CurrentVoltage'; e = { [int]$_.CurrentVoltage }}
    }
  }
}

start-job -args $globalconfig.systemstate.processors {
  $list = $args[0].selectproperties
  $list[1].e.gettype()
  $list[2].e.gettype()
} | receive-job -wait -auto

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object
True     True     String                                   System.Object

It works with threadjobs.  Threadjobs don't serialize their objects.  In ps 5 you can download it from the powershell gallery.  https://www.powershellgallery.com/packages/ThreadJob  In ps 6 & 7, it comes with it.  It doesn't make a new process, and is faster anyway.  (It doesn't have the "-args" alias.)
start-threadjob -argumentlist $globalconfig.systemstate.processors {
  $list = $args[0].selectproperties
  $list[1].e.gettype()
  $list[2].e.gettype()
} | receive-job -wait -auto

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     ScriptBlock                              System.Object
True     True     ScriptBlock                              System.Object

Or use the static method [scriptblock]::create() like here:  How do I pass a scriptblock as one of the parameters in start-job

A: I wouldn't have found my answer without @js2010 pointing me in the right direction, thank you!
He/She is correct - for security reasons you cannot pass a scriptblock to a job, but as always with PowerShell there is a workaround.
I can get this to work by switching from Start-Job to Invoke-Command -asjob, but this requires WinRM to be runnning and configured, which isn't an option in production.
$globalConfig = @{
    PingAddress = '8.8.8.8';
    SystemState = @{
        Processors = @{
            Namespace = 'root\cimv2';
            ClassName = 'Win32_Processor';
            SelectProperties = 'Name',  @{ n = 'CpuStatus'; e = { [int]$_.CpuStatus }};
        }
    }
}

$ScriptBlock = {

    param(
        [Parameter(Mandatory=$True, Position=1)]
        [hashtable]$hashtable
    )

    Try{
        $Response = @{
            State = @();
            Error = $Null
        }
        $Response.State = Get-CimInstance -ClassName $hashtable.ClassName | Select-Object -Property $hashtable.SelectProperties -ErrorAction Stop
    }Catch{
        $Response.Error = @{Id = 2; Message = "$($data.Target) query failed: $($_.Exception.Message)"}
    }

    Return $Response
}

Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $globalConfig.SystemState.Processors -ComputerName . -AsJob

Name                           Value
----                           -----
Error
State                          @{Name=Intel(R) Core(TM) i7-4710MQ CPU @ 2.50GHz; CpuStatus=1}

This must be possible... so I'll keep testing solutions and will post anything I find here.
Update
I have this working, its a little dirty, but it meets the needs of the project. I simply construct the command using the hashtable outside of the job (as a string), pass the command string to the job as an argument and then run the command inside the job using Invoke-Expression:
$globalConfig = @{
    PingAddress = '8.8.8.8';
    SystemState = @{
        Processors = @{
            Target = 'Processors'
            Namespace = 'root\cimv2';
            ClassName = 'Win32_Processor';
            SelectProperties = [string]('"Name", @{ n = "CpuStatus"; e = { [int]$_.CpuStatus }}');
        }
    }
}

$Args = [PSCustomObject]@{
    Target = $globalConfig.SystemState.Processors.Target;
    Command = "Get-CimInstance -ClassName $($globalConfig.SystemState.Processors.ClassName) -ErrorAction Stop | Select-Object $($globalConfig.SystemState.Processors.SelectProperties) -ErrorAction Stop";
}

$job = Start-Job -Name Processors -ArgumentList $Args -ScriptBlock {

    Try{
        $Response = @{
            State = @();
            Error = $Null
        }
        $Response.State = Invoke-Expression -Command $args.Command
    }Catch{
        $Response.Error = @{Id = 2; Message = "$($Args.Target) query failed: $($_.Exception.Message)"}
    }

    Return $Response
}

$job | Wait-Job
$job | Receive-Job | ConvertTo-Json -Depth 3

{
    "Error":  null,
    "State":  {
                  "Name":  "Intel(R) Core(TM) i7-4710MQ CPU @ 2.50GHz",
                  "CpuStatus":  1
              },
    "PSComputerName":  "localhost",
    "RunspaceId":  "89f17de1-98b6-4746-a0ba-3e7c47294c61",
    "PSShowComputerName":  false
}


text:
Q: get a particular property value using Linq to C# I created a class with properties like this
public class Dependencies
{
    public string issueID { get; set; }
    public string status { get; set; }
    public int dependencyCheck { get; set; }
}

Now I created a method where i can use these properties.
private static void prepareIssuesList(string IssueKey, string JIRAtoken)
{
    Dependencies dpObj = new Dependencies();
    List<Dependencies> listObj = new List<Dependencies>();
    dpObj.issueID = IssueKey;
    dpObj.status = "open";
    dpObj.dependencyCheck = 0;
    listObj.Add(dpObj);

}

Now my question is, how to change the dependencyCheck property value. The prepareIssuesList() can called for multiple times. So i am adding multiple objects to Dependencies class. At certain point of time i want to change the dependencyCheck property value. How to do this. I think need to use the Linq to C#. ICan any one have any solution for this one?

A: I would do something along these lines:
public class Dependency
{
     public string IssueId { get; set; }
     public string Status { get; set; }
     public int DependencyCheck { get; set; }
}

public class DependencyManager
{
     public DependencyManager()
     {
          this.Dependencies = new List<Dependency>();
     }

     public List<Dependency> Dependencies { get; private set; }

     public void AddDependency(string issueId)
     {
         var dep = new Dependency();
         dep.IssueId = issueId;
         dep.Status = "open";
         dep.DependencyCheck = 0;

         this.Dependencies.Add(dep);
     }

     public void SetDependencyCheck(string issueId, int value)
     {
         var dep = this.FindDependencyByIssueId(issueId);
         dep.DependencyCheck = value;
     }

     public Dependency FindDependencyByIssueId(string issueId)
     {
         var dep = this.Dependencies.FirstOrDefault(d => d.IssueId.Equals(issueId));
         if(dep == null) throw new ArgumentException("Dependency not found", "issueId");
         return dep;
     }
}

Then somewhere in your code you could do:
var mgr = new DependencyManager();
mgr.AddDependency("ABC123");
mgr.AddDependency("ABC456");

//... some other stuff that makes sense

mgr.SetDependecyCheck("ABC123", 42);


text:
Q: Scheduling task with JobScheduler in Android causes UI freeze on app launch While trying to find out why my android app (java) was not responding for the first 2-3 seconds after launching (UI elements were loaded, apart from menu options, but I could not click anything), I located the delay being caused by the command that schedules a task with JobScheduler.
Basically I have an App class that extends Application, and there I do set a task with JobScheduler that would run every 30 minutes and perform some action (update some information and provide notification if their value was changed).
After creating the Builder containing all details for that task, i run the command scheduler.schedule(info) and by commenting it out I found out that this is the reason my app is unresponsive for 2-3 seconds after launching.
private void scheduleJob() {
    ComponentName componentName = new ComponentName(this, myRecurringTask.class);
    JobInfo info = new JobInfo.Builder(JOB_ID, componentName)
            .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
            .setPersisted(true)
            .setPeriodic(1800000)
            .build();
    JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
    scheduler.schedule(info);
}

I have tried running it in a Thread hoping that it'll run in background and not freeze the UI while running, among other similar practices, but I have yet to manage to run it in background and not have it affect the UI's responsiveness.
I suspect that the lifecycle of the App class might be the reason of that issue but I'm not experienced enough on being sure about it, or knowing how to overcome it.
Have anyone had any similar issue? And if so, how did you get it resolved?
Thank you

UPDATE 2020/02/18: As a workaround I am now checking first if job is already scheduled and only if it's not I go ahead and schedule again.
When I wrote the scheduling part, I saw in the documentation that it will overwrite the job if it already exists, so I did not worry about it, but since it's affecting app's performance, it makes sense to not do it every single time.
With that being said, I'm still looking for a better solution, that's just a workaround to limit the times it gets frozen, the UI still freezes every time job gets scheduled.

A: After a lot of frustration trying to overcome the issue I was experiencing, I did a more in-depth troubleshoot where I found out that the reason app freezes is that the first job run is running right when I schedule it.
It makes sense but I never thought of it being the issue.
I have made a new question on my quest to overcome that new issue, being able to skip the first job run...
JobScheduler - How to skip first job run of periodic job?


text:
Q: scoping: get all instances of specific type in current file xtext Following to my question:
here
I am trying to customize the scoping. I want that in scope of 'Predicate' in my language some of objects will be visible in the scope, types like 'typeDef'.
Predicate:
    'predicate' name=ID ('(' params=TypedParamList ')')?
    (':' body=TemporalExpression TOK_SEMI)
    | ('{' body=TemporalExpression '}');

TypeDef:
    'type' name=ID '=' type=VarType TOK_SEMI;

Here is some example of my language:
type
  move = {left, right};

predicate stop(move m1, move m2) :
  m1=left and m2=right;

It's not recognize left and right.(can't resolve reference)
I tried something like this:
            val allContentsCurrFile  = EcoreUtil2.eAllOfType(context,TypeDef)
            val allContentsCurrFile2  = EcoreUtil2.getAllContentsOfType(context,TypeDef)

I putted this as parameters to the Scopes.scopeFor method (in addition to the params of Predicate) and this isn't worked for me. I don't know how to do it, how to find all the instances of specific type in current file so the cross reference will work in the Predicate scope.
Thanks.

A: You have to walk up to the root of the from before you an walk down. EcoreUtil2.getContainerOfType(context, YourRootType) might help with this.
update:
The grammar and the example model don't fit, but that seems to be a completely different problem, so I can give only some hints.
You can only reference named elements to put those elements into the scope.
Grammar:
TypedParam:
    (module=[Import] '.')? type=[TypeDef] name=ID;

Referrable:
    TypedParam | TypeDef | TypeConstant;

Code:
val root = EcoreUtil2.getContainerOfType(context, Domainmodel)
val allContentsCurrFile  = EcoreUtil2.getAllContentsOfType(root,TypeConstant)


text:
Q: some strange orthogonal basis and  an integral equation with it I know  coefficients of some function in basis $p_j,j=1...K$ where
$p_{j}(x)=\sum_{s\in Z}a_{s,j}\exp\left(-2\pi i(j+sK)x\right)$
With respect to inner product $(f,g)=\int_{0}^{1}f(x)\overline{g(x)}dx$ this basis is orthogonal.
What kind of basis is it?  Can I somehow use Fourier analysis framework  for this basis?
One more question about this basis. How to solve this integral equation?
$$a_{j}=\int_{-\infty}^{\infty}g(x)p_{j}(x)dx$$
$g-$unknown function. Could you give me some hint, or some links?

A: If $a_{s,j}$ is in $\ell_2$ for any fixed $j$, $p_j$ forms an orthogonal basis for some finite dimensional sub-space of $L^2(\mathbb{T})$. If $f(x) = \sum_{j=0}^K b_j p_j(x)$, then its fourier coefficients are just given by $\hat{f}(\xi) = a_{s,j} b_j$ where $j = \xi \mod K$ and $s = \lfloor \xi / K \rfloor$, so surely normal Fourier analytic techniques apply.
I don't quite understand your question about "What kind of basis is it?" Can you clarify?


text:
Q: how to notice if a mail is a forwarded mail? I have a very special problem.
If we create a mail in Outlook, we add a UserProperty which contains a DataBase-ID of our System, so we can Link the mail to the representing DataBase-Item. On the service which reads the mails in each Mailbox and imports them automatically I can read this property by using ExtendedPropertyDefinitions. So far everything is fine...
If the User now forwards the message in Outlook, Olk copies the UserProperty to the new message. And now my problems beginn. Now my Service thinks the new message is also linked to our database and updates DB-Entry with the new Body and new Subject.
So does anyone now how to find out if a message is a forwarded one or how to tell Outlook not to copy the userproperty to the forwarded (new) message?
thx. Jay
What we thought about, but isnt working for our case
- a second userproperty containing a simple tag linke "fromSystem". Cause this would be copied too.
- a second userproperty containing a hashsum calculated from subject and Body. Cause both could be changed by the user. We just create the message, add all properties and Display it. from this Point on we no longer have control what is Happening to the mail until the Service handles it.

A: Your service consuming EWS should check the ConversationIndex and only update the database if it's 22 bytes long (original source message). Forward emails and reply emails keep appending 5 bytes (10 chars) to the ConversationIndex extending it beyond 22 bytes.
Sample ConversationIndexes

Original: 01CDD15D80E51C1D4522172840ACA96287DA28A15D97
Reply:    01CDD15D80E51C1D4522172840ACA96287DA28A15D970000018630
Forward:  01CDD15D80E51C1D4522172840ACA96287DA28A15D970000018630000000FC30

ConversationIndex represents the sequential ordering of the ConversationTopic (essentially GUID + timestamp). See Working with Conversations on MSDN. ConversationIndex is explicitly defined on MSDN here.
 if (message.ConversationIndex.Length == 22)
 {
   // update DB body, subject, etc.
 }

Also make sure you load the EmailMessageSchema.ConversationIndex before trying to access its value.


text:
Q: Objective-C - generating source code reports I am facing a following problem:  I need to generate detailed reports for Objective-C  source code (written for iOS). I need to be able to display following:
Class report:
Class name | File location | Number of methods
ClassA | /my/path/ClassA.m | 7
ClassB | /my/path/ClassB.m | 12
....
Methods report:
Method name | Class name | File location
method1 | ClassA | /my/path/ClassA.m
method2 | ClassA | /my/path/ClassA.m
....
And I also need to be able display few other reports but at this moment I am interested just to start from somewhere.
Please note:
- At the moment I do not have requirement to have number of lines/complexity/etc displayed.
- Report similar to above one is sufficient (as long as it contains information above I will be really happy; I can parse the info and create the report that is needed)
- I have already looked at Doxygen and its xml output but for few sample projects that I run I did not get all methods listed in xml documentation (even though they are in the files).  I have to investigate why these methods are not showing up.
Thanks in advance to all the answers/hints/comments....

A: Depending on your proficiency with Java, you might want to take a look at JavaCC. It also has a grammar for parsing Objective-C 2.0.
http://lists.apple.com/archives/java-dev/2010/Sep/msg00097.html
I confess I barely opened the grammar to look at how complex/simple it is. It looked well organized but I didn't experiment with it myself. Generally speaking, JavaCC looks a bit steep at first glance but with a couple of hours of toying around with it, you should find your marks pretty quickly. Once you get it though, parsing any language becomes really easy.

A: Our Source Code Search Engine would probably help you do this nicely.
SCSE is normally used interactively to search across large source codes and inspect the code.  It understands the elements of the langusges it is searching, and it has an option for Objective C.   Because it understands language syntax, it isn't confused by whitespace or comments or strings with funny content.  It can also record the results of searches as text logs and/or XML files of hits and locations (file, line).
One can use it in batch scripts to do searches and capture results.
To do what you want, you'd give the SCSE the following queries and log the results into XML (forgive my ObjectiveC syntax, I'm not a programmer in such):
    '@implementation' I     -- this would find class declarations, bind I and capture line #
    '@interface' I  -- if you wanted these, too
    '@end'   -- would find end-of-class declarations
    '+' '(' I ')' '{'  -- find method declations and bind name
    '-' '(' I ')' '{'  -- find static method declarations

Now you have a set of XML files that describe where these elements are.   Integrating the hits gives you an outline model of classes and content, and computing your values from this information should be pretty straightforward.
If you want a more precise answer, our DMS Software Reengineering Toolkit has a full Objective C parser.  This information is easily extracted from the AST that the parser produces.


text:
Q: How to specify concrete classes in factory for deferred instantiation / how to defer constructor call I have a several server programs which have a bunch of common code, but differ in a few child class implementations.  I use the abstract factory-like pattern something like this:
int main(int argc, char **argv) {
    Factory *factory = new Program1Factory();
    ServerThread theServer(factory);       // inject the dependencies
    theServer.start();
}

Factory is a pure abstract class, composed of the various bits I need to obtain the methods which have to vary from program to program.  It looks roughly like this:
class Factory {
    public: virtual foo *getFooThing() = 0;
    public: virtual bar *getBarThing() = 0;
};

The concrete declaration and implementation for one program might look like this:
class Program1Factory : public Factory {
    public: virtual foo *getFooThing() { return new Program1Foo(); }
    public: virtual bar *getBarThing() { return new Program1Bar(); }
};

This worked fine until I got to a bunch of methods which themselves are child classes of a library over which I have no control.
In that library, the constructors of each of the classes require the data to be processed to be provided in the constructor!  But my program does not yet have the data; it's just starting up and declaring its factory.  Only once all the methods are set up and the threads start, do my server programs receive transactions which are the input to the constructors.
That is to say, in the example above, I cannot simply say:
return new Program1Bar()

because the class from which Program1Bar is derived only has a constructor that looks like
Program1Bar(string *inputString, string *outputString)

I don't have those values at the time my factory is instantiated.
I need to somehow create a pointer to the concrete class I want, store that pointer in my factory, and -- the hard part I cannot figure out -- instantiate (call the constructor) for those classes when data finally arrives.
How can I go about this?

A: With those restrictions your Program1Bar class cannot be a subclass of the 3rd party library. Hard to talk abstract, but one suggestion would be for you to define a class like Task1Bar which is a subclass of your 3rd party library.
Then somewhere inside ProgramBar1::someMethod you can make your call to new Task1Bar. If you need the 3rd party library to persist across methods you can always define a member Task1Bar* task1 inside your Program1Bar class.
Just a suggestion, As I said, hard to define in the abstract.


text:
Q: How to implement optimistic concurrency on navigation properties in Entity Framework 6 Database First What's the idiomatic way to implement optimistic concurrency in Entity Framework Database First if you have navigation properties on your entities (Ie x to Many relationship between parent and child tables)? Do you need to check the rowversion on both parent and child entities or is there wa such that only checking the parent entity's rowversion would suffice to know whether any child table was updated as well as any parent?
Consider 2 tables:
Table Parent {
   ParentId INT PRIMARY KEY,
   ValueParent INT
   Version ROWVERSION
}

Table Child {
   ParentId INT FOREIGN KEY
   ChildId INT,
   ValueChild INT
   Version ROWVERSION
  (ParentId,ChildId) Primary Key
}

When converted to entities, the tables will look like the following:
class Parent{
   int ParentId;
   int valueParent;
   byte[] version;
   virtual ICollection<Child> Children
}

class Child{
   int parentId;
   int childId;
   int valueChild;
   byte[] version;
}

If I load a Parent object, and only update the child entity on it,
parent.Children.ElementAt(0).valueChild = 1 //

In the db, the rowversion in the child entity will increment, but the parent rowversion will remain unchanged. Is that valid? If I want to implement optimistic concurrency I'd still need to do a rowversion check on both parent and child to ensure that the model hasn't changed. I could set concurrency mode to fixed for versions on both entities but that wouldn't prevent having to check at the beginning before I do the update right?
What's the idiomatic way to implement optimistic concurrency if you have 1-many relationships between your entities? Is there some way to do it where I only need to check the parent rowversion or would I need always to check rowversions of any child elements as well?

A: Optimistic concurrency is checked on every row, and you just need to configure the column as a Timestamp/Rowversion and EF will generate the concurrency checks for you.

Is there some way to do it where I only need to check the parent rowversion

As @Jeremy Lakeman suggests, if you always update the parent when any child changes, then concurreny violations from your EF app can be detected and prevented.  But it wouldn't protect against ad-hoc updates to the child rows.


text:
Q: Using case_when to subset a datatable I am still new to R, and I'm running into an issue.
I have a file with Raw Data :
dfRawData <-
  data.table(
    "Model" = c(
      "Car1",
      "Car1",
      "Car1",
      "Car2",
      "Car2",
      "Car2",
      "Car3",
      "Car3",
      "Car3"
    ),
    "variable" = c(
      "Metric1",
      "Metric2",
      "Metric3",
      "Metric1",
      "Metric2",
      "Metric3",
      "Metric1",
      "Metric2",
      "Metric3"
    ),
    "valeur" = c(1, 2, 3, 4, 5, 6, 7, 8, 9)
  )

I want to subset this data table based on the name of the car, and the metric. However, I'd like to avoid using if statements, because my code is already very long. To what I've understood, case_when could be very useful.
I know that the formula for the subsetted data table is right, since when I use if statement, it returns me what I want.
Yet, when I use case_when, I get the following error :
Error in `[.data.frame`(x, i) : undefined columns selected

Does someone know what I'm doing wrong ?
Here is my code :
carName = 'Car1' ##Can be changed
dfCarMetric = case_when(
           carName == 'Car1' ~ dfRawData[which(dfRawData[["Model"]] == carName  &
                                               dfRawData[["variable"]] %in% c("Metric1", "Metric2")), ],
           carName == 'Car2' ~ dfRawData[which(dfRawData[["Model"]] %in% c("Car2", "Car3")  &
                                               dfRawData[["variable"]] == "Metric1"), ]
       )

I want to have this in the end :
carName = 'Car1'
    dfCarMetric
       Model variable valeur
    1:  Car1  Metric1      1
    2:  Car1  Metric2      2

carName = 'Car2'
    dfCarMetric
      Model variable valeur
    4  Car2  Metric1      4
    7  Car3  Metric1      7

Thank you very much for your answers !!

A: Instead of case_when, which I imagine is from the package dplyr, why don't you try to filter function instead, which is better suited for sub-setting data sets.
library(dplyr)
library(magrittr)

dfRawData <-  data.frame(
    "Model" = c(
      "Car1",
      "Car1",
      "Car1",
      "Car2",
      "Car2",
      "Car2",
      "Car3",
      "Car3",
      "Car3"
    ),
    "variable" = c(
      "Metric1",
      "Metric2",
      "Metric3",
      "Metric1",
      "Metric2",
      "Metric3",
      "Metric1",
      "Metric2",
      "Metric3"
    ),
    "valeur" = c(1, 2, 3, 4, 5, 6, 7, 8, 9)
  )

# Filter
newData <- dfRawData %>%
  filter((Model =='Car1' & variable %in% c('Metric1', 'Metric2')) |  # Condition 1
                     (Model %in% c('Car2', 'Car3') & variable == 'Metric1')) # Condition 2

This makes an output like the following:
 newData
  Model variable valeur
1  Car1  Metric1      1
2  Car1  Metric2      2
3  Car2  Metric1      4
4  Car3  Metric1      7

You can adjust the filter conditions to get the exact subset that you like, and it should be an easier syntax than case_when.
Using a function

To make this a bit easier and allow you to specify carName, you could wrap this specific filter into a simple (albeit fragile) function:
myFilterFunction <- function(data, carName = 'Car1', metric = c('Metric1', 'Metric2')) {
  data %>%
    filter(Model %in% carName & variable %in% metric)
}

carName = 'Car1'
myFilterFunction(dfRawData, carName = carName, c('Metric1', 'Metric2'))

carName = c('Car2', 'Car3')
myFilterFunction(dfRawData, carName = carName, c('Metric1'))

Which has outputs of:
  Model variable valeur
1  Car1  Metric1      1
2  Car1  Metric2      2

  Model variable valeur
1  Car2  Metric1      4
2  Car3  Metric1      7

A: If you are trying to minimise the amount of conditional statements, you could use them inside of the filter function, also from the dplyr package:
dfCarMetric <- dfRawData %>%
  filter(
    if (carName == "Car1")
      Model == carName & variable %in% c("Metric1", "Metric2")
    else if (carName == "Car2")
      Model %in% c("Car2", "Car3") & variable == "Metric1")
  )

The case_when function can be used in a similar way, albeit less usual IMHO:
dfCarMetric <- dfRawData %>%
  filter(case_when(
      carName == "Car1" ~
        Model == carName & variable %in% c("Metric1", "Metric2"),
      carName == "Car2" ~
        Model %in% c("Car2", "Car3") & variable == "Metric1"
    )
  )


text:
Q: Static variable for VUs in K6 Is there a way to use a static variable shared across VUs in K6.
Say
// init code
let x = 0 // i want this to be static
// options
export let options = {
  vus : 10,
  iterations : 10
};
// VU code
export default function() {
  x++;
  console.log(x);
}

When I run this piece of code, the output should be incremental (1 to 10) and not 1 printed 10 times (1 for each VU).

A: In k6, each VU is a separate independent JS runtime, so you essentially have 10 copies of x. There is no way around that with stock k6 for now, you have to use some external service as an incrementing counter via HTTP or something like that. Alternatively, if you'll run k6 locally and only on a single instance, you can use this xk6 extension (more info): https://github.com/MStoykov/xk6-counter. It was a PoC originally developed for https://community.k6.io/t/unique-test-data-per-vu-without-reserving-data-upfront/1136/3 , but can be easily extended.


text:
Q: How can I temporarily disable ASLR (Address space layout randomization)? I am using Ubuntu 12.04 32-bits, for some experiment I need to disable ASLR; how do I accomplish that? What should I do after that to enable ASLR again?

A: If you want to construct a program which disables ASLR for itself when it runs, you can use the personality system call on Linux. Here's a recipe:
#include <stdio.h>
#include <sys/personality.h>

int main(int argc, char **argv) {
    const int old_personality = personality(ADDR_NO_RANDOMIZE);
    if (!(old_personality & ADDR_NO_RANDOMIZE)) {
        const int new_personality = personality(ADDR_NO_RANDOMIZE);
        if (new_personality & ADDR_NO_RANDOMIZE) {
            execv(argv[0], argv);
        }
    }
    printf("&argc == %p\n", (void *) &argc);
}

If you look at the source for setarch, it calls personality twice in roughly this pattern. The major difference is that setarch calls exec on some other program, whereas my recipe execs itself. It's important that you use non-zero-ness of & ADDR_NO_RANDOMIZE and not equality tests: else you can go into an infinite exec loop if you e.g. compile with -z execstack.
See also the man page for personality.

A: The /proc/sys/kernel/randomize_va_space interface controls ASLR system-wide.
If you don't want a system-wide change, use ADDR_NO_RANDOMIZE personality flag to temporarily disable ASLR. Controlling of this flag can be done with setarch and its -R option, like
setarch `uname -m` -R /bin/bash

This will open a new Bash shell for you with ASLR disabled, including all child processes run from this shell. Just exit the shell once you're done.

By the way, on i386, ulimit -s unlimited can effectively "disable" ASLR.
EDIT (Apr 2016): The ulimit -s unlimited was fixed and assigned CVE-2016-3672.

A: The more permanent ways of disabling ASLR should be kept in a VM for obvious reasons.
to test the ability to overwrite stack frame return addresses etcetera, you'll need to compile without stack canaries -fno-stack-protector, while to allow you to execute code on the stack you need to compile with -z execstack, making
$ gcc -fno-stack-protector -z execstack -o <my_program> my_code.c

A: You can use the following command to temporarily disable ASLR.
sudo sysctl kernel.randomize_va_space=0

A: According to an article How Effective is ASLR on Linux Systems?, you can configure ASLR in Linux using the /proc/sys/kernel/randomize_va_space interface.

The following values are supported:

*

*0 – No randomization. Everything is static.

*1 – Conservative
  randomization. Shared libraries, stack, mmap(), VDSO and heap are
  randomized.

*2 – Full randomization. In addition to elements listed in
  the previous point, memory managed through brk() is also randomized.

So, to disable it, run
echo 0 | sudo tee /proc/sys/kernel/randomize_va_space

and to enable it again, run
echo 2 | sudo tee /proc/sys/kernel/randomize_va_space

This won't survive a reboot, so you'll have to configure this in sysctl. Add a file /etc/sysctl.d/01-disable-aslr.conf containing:
kernel.randomize_va_space = 0

should permanently disable this.


text:
Q: Inequality w.r.t determinant of a non-negative definite matrix. I am reading a paper where the author mentioned the following property without proof. Neither can I prove it nor can I find the proof in various textbooks.
For any non-negative definite (i.e. positive semidefinite) matrix $A$,
$$\text{det}(A) \leq \Pi_iA_{ii}$$
How to prove it?

A: First, there is the fact that for any $n\times n$ matrix $P$, if one writes $P=[v_1, v_2, ..., v_n]$, where $v_k$ is the $k$-th column of $P$, then
$$
|\text{det}P|\leq |v_1|\cdot|v_2|\cdot ...\cdot|v_n|;
$$
here $|v_k|$ is the length of the vector $v_k$. This actually reaches the equal sign if $v_1, ...,v_n$ are mutually perpendicular; in that case $[v_1/|v_1|, ..., v_n/|v_n|]$ is an orthogonal matrix, thus has determinant $\pm 1$, on the other hand its determinant is also $\text{det} P/(|v_1|\cdot ...\cdot |v_n|)$. For the general case, we do a procedure similar to Gram-Schmidt: replace $v_2$ by $v_2'$, which is $v_2$ minus its projection to $v_1$; that will reduce $|v_2|$ but not changing $\text{det}P$. Replace $v_3$ by $v_3'$, which is $v_3$ minus its projection to the $v_1, v_2$ plane, ... and in the end get $[v_1, v_2', v_3'...]$ with orthogonal columns. Thus $|\text{det} P|= |v_1|\cdot |v_2'|\cdot..\cdot|v_n'|\leq |v_1|\cdot...\cdot|v_n|$.
Now $A$ is nonnegative, it is "well-known" that we can find orthogonal matrix $Q$ so that $A=Q^T\Lambda Q$, where $\Lambda$ is diagonal with $\geq 0$ entries. Write $\sqrt \Lambda$ be the diagonal matrix with $(\sqrt\Lambda)^2=\Lambda$, thus $A=Q^T\sqrt\Lambda\sqrt\Lambda Q=(Q^T\sqrt\Lambda Q)(Q^T\sqrt\Lambda Q)$. in conclusion, we can write $A=P^TP$, with $P=Q^T\sqrt\Lambda Q$.
Let  $P=[v_1, ...,v_n]$. Then from $A=P^TP$ we see $a_{11}=|v_1|^2$, ... , $a_{nn}=|v_n|^2$. Thus
$$\text{det}A=
(\text{det} P)^2\leq (|v_1|\cdot...\cdot|v_n|)^2=|v_1|^2\cdot...\cdot|v_n|^2=a_{11}\cdot ...\cdot a_{nn}.
$$


text: Q: Get IP Address of Device on Same Network by Mac Address in React Native I have a react native project I'm working on where I need to make requests to a raspberry pi server using it's IP address. I need to connect to the raspberry pi regardless of if the IP address changes. I know the mac address of the Pi usually starts with either b8:27:eb or dc:a6:32. Using arp -a | findstr /i "b8-27-eb dc:a6:32 as per this blog post https://www.shellhacks.com/find-raspberry-pi-ip-on-network-windows-macos-linux/ usually gives me the IP address of my raspberry pi. The project is strictly android, is there a way to achieve this in react native? If not in react native what native code could I use to accomplish this task?


text:
Q: Enabling iCloud Drive folder for files of an iOS app I store files and a persistant core data store in iCloud. If I go to ~/Library/Mobile Documents/iCloud~com~company~myApp/Documents I can see the files that are stored in iCloud.
But when I go to the Finder and select iCloud Drive then I can not see the files. If I log onto iCloud.com I can also not see the files.
I have the following entries in my Info.plist
<dict>
    <key>iCloud~com~company~myApp</key>
    <dict>
        <key>NSUbiquitousContainerIsDocumentScopePublic</key>
        <true/>
        <key>NSUbiquitousContainerName</key>
        <string>My App</string>
        <key>NSUbiquitousContainerSupportedFolderLevels</key>
        <string>None</string>
    </dict>
</dict>
</plist>

Is there anything else I need to set up for the files and the folder to also show up in Finder?
Thanks

A: The problem was that the key is not supposed to reflect the folder name, but instead the namespace so iCloud~com~company~myApp is supposed to be iCloud.com.company.myApp.


text:
Q: Django post initialization modules Is there a way that I can call some functions/modules right after all the settings in Django have been imported?

A: Probably, the best place for this is the end of the settings.py ;-)


text:
Q: Validate Date Value before converting in DB2 We have Dates stored as packed fields in our DB2 tables.  I am able to convert these to a valid DB2 DATE field, but sometimes the source contains an invalid date value such as 20130431 - only 30 days in April.  I know that wwhen the date supplied to DATE function is invalid, the SQLCODE returned is
-181.  Do I have to write a function to check for the SQLCODE inorder to validate or can I do something in a CASE statement?


text:
Q: Import user data using CSV I want to import user information using a CSV file. I am using the BP Groups Import User plugin.
The challenge is to add the first name and last name columns in the CSV file but I cannot get the value to save.
My table is
| email      | first name | last name | moderator | admin |
+------------+------------+-----------+-----------+-------+
|sm@mail.com | max        | biagi     |      1    |   1   |

my code
}else if(isset($_POST['create_user'])) {
                    //Create new user
                    $usermeta = array();
                    $usermeta['first_name'] = ucfirst ($first_name);
                    $usermeta['last_name'] = ucfirst ($last_name);
                    $usermeta['password'] = wp_hash_password( $email );
                    $user_login = strtok($email, '@');
                    $user_id = bp_core_signup_user( $user_login, $email, $email, $usermeta );

                    //Add user to group
                    groups_join_group($group_id, $user_id );

                    //Promote user to group moderator
                    if($mod){
                        groups_promote_member($user_id,$group_id,'mod');
                    }
                    //Promote user to group administrator
                    if($admin){
                        groups_promote_member($user_id,$group_id,'admin');
                    }
                }

I can only save email.
Is there another way to get the value from the CSV table?

A: UPDATE SOLVED
I change my code to wp_insert_user beside bp_core_user_signup
$user_id = wp_insert_user(array(
                            'user_login' => $user_login,
                            'user_pass' => wp_hash_password( $email ),
                            'first_name' => $first_name,
                            'last_name' => $last_name,
                            'display_name' => $first_name . ' ' . $last_name,
                            'user_email' => $email,
                            'user_nicename' => $first_name


text:
Q: Как сохранить фрагменты в памяти? Я использую MVP + Moxy+ BottomNavigation.
Моя задача состоит в том чтобы сохранять фрагменты в памяти. Сделать работу на подобии ViewPagerApdater.
Вообщем. У меня есть 3 фрагмента, они все наследуются от MVPFragment. Изначально ни один из фрагментов не создан. Я должен создать по нажатии на кнопку, тот или иной фрагмент 1 раз. Пока жив MainActivity.
Тоесть получается.

Нажимаем на кнопку 1 создается 1 фрагмент.
Нажимаем на кнопку 3 создается 3 фрагмент.
Нажимаем на кнопку ничего не создалось заново, просто восстановился
  фрагмент 1.
Нажимаем на кнопку 2 создался 2 фрагмент.

и т.д.
Как такое реализовать в коде? Мучаюсь уже 4 день(((


text:
Q: How can I merge different accounts for Stack Exchange and Stack Overflow? How do I consolidate all my accounts into one? I have this account on Stack Overflow

Then this one shows up for my Stack Exchange

How would I add them all together ?


text:
Q: Добавление значений в ArrayList Получаю json с сервера, чтобы в дальнейшем передать в кастомный адаптер. При запуске приложение вылетает ошибка

java.lang.NullPointerException: Attempt to invoke virtual method
  'boolean java.util.ArrayList.add(java.lang.Object)' on a null object
  reference

Как исправить?
    public class JSONTask extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {

        HttpURLConnection connection = null;
        BufferedReader reader = null;
        while (true) {

            try {
                URL url = new URL(params[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                InputStream stream = connection.getInputStream();

                reader = new BufferedReader(new InputStreamReader(stream));

                StringBuffer buffer = new StringBuffer();

                String line = "";
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                return buffer.toString();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if (result != null) {

            JSONObject jsonObject = null;

            try {
                jsonObject = new JSONObject(result);

                JSONArray jsonArray = jsonObject.getJSONArray("wall");

                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject productObject = jsonArray.getJSONObject(i);

                    UList.add(new CSD(
                            productObject.getString("name"),
                            productObject.getString("text")
                    ));
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        } else {

        }

    }

}

A: у вас нет инициализации масива.
сделайте ее при обявлении масива, примерно так
List<CSD> UList = new ArrayList<>();

если не поможет, то укажите в какой строке ошибка


text:
Q: Transform the type of a thrust vector I am somewhat new to CUDA and thrust and I am currently struggeling with the following problem:
I have 2 structs carrying data.
struct S1 {
    unsigned long A, B, C;
}

struct S2 {
    double A, B, C;
}

At the start of the program I have a vector of the first struct and I want to use the GPU as well as a special functor to transform the vector of S1 to a vector of S2. The result will have the same size as the input only with elements of a different type.
I am currently using this setup:
struct Functor {
    Functor() {}

    __host__ __ device__ S2 operator() (const S1& s1) {
        // perform some operation on S1 to convert it so S2
        // here I just copy the values
        return S2{s1.A, s1.B, s1.C};
    }
}

void main() {
    std::vector<S1> input;
    // fill the 'input' vector

    // move the input to a device vector
    thrust::device_vector<S1> input_d(input);
    // empty vector for struct S2
    thrust::device_vector<S2> output_d(input.size());

    thrust::transform(input_d.begin(), input_d.end(), output_d.begin(), output_d.end(), Functor());

    return 0;
}

The functor Functor is responsible for converting S1 to S2 (simplified in this case).
This code results in a compiler error since the operator() needs 2 arguments while I only want to have one input. Looking around the web I did not find a solution that applies to my problem.

A: As already pointed out in the comments I misread the documentation (see here). The solution is to use a unary functor and another way of calling the thrust::transform.
// this functor converts values of S1 to S1 by multiplying them with .5
// in the actual scenario this method does perform much more useful operations
struct Functor : public thrust::unary_function<S1, S2> {
    Functor() {}

    __host__ __device__ S2 operator() (const S1& s1) const {
        // very basic operations on the values of s1
        double a = s1.A * .5;
        double b = s1.B * .5;
        double c = s1.C * .5;
        return S2{a, b, c};
    }
}

The transform is then called as:
thrust::host_vector<S1> tmp;
// fill the tmp vector with S1 instances...

// move the host vector to the device
thrust::device_vector<S1> input_d;
input_d = tmp;

// initializing the output with the same size as the input
thrust::device_vector<S2> output_d(tmp.size());

// calling the functor on all elements of the input and store them in the output
thrust::transform(input_d.begin(), input_d.end(), output_d.begin(), Functor());

Edit: Added some more code parts so it is actually working code.


text:
Q: React version of jQuery.getJSON { New to React and trying to rebuild my site to ReactJS and GatsbyJS. One issue I keep coming up against is getJSON, especially in this code here.
How can I use this in React without needing jQuery?
_fetchWeather() {
  jQuery.getJSON({
    method: 'GET',
    data: {
      q: `select * from weather.forecast
          where woeid in (select woeid from geo.places(1)
          where text="${this.state.search}")`,
      format: 'json',
      env: 'store://datatables.org/alltableswithkeys'
    },
    url: 'https://query.yahooapis.com/v1/public/yql'
  }).success(res => {
    this.setState({weather: res.query.results.channel});
  });
}

A: There are several options to get data from an API endpoint in React. The simplest is to use the fetch api found in most modern browsers. If you are worried about compatibility issues, there are libraries such as superaget and axios both of which heavily leverage JavaScript's promise api


text:
Q: Inequality Question - Homogeneity Let $n>3$ and $x_1, x_2, \ldots, x_n$ be positive real numbers with $x_1x_2\cdots x_n=1$. Prove that
$$
\frac{1}{1+x_1+x_1x_2}+\frac{1}{1+x_2+x_2x_3}+\cdots+\frac{1}{1+x_n+x_nx_1}>1.
$$
I'd like to homogenize the degree of the denominator of each term but I ran out of tricks. Any help will be appreciated. Thanks.

A: You can make the homogenization by the following way.
Let $x_1=\frac{a_2}{a_1},$ $x_2=\frac{a_3}{a_2},$..., $x_{n-1}=\frac{a_n}{a_{n-1}},$ where all $a_i>0$, $a_{n+1}=a_1$ and $a_{n+2}=a_2$.
Thus, the condition gives $x_n=\frac{a_1}{a_n}$ and
$$\sum_{i=1}^n\frac{1}{1+x_1+x_2}=\sum_{i=1}^n\frac{1}{1+\frac{a_{i+1}}{a_i}+\frac{a_{i+2}}{a_i}}=\sum_{i=1}^n\frac{a_i}{a_i+a_{i+1}+a_{i+2}}>\sum_{i=1}^n\frac{a_i}{a_1+a_2+...+a_n}=1.$$


text: Q: How to prevent git push - only verified emails can be pushed In GITHUB. How can I prevent unverified emails from pushing changes into the repository? sometimes code can be pushed even if user.email is not set. how to prevent this?


text:
Q: MS SQL row_number/rank alternative for simple set enumeration I am trying to use row_number or rank just to insert a row number so I can enumerate over a temp table without using a cursor.  Both functions give me error "Incorrect syntax near 'rank', expected 'OVER'".  I do not need all of the functionality + performance impact that OVER provides - I don't care one bit about order/ranking etc.  I'm sure I've done this before but it was a few years ago, can someone point me to the correct function?
declare @SomeTempTable table (RowNum int NOT NULL, SomeField int NOT NULL);

insert into @SomeTempTable
  select rank() as RowNum, SomeField
  from SomeTable

declare @RowNum int = 1;
declare @NumRows int = (select max(RowNum) from @SomeTempTable);

while@RowNum <= @NumRows
begin
  declare @SomeField int;

  select @SomeField = SomeField
  from @SomeTempTable
  where RowNum = @RowNum;

  --TODO: Do stuff

  set @RowNum = @RowNum + 1;
END

A: Hmmm, you don't get to decide on the syntax of SQL functions, even if it is appealing to you.
There are two methods to get what you want.  The first is the standard method, that doesn't use windows functions at all:
declare @SomeTempTable table (
    RowNum int identity(1,1) not null,
    SomeField int NOT NULL
);

insert into @SomeTempTable(SomeField)
     select SomeField
     from SomeTable

Voila!  Let the identity do the work.
The second is the approach you were taking:
insert into @SomeTempTable(RowNum, SomeField)
    select row_number() over (order by (select NULL)) as RowNum, SomeField
    from SomeTable

The "order by (Select NULL)" appears to be a magical incantation in SQL Server to just assign numbers, without actually doing a sort.
As an aside, when you do an insert, you should always specify the columns in the insert statement.
Also, it is quite possible that the WHILE loop could be re-written as a query, making everything more efficient (not always, but sometimes).