text:
Q: App Intent Problem | Your app contains an Intent Redirection vulnerability I got this message after updating app in play console. I am sharing code of a method where the error is, as suggested by Google. I never updated this part of the code and it never showed any problem before. I am not sure why it is showing me an error. Do I need to update the way of saving a file? I hope to find a solution here.
       public void saveDocument(ScannedDocument scannedDocument) {

        Mat doc = (scannedDocument.processed != null) ? scannedDocument.processed : scannedDocument.original;

        Intent intent = getIntent();
        String fileName;
        boolean isIntent = false;
        Uri fileUri = null;

        if (intent.getAction().equals("android.media.action.IMAGE_CAPTURE")) {
            fileUri = ((Uri) intent.getParcelableExtra(MediaStore.EXTRA_OUTPUT));
            Log.d(TAG, "intent uri: " + fileUri.toString());
            try {
                fileName = File.createTempFile("onsFile", ".jpg", this.getCacheDir()).getPath();
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
            isIntent = true;
        } else {
            String folderName = mSharedPref.getString("storage_folder", FOLDER_NAME);
            File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString()
                    + "/" + folderName);
            if (!folder.exists()) {
                folder.mkdirs();
                Log.d(TAG, "wrote: created folder " + folder.getPath());
            }
            fileName = folder.getAbsolutePath()
                    + "/DOC-"
                    + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date())
                    + ".jpg";
        }

        Mat endDoc = new Mat(Double.valueOf(doc.size().width).intValue(),
                Double.valueOf(doc.size().height).intValue(), CvType.CV_8UC4);

        Core.flip(doc.t(), endDoc, 1);

        Imgcodecs.imwrite(fileName, endDoc);
        endDoc.release();

        try {
            ExifInterface exif = new ExifInterface(fileName);
            exif.setAttribute("UserComment", "Generated");
            String nowFormatted = mDateFormat.format(new Date().getTime());
            exif.setAttribute(ExifInterface.TAG_DATETIME, nowFormatted);
            exif.setAttribute(ExifInterface.TAG_DATETIME_DIGITIZED, nowFormatted);
          //  exif.setAttribute("Software", "OpenNoteScanner " + BuildConfig.VERSION_NAME + "");
            exif.saveAttributes();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (isIntent) {
            InputStream inputStream = null;
            OutputStream realOutputStream = null;
            try {
                inputStream = new FileInputStream(fileName);
                realOutputStream = this.getContentResolver().openOutputStream(fileUri);
                // Transfer bytes from in to out
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) > 0) {
                    realOutputStream.write(buffer, 0, len);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return;
            } catch (IOException e) {
                e.printStackTrace();
                return;
            } finally {
                try {
                    inputStream.close();
                    realOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        animateDocument(fileName, scannedDocument);

        Log.d(TAG, "wrote: " + fileName);

        if (isIntent) {
            new File(fileName).delete();
            setResult(RESULT_OK, intent);
            finish();
        } else {
            addImageToGallery(fileName, this);
        }

        refreshCamera();
    }

A: Google has a page on Mitigating Intent Redirection vulnerabilities that you should read carefully.
The short version is that the vulnerability could potentially1 be exploited by a malicious app to allow it to access private app components or files.
The document explains three possible ways to mitigate this vulnerability.  Unfortunately, there is not enough context to be sure which of the three is most appropriate for your app.  However, the first one is straightforward:

"If the affected app component does not need to receive Intents from other apps then you can make that app component private by setting `android:exported="false" in your Manifest."

I never updated this part of the code and it never showed any problem before.

That could mean that this is a relatively new kind of Android vulnerability, or that Google's methodology for detecting it has become more rigorous since last time you published your app.

Do I need to update the way of saving a file?

Possibly yes.  Or possibly one of the mitigations will be sufficient.

I hope to find a solution here.

There are some possible solutions in the Google document I linked to.

1 - It is moot if it is actually possible to exploit the vulnerability in your app.  The point is that Google Play Store's scanning / analysis / testing methodology has found what they believe to be a problem.  Their goal is to protect Play Store users.


text:
Q: SQL interpolating missing values for a specific date range - with some conditions There are some similar questions on the site, but I believe mine warrants a new post because there are specific conditions that need to be incorporated.
I have a table with monthly intervals, structured like this:
+----+--------+--------------+--------------+
| ID | amount | interval_beg | interval_end |
+----+--------+--------------+--------------+
|  1 |     10 | 12/17/2017   | 1/17/2018    |
|  1 |     10 | 1/18/2018    | 2/18/2018    |
|  1 |     10 | 2/19/2018    | 3/19/2018    |
|  1 |     10 | 3/20/2018    | 4/20/2018    |
|  1 |     10 | 4/21/2018    | 5/21/2018    |
+----+--------+--------------+--------------+

I've found that sometimes there is a month of data missing around the end/beginning of the year where I know it should exist, like this:
+----+--------+--------------+--------------+
| ID | amount | interval_beg | interval_end |
+----+--------+--------------+--------------+
|  2 |     10 | 10/14/2018   | 11/14/2018   |
|  2 |     10 | 11/15/2018   | 12/15/2018   |
|  2 |     10 | 1/17/2019    | 2/17/2019    |
|  2 |     10 | 2/18/2019    | 3/18/2019    |
|  2 |     10 | 3/19/2019    | 4/19/2019    |
+----+--------+--------------+--------------+

What I need is a statement that will:

*

*Identify where this year-end period is missing (but not find missing
months that aren't at the beginning/end of the year).

*Create this interval by using the length of an existing interval for
that ID (maybe using the mean interval length for the ID to do it?). I could create the interval from the "gap" between the previous and next interval, except that won't work if I'm missing an interval at the beginning or end of the ID's record (i.e. if the record starts at say 1/16/2015, I need the amount for 12/15/2014-1/15/2015

*Interpolate an 'amount' for this interval using the mean daily
'amount' from the closest existing interval.

The end result for the sample above should look like:
+----+--------+--------------+--------------+
| ID | amount | interval_beg | interval_end |
+----+--------+--------------+--------------+
|  2 |     10 | 10/14/2018   | 11/14/2018   |
|  2 |     10 | 11/15/2018   | 12/15/2018   |
|  2 |     10 | 12/16/2018   | 1/16/2018    |
|  2 |     10 | 1/17/2019    | 2/17/2019    |
|  2 |     10 | 2/18/2019    | 3/18/2019    |
+----+--------+--------------+--------------+

A 'nice to have' would be a flag indicating that this value is interpolated.
Is there a way to do this efficiently in SQL? I have written a solution in SAS, but have a need to move it to SQL, and my SAS solution is very inefficient (optimization isn't a goal, so any statement that does what I need is fantastic).
EDIT: I've made an SQLFiddle with my example table here:
http://sqlfiddle.com/#!18/8b16d

A: You can use a sequence of CTEs to build up the data for the missing periods. In this query, the first CTE (EOYS) generates all the end-of-year dates (YYYY-12-31) relevant to the table; the second (INTERVALS) the average interval length for each ID and the third (MISSING) attempts to find start (from t2) and end (from t3) dates of adjoining intervals for any missing (indicated by t1.ID IS NULL) end-of-year interval. The output of this CTE is then used in an INSERT ... SELECT query to add missing interval records to the table, generating missing dates by adding/subtracting the interval length to the end/start date of the adjacent interval as necessary.
First though we add the interp column to indicate if a row was interpolated:
ALTER TABLE Table1 ADD interp TINYINT NOT NULL DEFAULT 0;

This sets interp to 0 for all existing rows. Then we can do the INSERT, setting interp for all those rows to 1:
WITH EOYS AS (
  SELECT DISTINCT DATEFROMPARTS(DATEPART(YEAR, interval_beg), 12, 31) AS eoy
  FROM Table1
),
INTERVALS AS (
  SELECT ID, AVG(DATEDIFF(DAY, interval_beg, interval_end)) AS interval_len
  FROM Table1
  GROUP BY ID
),
MISSING AS (
  SELECT e.eoy,
         ids.ID,
         i.interval_len,
         COALESCE(t2.amount, t3.amount) AS amount,
         DATEADD(DAY,  1, t2.interval_end) AS interval_beg,
         DATEADD(DAY, -1, t3.interval_beg) AS interval_end
  FROM EOYS e
  CROSS JOIN (SELECT DISTINCT ID FROM Table1) ids
  JOIN INTERVALS i ON i.ID = ids.ID
  LEFT JOIN Table1 t1 ON ids.ID = t1.ID
                     AND e.eoy BETWEEN t1.interval_beg AND t1.interval_end
  LEFT JOIN Table1 t2 ON ids.ID = t2.ID
                     AND DATEADD(MONTH, -1, e.eoy) BETWEEN t2.interval_beg AND t2.interval_end
  LEFT JOIN Table1 t3 ON ids.ID = t3.ID
                     AND DATEADD(MONTH,  1, e.eoy) BETWEEN t3.interval_beg AND t3.interval_end
  WHERE t1.ID IS NULL
)
INSERT INTO Table1 (ID, amount, interval_beg, interval_end, interp)
SELECT ID,
       amount,
       COALESCE(interval_beg, DATEADD(DAY, -interval_len, interval_end)) AS interval_beg,
       COALESCE(interval_end, DATEADD(DAY,  interval_len, interval_beg)) AS interval_end,
       1 AS interp
FROM MISSING

This adds the following rows to the table:
ID  amount  interval_beg    interval_end    interp
2   10      2017-12-05      2018-01-04      1
2   10      2018-12-16      2019-01-16      1
2   10      2019-12-28      2020-01-27      1

Demo on SQLFiddle

redpajama_set_name: RedPajamaStackExchange


text:
Q: count of matrix of 0,1 in which each row and each column have at least one 1. I know that the number of matrices with $0,1$ entries, in which each row and each column have at least one $1$, is equal to
$$\sum_{r=0}^n \sum_{s=0}^n (-1)^{r+s} C(n,r) C(n,s) 2^{rs}.$$
I want to prove it combinatorially using Inclusion–exclusion principle.

A: Let's say $S_{t,u}$ is the number of binary $n$ by $n$ matrices with $t$ rows of zeroes and $u$ columns of zeroes. The rows can be chosen in $C(n,t)$ ways and the columns can be chosen in $C(n,u)$ ways. The remaining portion of the matrix has $(n-t)(n-u)$ binary elements. So
$$S_{t,u} = C(n,t)C(n,u)2^{(n-t)(n-u)}$$
(Note that this formula works even when $t=u=0$.)
By inclusion/exclusion, the number of matrices with no row of zeroes and no column of zeroes is
$$\begin{align}
N_0 &= \sum_{t=0}^n \sum_{u=0}^n (-1)^{t+u} S_{t,u} \\
 &= \sum_{t=0}^n \sum_{u=0}^n (-1)^{t+u} C(n,t)C(n,u)2^{(n-t)(n-u)}
\end{align}$$
Now make a change of indices to $r=n-t$ and $s=n-u$.  The result is
$$\begin{align}
N_0 &= \sum_{r=0}^n \sum_{s=0}^n (-1)^{2n-r-s} C(n,n-r)C(n,n-s) 2^{rs} \\
&= \sum_{r=0}^n \sum_{s=0}^n (-1)^{r+s} C(n,r)C(n,s) 2^{rs}
\end{align}$$


text:
Q: Use Bitbucket Resources in another application I am software engineering student and I have to create a new project for one of my courses.
I've designed my application solution which needs to use git as a backend service. it needs git basics operations such as create a user, grant accesses, manage ssh keys, commit, push and etc, so I tried to run a git server but I thought it will be a better solution if application uses a perfect service like bitbucket.
so my question is, can I use bitbucket resources for my application as backend service? and if the answer is yes , please tell my how can I do this and also can I use bitbucket resources for free?
thanks in advance,
best regards.

A: If you want to host your own backend for testing, I'd suggest SCM Manager. It might not be as nearly as good as BitBucket, GitHub or Gitorious, but it's much, much, MUCH easier to install. Unless you need the more complex ALM features(like issue tracking or web GUI for code reviews) it should suffice your needs.

A: You can use BitBucket. It support both for Git and Mercurial repositories. The service offering includes an issue tracker and wiki, as well as integration with a number of popular third-party services.
The great thing of BitBucket, compared with GitHub, is that it's free and you can create as many private repos as you want.


text:
Q: Fatal error: Uncaught OAuthException: (#200) Requires extended permission: read_stream Fatal error: Uncaught OAuthException: (#200) Requires extended permission: read_stream thrown in /home/a1607618/public_html/base_facebook.php on line 1033
my app tend to read user wall posts
if ($user)
{
    $comments = $facebook->api('/me/home');
    d($comments);
}

function d($d){
    echo '<pre>';
    foreach ($d as $a => $b)
    {
        print "$a: $b\n";
    }
    echo '</pre>';
}

i give my app extended permission: read_stream  through Apps_>connectme_>Permissions
and here is the line 1033
protected function throwAPIException($result) {
    $e = new FacebookApiException($result);
    switch ($e->getType()) {
        // OAuth 2.0 Draft 00 style
        case 'OAuthException':
        // OAuth 2.0 Draft 10 style
        case 'invalid_token':
        $message = $e->getMessage();
        if ((strpos($message, 'Error validating access token') !== false) ||
           (strpos($message, 'Invalid OAuth access token') !== false)) {
            $this->setAccessToken(null);
            $this->user = 0;
            $this->clearAllPersistentData();
        }
    }

    throw $e;
}


text:
Q: Show that $\sum_{i=1}^{r}\sum_{j=1}^{r}i^2n_in_j \ge \sum_{i=1}^{r}\sum_{j=1}^{r}ijn_in_j $ As a step in a proof, I need to show the following:
$\sum_{i=1}^{r}\sum_{j=1}^{r}i^2n_in_j \ge \sum_{i=1}^{r}\sum_{j=1}^{r}ijn_in_j $
To show this, the solution states:

But for a fixed pair $i, j$ the coefficient of $n_in_j$ on the left-side summation is $i^2+j^2$, whereas its coefficient in the right summation is $2ij$. Hence it suffices to show that $i^2 + j^2 \ge 2ij$

While I think I understand the argument and how to conclude it from here (i.e, this follows since $(i-j)^2\ge 0$) I don't understand how we get the coefficients used in this inequality. I would appreciate if someone could explain this to me.

A: The idea here is that $n_i n_j=n_j n_i$, therefore you need to sum two coefficients since both lead to the same type of term. Here's an example: Let's say you want to compute the $n_3 n_4$ coefficient of the sum on the left-hand side. Then you need to sum the term when $(i,j)=(3,4)$ with the term when $(i,j)=(4,3)$. This gives you $(3^2+4^2)n_3 n_4$.

If you still do not understand, then perhaps here is a simpler way of reasoning. Write
$$S:=\sum_{i=1}^r \sum_{j=1}^r i^2 n_i n_j.$$
Relabelling the indices (the variables $i$ and $j$ are just dummy variables) and changing the order of summation (justified, since the sums are finite) also shows that
$$S=\sum_{j=1}^r \sum_{i=1}^r j^2 n_j n_i=\sum_{i=1}^r \sum_{j=1}^r j^2 n_i n_j.$$
Hence one has by the inequality $i^2+j^2\geq 2ij$:
$$2S=\sum_{i=1}^r \sum_{j=1}^r (i^2+j^2)n_i n_j\geq \sum_{i=1}^r \sum_{j=1}^r 2ijn_i n_j,$$
Dividing by $2$ gives the result you need to prove.


text:
Q: requests.exceptions.InvalidSchema: Missing dependencies for SOCKS support I would like to try to open a page using proxy requests.
https://stackoverflow.com/…/make-requests-using-python-over…
I have this code:
def get_tor_session():
session = requests.session()
# Tor uses the 9050 port as the default socks port
session.proxies = {'http': 'socks5://127.0.0.1:9050',
'https': 'socks5://127.0.0.1:9050'}
return session

# Make a request through the Tor connection
# IP visible through Tor
session = get_tor_session()
print(session.get("http://httpbin.org/ip").text)
# Above should print an IP different than your public IP

# Following prints your normal public IP
print(requests.get("http://httpbin.org/ip").text)

But i see:
requests.exceptions.InvalidSchema: Missing dependencies for SOCKS support.

What should I do?
Thanks

A: In order to make requests use socks proxy, you need to install it with it's dependency.
pip install requests requests[socks]

A: This means that requests is using socks as a proxy and that socks is not installed.
Just run  pip install pysocks


text:
Q: Regular expression not working as intended when I use an emoji at the beginning of a string My code is written in PHP. I am trying to store in my database subjects of the emails that I send, only after I remove the emojis that I include in the subject lines of those emails. I created this regular expression:
$cleansubject = preg_replace("/[^a-zA-Z0-9\s]/", "", $subject);

It works when I have the emoji at the end of the string, such as:

But if the emoji I have it at the beginning of the string, it does not work, the entry is not even stored in my database:

Any issues that you can identify in my regular expression to achieve what I want?
UPDATE 1: Apparently the regular expression is just fine:

A: This could be an encoding problem (3v4l example):
echo utf8_encode('⌨,,, Learning Online: Digital Marketing Course');
// Output: ⌨ï¸,🖥,🖨, Learning Online: Digital Marketing Course

When you try to match using your pattern this fails (see here), but if you instead match any number of non-word characters without the global flag like here you match the whole emoji.
And using preg_match() this becomes:
$re = '/\W*/';
$str = 'â¨ï¸,ð¥,ð¨, Learning online: Digital Marketing Course';
$subst = '';

$result = preg_replace($re, $subst, $str, 1);

echo "The result of the substitution is ".$result;
// Output: Learning online: Digital Marketing Course

A: Add the "u" modifier to your regular expression to make it treat strings as UTF-8.
$cleansubject = preg_replace("/[^a-zA-Z0-9\s]/u", "", $subject);

Or use a built-in function to remove the Unicode characters from your string, eg iconv, utf8_decode, mb_convert_encoding, or recode.
$cleansubject = trim(iconv('UTF-8', 'ASCII//IGNORE', $subject));


text:
Q: HR Easy Blog WordPress theme logo removal Currently for a blog of mine I'm using HR Easy Blog WordPress theme. There I have a problem on how to remove the HR Easy Blog logo on the home page. I tried several methods but nothing worked for me.enter image description here

A: You need to go to your theme's header.php file and remove or comment below code:

    <a href="<?php echo home_url(); ?>" title="<?php bloginfo('name'); ?>"><?php $logo = (get_option('hires_logo') <> '') ? get_option('hires_logo') : get_template_directory_uri().'/images/logo.png'; ?><img src="<?php echo $logo; ?>" alt="<?php bloginfo('name'); ?>" id="logo"/>

        <?php /* Home Ad #1 */
        if( get_option('hires_ad_480_60_enable') == 'on'){
            echo '
';
            echo get_option('hires_ad_480_60_code');
            echo "
";
        } ?>


text:
Q: Extending generic typing for the nested Object I want to dynamically set a type for the record of the interfaces.
interface ChildInput<V> = {value: V};

Now, I would like to have a record of different ChildInput<V>s.
So, ParentInput would look like something like this:
interface ParentInput<Keys extends string, T> /*this is the point of the question*/ = {
  [index: Keys]: ChildInput<?> /*this is the point of the question*/
}

for example:
const parentInput =  {
  foo: {value: 2},
  bar: {value: 'bar'},
  foobar: {value: true},
  .
  .
  .
}

expected result for the parentInput should be something like this:
interface ParentInput {
  foo: ChildInput<number>,
  bar: ChildInput<string>,
  foobar: ChildInput<boolean>,
}

Number of keys having ChildInput type in parentInput variable is not known. Also the type of the value.
I want to find a way, given the variable, dynamically types the parentInput with right types for the ChildInput.
The question for me is hard to formulate and explain. Please write for more clarification.

A: The key problem here is that you need to map from the name/key to a type. The only way to do this is with a fully defined object type literal or interface. So we can provide a simpler interface as a generic input and then use a mapped type to translate this into the resultant shape.
interface ChildInput<T> {
    value: T
}

type ParentInput<T> = {
    [K in keyof T]: ChildInput<T[K]>
}

type Example = ParentInput<{
    foo: number,
    bar: string,
    foobar: boolean
}>

// Example will be
// {
//   foo: ChildInput<number>,
//   bar: ChildInput<string>,
//   foobar: ChildInput<boolean>,
// }

This may only be useful is ChildInput is more complicated or you use this mapping in a lot of types so that it is saving more redundancy.


text:
Q: Html2Canvas rendered picture showing borders/grid of table i am trying to export a div with html2canvas to pdf. Inside the div are 4 Tables.
The Problem is the output in the pdf, because the grid/borders of the table are visible in default black, but i set any border-colors to transparent. Surprisingly the random-lines hide when i zoom inside the generated pdf.
Do you know how to prevent thees unwanted lines?
Picture below...

Backend-code where i add the picture to the pdf-document...
        base64 = hfImageData2.Value.Split(',')[1];
        bytes = Convert.FromBase64String(base64);
        iTextSharp.text.Image img2 = iTextSharp.text.Image.GetInstance(bytes);
        img2.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
        img2.ScalePercent(2000);
        img2.ScaleToFit(790, 700);
        document.Add(img2);

html2canvas javascript where i save the div to hiddenfield...
        function ConvertToImage(btnExport) {
            html2canvas($("#containerChart")[0]).then(function (canvas) {
                var base64 = canvas.toDataURL();
                $("[id*=hfImageData]").val(base64);
                __doPostBack(btnExport.name, "");
            });
            return false;
        }

The div element...


text:
Q: SQL Select if any child or subchild has a value I have two tables, Categories and Articles. Articles have a FK relating them to a category. The Category table is hierarchical, so each category has a CAT_FK_Parent pointing to another Category, or NULL if it is a top level category.
What I am trying to do is sort the Articles by Category, and only display categories from the list that either have an article directly associated with it, or categories that have a child/subchild that have an Article associated.
So right now my code looks like:
SELECT  TOP 1000 [CAT_PK]
  ,[CAT_Description]
  ,[CAT_FK_Parent]
  ,[CAT_CanHaveChildren]
  ,[CAT_EMP_FK]
  ,[CAT_Action]
  ,[CAT_Active]
  ,[CAT_Autoclose]
  ,[CAT_ROL_Name]
FROM [TicketCategories]
WHERE
((SELECT COUNT(1) FROM WikiArticles WHERE WAR_CAT_FK = CAT_PK AND WAR_Active=1) ) > 0

This returns categories with a WAR_CAT_FK equal to themselves, but does not take children into account.
Since Categories can have any number of child levels under them, I assume I need some kind of recursive function to do a count of all children, but I'm having trouble finding resources for recursive WHERE conditions.

A: You should use joins to do this not a sub-query, much faster.

*

*First join to Articles

*Then join to Children categories that have articles

*Then check to see if one of the join to article exists (is not null)

*Finally Group By or DISTINCT to remove duplicate rows

.
SELECT DISTINCT TOP 1000
   TC.CAT_PK
  ,TC.CAT_Description
  ,TC.CAT_FK_Parent
  ,TC.CAT_CanHaveChildren
  ,TC.CAT_EMP_FK
  ,TC.CAT_Action
  ,TC.CAT_Active
  ,TC.CAT_Autoclose
  ,TC.CAT_ROL_Name
FROM TicketCategories TC
LEFT JOIN WikiArticles WA ON TC.WAR_CAT_FK = WA.CAT_PK AND WA.WAR_Active=1
LEFT JOIN TicketCategories Child ON TC.CAT_PK = Child.CAT_FK_Parent
LEFT JOIN WikiArticles CWA ON Child.WAR_CAT_FK = CWA.CAT_PK AND CWA.WAR_Active=1
WHERE
  COALESCE(WA.CAT_PK,CWA.CAT_PK) IS NOT NULL


text:
Q: CodeAnalysis using msbuild does not fail on warning/error I started down this path of wanting to do code analysis on my solution using msbuild. I was looking at FxCop but it appears to now be part of Visual Studio and from my understanding you need Visual Studio installed on your build agents.
I am calling msbuild from a powershell using the following command;
"$(get-content env:systemroot)\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe /tv:4.0 /p:RunCodeAnalysis=Always"

It appears to run the code analysis and output warnings but never fails the build, even after I added  <CodeAnalysisTreatWarningsAsErrors>true</CodeAnalysisTreatWarningsAsErrors>
to my .csproj file.
All I want is to run code analysis from msbuild command line and have it fail the build if any warning is found. I understand it can be done in Visual Studio but I need to be able to run this from the command line (with/without VS2013)
Am I missing something? Shouldn't /p:RunCodeAnalysis=Always and setting the CodeAnalysisTreatWarningsAsErrors to true be all that is needed?


text:
Q: Validate JSON array length I am trying to write an if statement that determines whether the getDept JSON array contains more than one value. If it does, then redirect to a different page. Through my research, it seems like it is as simple as getDept.length > 1, I have not been able to make this work though.
My Javascript code is as follows:
$.getJSON("https://apex.oracle.com/pls/apex/mfajertest1/department/"+$x('P2_DEPT_NO').value, function(getDept)
{
    console.log(getDept);
    if(getDept.length == 0)
        {
                window.alert("No Department with that ID");
        }
    else if(getDept.length > 1)
        {
                apex.navigation.redirect('f?p=71293:11');
        }
    else
        {
    $x('P2_DEPT_NAME').readOnly = false;
    $x('P2_DEPT_NAME').value=getDept.items[0].dname;
    $x('P2_DEPT_NAME').readOnly = true;
    $x('P2_DEPT_LOC').readOnly = false;
    $x('P2_DEPT_LOC').value=getDept.items[0].loc;
    $x('P2_DEPT_LOC').readOnly = true;
    $x('P2_DEPT_NO').readOnly = true;
  }
});

The getDept JSON array contains this information:
{
    "next": {
        "$ref": "https://apex.oracle.com/pls/apex/mfajertest1/department/%7Bid%7D?page=1"
    },
    "items": [
        {
            "deptno": 10,
            "dname": "accounting",
            "loc": "madison"
        },
        {
            "deptno": 20,
            "dname": "Finance",
            "loc": "Milwaukee"
        },
        {
            "deptno": 30,
            "dname": "IT",
            "loc": "La Crosse"
        },
        {
            "deptno": 40,
            "dname": "Purchasing",
            "loc": "Green Bay"
        },
        {
            "deptno": 10,
            "dname": "Accounting II",
            "loc": "Madison II"
        },
        {
            "deptno": 50,
            "dname": "Sports",
            "loc": "Waukasha"
        }
    ]
}

I would be glad to provide more information regarding this issue if need be.

A: Your JSON response is actually an object, not an array. The array you're checking for is a property inside that object called items. Thus, wherever you are using getDept, you should instead be using getDept.items:
$.getJSON("https://apex.oracle.com/pls/apex/mfajertest1/department/"+$x('P2_DEPT_NO').value, function(getDept)
{
    console.log(getDept.items);
    if(getDept.items.length == 0)
        {
                window.alert("No Department with that ID");
        }
    else if(getDept.items.length > 1)
        {
                apex.navigation.redirect('f?p=71293:11');
        }
    else
        {
    $x('P2_DEPT_NAME').readOnly = false;
    $x('P2_DEPT_NAME').value=getDept.items[0].dname;
    $x('P2_DEPT_NAME').readOnly = true;
    $x('P2_DEPT_LOC').readOnly = false;
    $x('P2_DEPT_LOC').value=getDept.items[0].loc;
    $x('P2_DEPT_LOC').readOnly = true;
    $x('P2_DEPT_NO').readOnly = true;
  }
});


text:
Q: Should em.flush be used in EJB 3.0 DAOs to abstract persistence layer? Say I have following generic dao deployed as a local SLSB:
public interface CrudService {

public <T> T create(T t);

public <T> T find(Object id, Class<T> type);

public <T> T update(T t);

public void delete(Object t);

public List<Object> findByNamedQuery(String queryName);

public List<Object> findByNamedQuery(String queryName, int resultLimit);

public List<Object> findByNamedQuery(String namedQueryName, Map<String, Object> parameters);

public List<Object> findByNamedQuery(String namedQueryName, Map<String, Object> parameters, int resultLimit);

}
This DAO is used from many other SLSB services. I'd like to abstract whole persistence layer (all operations and exceptions) from business logic. I created an interceptor with @AroundInvoke method like below and put it on DAO's class level:
    @AroundInvoke
public Object wrapExceptions(InvocationContext context) throws Exception {
    try {
            return context.proceed();
    } catch(Exception e) {
              throw mapToApplicationException(e)
    }
}

No exception is caught and therefore mapped having default implementations of dao methods.
But if I use flush at the end of persist, update and delete methods it works - and that's ok.
Now my question is: is it the only way to get it working? I know that calling flush is quite heavy and if I need to call let's say update multiple times it's gonna be a serious bottleneck.
Edit:
another option is to use BMT, but it causes all facade methods to be polluted with tx.begin() etc...
EDIT after Kris Babic answer:
I have some doubts according to Kris proposal. Dealing with PersisteceExceptions in service layer causes mixing of layers transparency. But this is not the worst for me. Say that I have Service Facade using set of my services or DAOs. Service Facade method need to be executed on it's own transaction so I'd use CMT and mark it with @TransactionAttribute(REQUIRES_NEW). Doing that way there is no place to have exceptions handling point (interceptor won't work, because transaction is still ongoing - this is the same case as above). So I see two ways: either have all facade methods use BMT and deal with all the tx.begin(), tx.commit() etc. stuff, or have another "Facade for Facade" having @TransactionAttribute(NEVER) and then call transactional facade and handle it's exceptions.

A: I guess it all depends on what you are trying to do.  If you are expecting all data to be immediately inserted into the database and any problems caused by that insertion to be immediately available, then you really only have two options: specifically call flush() on the EntityManager which will cause all batch datasource operations to be executed, or  specify that a transaction to start and end at the DAO method (there are different options for that, but I won't go into them here).  Both of these options can have negative affects on performance and on successful business transaction definition.
One of the features in a JPA implementation is the idea of a PersistenceContext.  The PersistenceContext is a set of managed Entities.  The lifecycle of these entities are managed by the EntityManager.  Part of EntityManager's responsibility is to manage when changes to the PersistenceContext get synchronized with the data source.  It is possible that the EntityManager batches together a number of changes to the PersistenceContext and synchronizes them at a later point such as during the transaction commit.  In this case, if there is a problem with the data being inserted into the database, you may not see the exception being raised until sometime later.  A call to em.flush() causes the data source synchronization to occur immediately, which in turn raises any exceptions which may occur during that database insert.
One good approach to exception handling is to only add it where you need it.  Adding it to a bottom layer method that throws RuntimeExceptions is not necessarily a good candidate.  If the idea is to add consistant error handling, such as the conversion to a common RuntimeException, then you would want to do so at a common entry point, such as the business layer or similar.  This allows you to limit the overall amount of exception handling you need to maintain, especially since errors can really occur anywhere in the application.  I would also suggest that you have exception handling at your main transaction entry points as that is where you will need to manage any unexpected exception which may only occur during transaction commit, especially when using optimistic locking.
Just some thoughts, hopefully they help.


text:
Q: jQuery generate multiple arrays and generate HTML I have a website that where a user can browse through products in a gallery format. This  gallery will be populated using an ajax call that passes the category to a php script which then fetches all the items matching that category and echoes all the item information back. The  success function of the  ajax  call then needs to split the data and insert each  items data  into its own array that will  be used to generate the  html to display the item.
I  am  struggling with the  inserting the data into its own array part as the   amount  of items will vary depending on how many are in the database at the  moment.
Here  is  what I have  so far:
The  jQuery function:
$('.category').click(function() {

    var category;

    if ($(this).hasClass('Shirts')) {
        category = 'shirts';
    }
    if ($(this).hasClass('Hats')) {
        category = 'hats';
    }
    if ($(this).hasClass('Acc')) {
        category = 'acc';
    }

    $.ajax({
        type: 'GET',
        url: 'galleryfetch.php',
        data: { 'category' : category }
    }).done(function(data) {
        alert('Succes ' + data);
        var arr = data.split('#');  // Information split by #
        for (int i = 0; i < (arr.length / 4); i++) { //  arr.length divided by 4 because each item has 4 pieces of information

            // Insert each item into its own array. So the first  array will be arr[0], arr[1], arr[2], arr[3]. Second array will be  arr[4], arr[5], arr[6], arr[7]
        }

    }).fail(function(response) {
        alert('Fail' + response);
    });
});

Here  is the  php script:

if ($_SERVER['REQUEST_METHOD'] == 'GET') {

    $category = $_GET['category'];

    $conn = mysqli_connect('localhost', 'root', 'Changde90', 'database');

    $rows = mysqli_query($conn, "SELECT * FROM products WHERE category = '".$category."'");

    $items = '';

    while ($row = mysqli_fetch_array($rows)) {
        $itemName = $row[1];
        $itemPrice = $row[2];
        $itemImage = $row[3];
        $itemDescription = $row[4];

        $items .= $itemName.'#'.$itemPrice.'#'.$itemImage.'#'.$itemDescription.'#';
    }

    echo $items;
}

A: Create the array in php like this :
while ($row = mysqli_fetch_array($rows)) {
    $arr[] = $row;
}
echo json_encode(array("data" => $arr));

Then in your javascript just decode the data and use it in your code as you like it.
For example :
var arr = $.parseJSON(data);
arr.itemName will return the item name
arr.itemprice will return the item price

Remember you have use the above code inside of $.each()
Hope this helps you.


text:
Q: R: Create new column by finding all numbers that are more or less than another given number in the same column with a condition in a dataframe I have the following df
df <- structure(list(position = c(44188968, 44188969, 44188970, 44188975,
44188977, 44188978), code1 = c(1, 0, 1, 0, 0, 1)), class = "data.frame", row.names = c(NA,
-6L))

>df
position    code1
44188968    1
44188969    0
44188970    1
44188975    0
44188977    0
44188978    1

I would like to add another column code2 (1 if true, 0 otherwise) when the following condition is true:

*

*for each position, check if the other positionsare located +/- 3 away. If true, the other position must have code1 = 1.

I would then obtain something like below
position    code1  code2
44188968    1      1
44188969    0      1
44188970    1      1
44188975    0      0
44188977    0      1
44188978    1      0

Could you please instruct me on how to achieve such table ?
EDIT: I forgot to mention that my data contains NA values
position    code1
44188968    1
44188969    0
44188970    1
44188975    0
44188977    0
44188978    1
NA          1
NA          0
44189323    NA

In case of NA values, code2 is also NA
EDIT2: As requested by @jazzurro, I am giving all possible patterns for my data
df <- structure(list(position = c(44188968, 44188969, 44188970, 44188975,
44188977, 44188979, 44188980, 44189323, 44189324, 44189328, 44189330,
44189334), code1 = c(1, 0, 1, 0, 0, 1, NA, NA, 1, NA, NA, NA)), class =
"data.frame", row.names = c(NA,
-12L))

>df
position    code1
44188968    1
44188969    0
44188970    1
44188975    0
44188977    0
44188979    1
44188980    NA
44189323    NA
44189324    1
44189328    NA
44189330    NA
44189334    NA

The desired output is the following:
position    code1   code2   # explanations
44188968    1       1       # code2 is 1 because 44188970 falls in the window of +/- 3 and code1 of 44188970 is 1. code1 of 44188969 is 0 so it is not taking into account.
44188969    0       1       # code2 is 1 because 44188968 or 44188970 falls in the window of +/- 3 and code1 of 44188968 or 44188970 is 1.
44188970    1       1       # code2 is 1 because 44188968 falls in the window of +/- 3 and code1 of 44188968 is 1.
44188975    0       0       # code2 is 0 because 44188977 falls in the window of +/- 3 but code1 of 44188977 is 0.
44188977    0       1       # code2 is 1 because 44188978 falls in the window of +/- 3 and code1 of 44188978 is 1. code1 of 44188975 is 0 so it is not taking into account.
44188979    1       0       # code2 is 0 because 44188977 falls in the window of +/- 3 but code1 of 44188977 is 0. code1 of 44188980 is NA so it is not taking into account.
44188980    NA      1       # code2 is 1 because 44188977 falls in the window of +/- 3 and code1 of 44188977 is 0.
44189323    NA      1       # code2 is 1 because 44189324 falls in the window of +/- 3 and code1 of 44189324 is 1.
44189324    1       0       # code2 is 0 because 44189323 falls in the window of +/- 3 but code1 of 44189323 is NA.
44189328    NA      0       # code2 is 0 because 44189330 falls in the window of +/- 3 but code1 of 44189330 is NA.
44189330    NA      0       # code2 is 0 because nothing falls in the window of +/- 3.
44189334    NA      0       # code2 is 0 because nothing falls in the window of +/- 3.

Thank you in advance.

A: Here is my attempt. Given the communication above, the range you are talking about is +/- 2 (3 is not inclusive). I created two numeric vectors, which are for identifying a range with plus/minus 2 with each position. Then, I ran a logical check. Check if there is any position number that stays in each range and code is equal to 1. Then, I unnested the list, check and created a new column called dum_position. I extracted rows that do not have an identical number in position and dum_position, and check is TRUE. By this time, numbers in position are the ones we want to find.
library(tidyverse)

mutate(df, check = map2(.x = position - 2,
                        .y = position + 2,
                        .f = function(x, y) {between(position, x, y) & code1 == 1})) %>%
unnest(check) %>%
group_by(position) %>%
mutate(dum_position = df$position) %>%
filter(position != dum_position & check == TRUE) %>%
distinct(position) %>%
unlist -> mynums

# Add 1 to the rows that have one of the numbers in mynums
mutate(df, code2 = if_else(position %in% mynums, 1, 0))

#  position code1 code2
#1 44188968     1     1
#2 44188969     0     1
#3 44188970     1     1
#4 44188975     0     0
#5 44188977     0     1
#6 44188978     1     0

A: Another solution using cross joins.
First create a lookuptable where you check for where code1 == 1 (df2)
df1 = df %>% mutate(cross = 'cross')
df2 = df %>% filter(code1 == 1) %>% mutate(cross = 'cross')

Secondly, cross join the tables, apply the filter and aggregate the results.
df3 = df1 %>% full_join(df2, by = 'cross') %>% group_by(position.x) %>% mutate(x = if_else(
  position.x < position.y & position.x > position.y - 3
  |
    (position.x > position.y &
       position.x < position.y + 3)

  ,
  1,
  0
)) %>% slice(which.max(x)) %>% select(position = position.x,
                                      code1 = code1.x,
                                      code2 = x)


text:
Q: sharing & storing IV for AES Encryption/decryption I am currently using AES-ECB encryption for user passwords on an android app, but I have to connect this app's database to a website where users can register and log in the same way as the mobile app.
I have read that ECB mode is not secured, so I wanted to use CBC by generating an IV.
Is it secure to store an IV as a constant in the code (I store the secret key this way too), both in php on the server side, and in the app ?
If not, is there a way for the website and the mobile app to share it's IV to encrypt /decrypt user password ?
Alternatively, I may have chosen the wrong encryption algorithm, there might be one that better suit my needs

A: Best practice would be to create a new random IV for each encryption. The IV is basically a seed for that encryption call used in the first block.
Each IV can be safely stored in clear text along with the cypher text so it is available when decrypting the cypher text (the IV used to encrypt must be the same IV used to decrypt).

A: If you are fixed with this algorithm, I may suggest - not to share IV from encrypting end to decrypting end.
Dummy Blocks
    Add an initial dummy block of 16 bytes before your actual message block of 16 bytes. So that, even if you are not sharing IV to the Decrypting End, as AES-CBC is a chaining mode, the first block (dummy block) at Decrypting end will be corrupted and rest of the blocks are not affected.
Encrypting End
As per CBC mode in AES, In CBC mode, each block of plaintext is XORed with the previous ciphertext block before being encrypted.
To make each message unique, an initialization vector must be used in the first block.
Refer: http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
Decrypting End
Decrypting with the incorrect IV causes the first block of plaintext to be corrupt but subsequent plaintext blocks will be correct.
This is because a plaintext block can be recovered from two adjacent blocks of ciphertext.


text:
Q: Awk pattern always matches last record? I'm in the process of switching from zsh to bash, and I need to produce a bash script that can remove duplicate entries in $PATH without reordering the entries (thus no sort -d magic). zsh has some nice array handling shortcuts that made it easy to do this efficiently, but I'm not aware of such shortcuts in bash. I came across this answer which has gotten me 90% of the way there, but there is a small problem that I would like to understand better. It appears that when I run that awk command, the last record processed incorrectly matches the pattern.
$ awk 'BEGIN{RS=ORS=":"}!a[$0]++' <<<"aa:bb:cc:aa:bb:cc"
aa:bb:cc:cc
$ awk 'BEGIN{RS=ORS=":"}!a[$0]++' <<<"aa:bb:cc:aa:bb"
aa:bb:cc:bb
$ awk 'BEGIN{RS=ORS=":"}!a[$0]++' <<<"aa:bb:cc:aa:bb:cc:" # note trailing colon
aa:bb:cc:

I don't understand awk well enough to know why it behaves this way, but I have managed to work around the issue by using an intermediate array like so.
array=($(awk 'BEGIN{RS=":";ORS=" "}!a[$0]++' <<<"aa:bb:cc:aa:bb:cc:"))
# Use a subshell to avoid modifying $IFS in current context
echo $(export IFS=":"; echo "${array[*]}")
aa:bb:cc

This seems like a sub-optimal solution however, so my question is: did I do something wrong in the awk command that is causing false positive matches on the final record processed?

A: The last record in your original string is cc\n which is different from cc. When unsure what's happening in any program in any language, adding some print statements is step 1 to debugging/investigating:
$ awk 'BEGIN{RS=ORS=":"} {print "<"$0">"}' <<<"aa:bb:cc:aa:bb:cc"
<aa>:<bb>:<cc>:<aa>:<bb>:<cc
>:$

If you want the RS to be : or \n then just state that (with GNU awk at least):
$ awk 'BEGIN{RS="[:\n]"; ORS=":"} !a[$0]++' <<<"aa:bb:cc:aa:bb:cc"
aa:bb:cc:$

The $ in all of the above is my prompt.

A: Another possible workaround instead of your bash array solution
$ echo "aa:bb:cc:aa:bb:cc" | tr ':' '\n' | awk '!a[$0]++' | paste -sd:
aa:bb:cc


text:
Q: GTA IV lag on powerful laptop I get about 15-20 FPS in GTA IV. I should be able to run it on the highest setting with over 60 FPS.
I have tried to lower all the settings to low, but it doesn't improve my performance at all, not even by 1 FPS. I was thinking there was some sort of FPS limit somewhere; could that be the case?
Specs
CPU: Intel Core i7
GPU: Nvidia GeForce GTX 675m/ 2GB
RAM: 8GB
as you see the should be no problem...

A: Without lowering your graphics
Right-click on GTA 4 in Steam, and click on Properties.
Click on Set Launch Options... and a window with a TextBox will appear.
In that TextBox, paste these arguments:
-nomemrestrict -norestrictions

and GTA 4 should run with a huge speedup.
On my rig
i7 3770K
32 GB RAM
GeForce GTX 680
GTA used to run on max settings at around 20-35 FPS.
With these arguments, it runs between 50 and 55 FPS and averages at ~52 FPS.
With lowering your graphics
Interestingly, GTA doesn't seem to care about GPU so much, as there is almost no difference between playing with a 1920x1080 or 800x600 resolution.
The only settings that seem to yield any significant increase in FPS is View Distance and Detail Distance, which should be lowered together. With both set to 1, my max FPS went from 55 to 140, although the average FPS only increased from 52 to 55. I wouldn't recommend setting them both to 1, as it can introduce some odd graphical glitches, such as signs seemingly floating in midair, until you get close enough for the sign's support to pop into view.
You might want to set the ingame option Definition: On, which will deactivate Motion Blur (yes, On == deactivate) and earn you an additional 5-20 FPS when driving fast enough for aforementioned Motion Blur to kick in.
About why GTA fails to start
According to this wiki the problem may be caused by an out-of-date GFWL client, or because of your MTU size.

A: Grand Theft Auto IV had an awful lag that was fixed in a patch. Make sure it is up to date. I had the same issue ages ago and updating fixed it nicely. Hope this helps!

A: Are you sure you are launching the game using you Nvidia Video card and not your on board laptop card?
Find the .exe that you are launching. Right click on and there should be an option open with Nvidia card.

A: I found a solution on this youtubevid:

Seems like the problem is windows keylogger.
It worked for me, hope it'll work for you :-)

A: I don't know how powerful your graphics card is, but have you tried lowering your resolution?
A lot of the time graphics cards aren't built to handle the higher resolutions when running a game.

A: What might be the case is having active Monitor Mirroring drivers installed and running.
Some examples:

*

*Teamviewer

*LogMeIn

*VNC

Any software that allows remote connections to see the desktop of your computer has the potential to cause such problems. Try uninstalling them, as simply exiting them does not stop the mirror drivers.

A: In the main GTA IV folder, create a text file and name it commandline.txt. Edit the file with a text editor, like Notepad to contain the following text:
availablevidmem 8


text:
Q: Is it possible to have a Javascript variable to have two or more functions inside? I have the following Javascript code:
    var Lab = {
        minseat: function(){
            var seat = 10;
            return seat;
        }

        maxseat: function(){
            var seat = 50;
            return seat;
        }

     }

So, when I need to get the value, I simply call the following code:
    console.log(" Min Seat: " + Lab.minseat());
    console.log(" Max Seat: " + Lab.maxseat());

However, it seems it is not working. So, may I know if it is possible to have a Javascript variable to have two or more functions inside?

A: You forgot a comma after the first function:
var Lab = {
    minseat: function(){
        var seat = 10;
        return seat;
    },

    maxseat: function(){
        var seat = 50;
        return seat;
    }

 }

A: How about a comma separating the keys in your object definition.
    var Lab = {
        minseat: function(){
            var seat = 10;
            return seat;
        },
        maxseat: function(){
            var seat = 50;
            return seat;
        }

     }

http://jsfiddle.net/V4Yje/


text:
Q: ArcGIS shared update group I would like to create a shared update group on ArcGIS, however, the "what items in the group can members update?" question is missing and I can´t, therefore, tag it. The questionnaire just ends after "Who can contribute content?" (s. picture). Has this option been removed?

A: The option is now embedded in the group designation settings:


text:
Q: Using One Variable Parameter Inside Another Method So I'm trying to have some methods for my class called test, and the methods get a variable from the driver. There are some methods that are supposed to get the return value from the getter methods.
Main Class:
public class test {
    public int setSpeed(int speed) {
        return speed;
    }
    public void getSpeed() {
        //I don't know what to put here
    }
}

Driver:
public class testDriver {
    test b = new test();
    b.setSpeed(25);
    System.out.println("The Speed is: ", b.getSpeed());
}

I have to use a regular int in the driver; I cannot assign its value to a variable.

A: Your test class should look like this:
public class test {
    private int speed;
    public void setSpeed(int speed) {
        this.speed = speed;
    }
    public int getSpeed() {
        return this.speed;
    }
}

Basically you are not suppose to return something when you are setting a value. You are suppose the return a value when you are getting something


text:
Q: PHP if condition doesn't work My html form
<form id="myForm">
    Select Class:
    <select class="form-control" id="class_name">
    <?php $query=$con->query("SELECT * FROM class ORDER BY id ASC") or die($con->error);
        while($row=$query->fetch(PDO::FETCH_ASSOC)){ ?>
            <option value="<?php echo $row['id']?>"><?php echo $row['class_name']?></option>
        <?php } ?>
     </select>
    Add Section:
    <input type="checkbox" name="section_name" value="A">A
    <input type="checkbox" name="section_name" value="B">B
    <input type="checkbox" name="section_name" value="C">C
</form>

Ajax

I am inserting array data in database through ajax. Insertion of data succeeded without implementing any condition. When I try to implement if condition, it doesn't work. What is error in following code
<?php
include "connect.php";
$class_id = $_POST['class_id'];
$section_name = $_POST['section_name'];
$section_name = implode(",",$section_name);
$query=$con->query("SELECT * FROM section") or die($con->error);
while($row=$query->fetch(PDO::FETCH_ASSOC)){
    if(($class_id==$row['class_id'])&&($section_name==$row['section_name'])){
        echo json_encode('Section -'.$section_name.' has already assigned in '.$class_id);
    }
    else{
        $query2=$con->query("INSERT INTO section(class_id,section_name) VALUES('$class_id','$section_name')") or die($con->error);
    echo json_encode($section_name);
    }
}
?>

A: You are imploding the $_POST section list
$section_name = implode(",",$section_name);

so this condition may not work :
$section_name==$row['section_name']

depending on your $_POST section ordering


text:
Q: Powershell bitwise comparison for robocopy exit codes I can't get my head around this bitwise conversion problem.
Robocopy exit codes don't conform to the normal 0(success), 1(failure) pattern so I want to wrap my robocopy calls in the powershell script below to make my TeamCity build configurations fail or proceed appropriately when robocopy terminates.
That first part was solved using a tip from the net with: ($LastExitCode -band 24) which correctly treats exit codes 8 through 16 as failures (1) and all others as success (0).
Now I want to echo a message corresponding to the exit code. How do I convert and round/floor the integer exit code (0 - 16) to its hexadecimal equivalent (0x00 - 0x10)?
param(
    [string] $source,
    [string] $target,
    [string[]] $action = @("/MIR"),
    [string[]] $options = @("/R:2", "/W:1", "/FFT", "/Z", "/XA:H")
)
$cmd_args = @($source, $target, $action, $options)
& robocopy.exe @cmd_args
$returnCodeMessage = @{
    0x00 = "[INFO]: No errors occurred, and no copying was done. The source and destination directory trees are completely synchronized."
    0x01 = "[INFO]: One or more files were copied successfully (that is, new files have arrived)."
    0x02 = "[INFO]: Some Extra files or directories were detected. Examine the output log for details."
    0x04 = "[WARN]: Some Mismatched files or directories were detected. Examine the output log. Some housekeeping may be needed."
    0x08 = "[ERROR]: Some files or directories could not be copied (copy errors occurred and the retry limit was exceeded). Check these errors further."
    0x10 = "[ERROR]: Usage error or an error due to insufficient access privileges on the source or destination directories."
}
Write-Host $returnCodeMessage[($LastExitCode <what goes here?>)]
exit ($LastExitCode -band 24)

A: In your case you do not need to convert it.
You do not need conversion because Hashtable keys are converted to [int] on pre-compiation stage.
If you lookup for $returnCodeMessage.Keys , you will see decimal numbers, not hex numbers
To display all messages you should use
$exitcode = $LastExitCode
Write-Host $( @( $returnCodeMessage.Keys | Where-Object { $_ -band $exitcode } | ForEach-Object {return $returnCodeMessage[$_]}   ) -join "`r`n")

IF you want to show Hex-encoded $LastExitCode, do
$exitcode = $LastExitCode
Write-Host $('0x' + [System.Convert]::ToString([int]$exitcode,[int]16) )
return $exitcode

String System.Convert.ToString(Int32, Int32)

A: As filimonic mentioned, 0x10 and 16 are just different ways of writing the same underlying numeric value (i.e. 0x10 -eq 16 evaluates to true), so no conversion is needed.
To display each message in the combined return code, you can test each of the individual flag values in turn:
if( $returnCodeMessage.ContainsKey( $LastExitCode ) ) {
    $returnCodeMessage[$LastExitCode]
}
else {
    for( $flag = 1; $flag -le 0x10; $flag *= 2 ) {
        if( $LastExitCode -band $flag ) {
            $returnCodeMessage[$flag]
        }
    }
}

For a return code like 0x00 (no change) or 0x04 (mismatch) that contains only one message, we look it up directly. Otherwise, for a composite code like 0x09 (some copied, some not) or 0x13 (some copied, some extras, access denied), we check for each possibility and output those that match.
Also, since "Any value greater than 8 indicates that there was at least one failure during the copy operation", you could use $LastExitCode -ge 8 instead of $LastExitCode -band 24 to test for errors.


text:
Q: Complex Comparators in java 8 Can some one explain the difference between following variants of complex Comparators?
List<String> listOfStrings = Arrays.asList("algo", "test", "is", "a", "common");

listOfStrings.stream()
             .sorted(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()))
             .sorted(Comparator.naturalOrder().thenComparing(Comparator.comparingInt(String::length))
             .forEach(System.out::println);

Why first call of sorted is OK, while second one can not even compile?

A: The compiler knows that Comparator.comparingInt(String::length) returns a Comparator<String> (since you are passing a ToIntFunction<String> to it), and therefore expects the second Comparator, passed to thenComparing, to be a Comparator<String>, so it can infer the type of the Comparator returned by Comparator.naturalOrder() to be a Comparator<String>.
On the other hand, when the first Comparator is returned by Comparator.naturalOrder() (which returns a Comparator<T>), the compiler doesn't know which type of Comparator to expect for the argument of thenComparing, so it rejects the Comparator<String> passed to it.
This error can be avoided if you declare the type of the Comparator returned by Comparator.naturalOrder() explicitly:
Comparator<String> comp = Comparator.naturalOrder();
listOfStrings.stream()
             .sorted(comp.thenComparing(Comparator.comparingInt(String::length)))
             .forEach(System.out::println);

A: *

*comparingInt(ToIntFunction keyExtractor)

Accepts a function that extracts an int sort key from a type T, and returns a Comparator that compares by that sort key.

*naturalOrder()

Returns a comparator that compares Comparable objects in natural order.
You can check natural order from there;
difference between natural ordering and total ordering
Comparator API;
https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#naturalOrder--


text:
Q: encrypted password with sonataadminbundle and fosuserbundle In sf2.3 i am using fosuserbundle for usermanagement and sonataadminbundle for admin management.
When i try to create a new user in the admin i create the form field
->add('plainPassword');

But whenever i persist to the database the userbundle doesnt generate the encrypted password out of the plain password, which means it must be possible to use the usermanagement within the sonataadminbundle.
How to correct set password and persist the encrypted password to the database?
Thank you

A: I suspect you are not using the fos user manager to persist your object?
$userManager = $this->get('fos_user.user_manager');
$userManager->update($user,true);

The update method takes care of encrypting the passwords as well as several other items such as canocalizating   the user name and email.  The doc files have more information.


text:
Q: In Java, what are the semantics of an array as an object? According to this question (Is an array an object in java), arrays are considered objects in Java.
The answers to that question mainly cite references to the language specification. My question is what methods and fields does that object have? Can I instantiate it directly (int[] myArr = new Array<int>(), or something similar)? In short, how does it work?
A quick search yielded no results. I see the JavaDoc for the Arrays object (used for sorting arrays, etc), but not JavaDoc for an Array.
Edit:
Just to be clear, I am NOT trying to learn to use an array for the first time. I am asking a question about the mechanics of the java language. I know I can create an array:
int[] a = new int[3];

I'm asking if there is a different way to do it - since it is an object, is there an object constructor that works? Is there documentation on the array object?

A: Arrays have a public final length attribute. They implement the Cloneable and Serializable interfaces. And of course, they inherit all methods from Object (equals(), hashCode(), wait(), etc.).
There is no class that you can use to construct an instance as you're trying in your question. The syntax to instantiate them is
int[] myArr = new int[someLength];

or, to populate them with non-default values;
int[] myArr = new int[] {1, 2, 3};

You can also use
int[] myArr = {1, 2, 3};

But note that you can't use this short syntax to assign a value to a previously declared variable. I.e. you can do
myArr = new int[] {1, 2, 3};

but not
myArr = {1, 2, 3};

A: Extract from Bozho answer to a similar question
Why isn't there a java.lang.Array class? If a java array is an Object, shouldn't it extend Object?

Arrays are a language feature - they have a specific syntax for
  declaring and accessing. And their class definition is hidden from
  you.
They have a representation in the refleciton API -
  java.lang.reflect.Array

A: You can declare an array in a similar way as any other Class's object.
If you aren't sure about the size of array at the time of declaration,then you can go like this---
class ArrayExample
{
int arr[];
public static void main()
{
//take length as input from the user
arr=new int[anylength];
//now do whatever you want to do with this array object
}
}


text:
Q: t-SQL greater/less than more than one value I'm facing a strange problem:
I have a simple table structured like below:
tbl1

Username | DateOfSell
  Jack     2021/04/04
  Joe      2021/04/14
  Jack     2021/05/20
  Joe      2021/04/11
  Jack     2021/05/01

And Anothe one with informations of the employee, number, hire date and fire date
tbl2

Username | Phone | DateOfStart | DateOfEnd
  Jack     02541   2010/01/01   2021/05/21
   Joe     08522   2012/06/01       NULL

What I need is to create a query to select the employee only if it is still working at some date.
for example in this case:
SELECT *
FROM tbl1 JOIN tbl2 (..)
WHERE tbl1.DateOfSell < tbl2.DateOfEnd

that would be ok, but I need (for SSRS purposes) to be able to check more than one date.
IF in SSRS I have a parameter with the actual day and the previos day and also the day of the past week, how can I do?
SO: today() = 2021/05/26
previous week: 2021/05/19
SELECT *
FROM tbl1 JOIN tbl2 (..)
WHERE  '2021/05/26' < tbl2.DateOfEnd

I want no results because now this employee is not working anymore.
SELECT *
FROM tbl1 JOIN tbl2 (..)
WHERE  '2021/05/19' < tbl2.DateOfEnd

in this case I need results because at tat date, the employee was still working.
what if in the parameter report I put both (or more) values?
clearly I have an error An expression of non-boolean type specified in a context where a condition is expected, near ','
Here is a way to resolve this problem?
thank you!

A: Maybe this query could do the trick
declare @dtparam date = '2021-01-10'

select *
from tbl1 t1
  join tbl2 t2
    on t1.Username = t2.Username
where t2.dateOfStart <= @dtparam
  and (
    t2.DateOfEnd >= @dtparam or
    t2.DateOfEnd is null
  )


text:
Q: Difference between "did save" and "saved" What is the difference between the two following sentences?

1) Where did you save that file?

And

2) Where you saved that file ?

A: Let's imagine that your friend saved a file somewhere, and you wanted to know where it had been saved. You would ask:
"Where did you save that file?"
Afterwards you might say to your friend:
"I wondered where you saved that file."
If you are asking the question, you cannot say:
"Where you saved that file?"
It's incorrect.
But you can use those words as part of a sentence, as illustrated.
http://www.grammar.cl/english/do-does-did-done.htm
https://www.englisch-hilfen.de/en/grammar/frage5.htm

A: In short the difference is the function of the word "where". In the first sentence is used as adverb, and in the second is used as conjunction.
Explanation:
The correct formal structure of questions (interrogative sentence) of the past simple tense is:

auxiliary verb ➕ pronoun ➕ infinitive verb

and with Wh questions is:

Wh question (adverb) ➕ auxiliary verb ➕ pronoun ➕ infinitive verb

Therefore, the the correct formal interrogative sentence is:

Where did you save that file?

On the other hand, you can use in a statement (declarative sentence) that says:

I am not sure where you saved that file.

In this case, the word "where" is not used as wh question (=adverb) but as conjunction.
So in the end of the day, both are correct depending on the context.
Obviously, it is not possible to ask:

Where you saved that file? ❎


text:
Q: How to define a exactly match using PHP preg_replace() I am trying to remove some parameters from a URL using PHP preg_replace(). For example, i need to remove a[]=1  from the bellow URL.
$my_url = 'www.myhost.com/filter.php?a[]=1&a[]=12&a[]=13&a[]=14'

So i am using:
$without_filter = preg_replace("/(&)?a\[\]=1/", '', $my_url);

I want to remove only a[]=1, but it is removing the portion that contains a[]=1 from the others parameters, so am i getting:
www.myhost.com/filter.php?234

Someone can help me to solve this?

A: What about: /a\[\]=1(&|\b)/
That way it will capture a[]=1 only if it is followed by a & or end of string.

A: Following the man page of preg_replace you may do something like this:
$without_filter = preg_replace("/\&(a\[\]=1)(\&|$)/", '\2', $my_url);

Or... you can always use preg_replace_callback

A: Use the $limit parameter of preg_replace and set it to 1, this should replace it only once. Assuming that your parameters are always sorted this way:
$without_filter = preg_replace("/(&)?a\[\]=1/", '', $my_url, 1);


text:
Q: Why can't I create an Application Password? Because I'm going to get a "Not Found" problem when I try to create an application password, I'm completely befuddled.
The following is the outcome of my attempts to generate a password for an application.


text:
Q: Limit Points and Sequences T or F questions:
1). If $p$ is a limit point of $M$, then $p$ is in $M$.
I know this is false because $M$ can be the open interval $M$ = $(a,b)$ and $p$ not be in it, and it be a limit point.
2). The range of the sequence can have exactly two points in it.
I'm pretty sure this is true. I'm not sure how to explain this. Would the sequence $(-1)^n$ work?
3). A sequence cannot converge to a point that is not in the range of the sequence.
I'm guessing this is false? Could someone help me find a few examples of a sequence where this statement is false?
4). If a set is not open, it must be closed.
I know this false because they're compliments of each other, but that doesn't mean it has to be one or the other. Right? Can someone give me a few examples of a set that is not open or closed please?

A: Edited based on comments

*

*done, you're correct

*done, your sequence works

*Consider the sequence $\left\{\frac{1}{n}\right\}_{n\in\mathbb{Z}_+}$. The limit 0 is not in the range

*Consider the interval $[1,2)\subset \mathbb{R}$ with the standard topology


text:
Q: SVG dropshadow getting clipped I have an SVG tick icon with a dropshadow that is being clipped. The usual filter offset method I've seen here on SO isn't helping. Any suggestions?
<svg version="1.2" baseProfile="tiny" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
     x="0px" y="0px" width="73.516px" height="55.507px" viewBox="0 0 73.516 55.507" xml:space="preserve">

  <filter id="dropShadow" x="-20%" y="-20%" width="200%" height="200%">
    <feGaussianBlur in="SourceAlpha" stdDeviation="2" />
    <feOffset dx="0" dy="0" />
    <feMerge>
        <feMergeNode />
        <feMergeNode in="SourceGraphic" />
    </feMerge>
  </filter>

  <polygon fill="#F2F2F2" points="61.769,0 29.784,31.987 11.765,13.96 0,25.69 18.034,43.735 18.011,43.761 29.748,55.507
    73.516,11.75 " filter="url(#dropShadow)"/>

</svg>

I generated this with Adobe Illustrator and then added the drop shadow via code.
Thanks!

A: Expanding the filter region won't help paint outside the SVG viewbox. Right now, your check mark paints right to the edge of the viewbox, so the drop shadow gets cut off by the viewbox, not the filter region. Increase the size of your viewbox and the world will be good.

A: Setting the CSS for the SVG to overflow:visible worked for me.


text:
Q: BitLocker, USB-drive and GPO I got myself into a difficult situation: enrypted USB-drive D: using an Windows PowerShell script file *.ps1.
Initialize-Tpm

#Enable Bitlocker
Enable-BitLocker -MountPoint "D:" -RecoveryPasswordProtector -SkipHardwareTest

#Key upload to AD
$keyID = Get-BitLockerVolume -MountPoint d: | select -ExpandProperty keyprotector |
            where {$_.KeyProtectorType -eq 'RecoveryPassword'}
Backup-BitLockerKeyProtector -MountPoint d: -KeyProtectorId $keyID.KeyProtectorId
Enable-BitLockerAutoUnlock -MountPoint "D:"

But problem is that GPO for removable drives wasn't configured, so there is no recovery key in AD and the recovery key is now needed to unlock USB-drive.
Is there any other way?


text:
Q: Routing problem finding shortest route to line inspiration on how to solve this problem.
(Ascii art, I don't have points to insert picture)
I need to find Z
Z = Shortest route from X Using Road (no point exists here)
O = The points that makes the line
X = Start point
Y = Closest point on line (Can't be used)
The problem right now is:
The nearest point (Y) from X will give a long route.
Route from X to Points (O) on line also returns a long route.
Any idea on how I can find Z ??
    O(Point)
    | ||
Line| ||       O2----------O2 (closer line but no road to this line so this can't be used)
    | ||
    | ||
    |Y||         X (Start point)
    | ||         ||
    | ||    ||   ||Road
    | ||    ||   ||
    | ||    ||   ||
    |Z||----||----Road
    | ||    ||
    | ||    ||------------- Road
    | ||
    | ||Road
    | ||
    | ||
    O (Point)

Is there anyway I can take the line and add more points to it on every 5 meters? So the Line would look like O-O-O-O-O-O instead of O---------O
Setup:
I have a postgres 9.3 with postgis 2
The database has all X (points)
All Lines (linestring)
And all roads (Export from openstreet)
(can't get pgrouting to work right now)
And a local osrm server running.

A: To add more points on the line use ST_Segmentize.
The easiest solution using pgRouting would be calculating shortest part from X to middle of O and then all alternate paths where the distance is within shortest path length + half of the length of line o (which can be done by disabling the last edge used in the route).


text:
Q: Java - For loop seems to execute past it's termination condition I have debugged this code and it appears to run a for loop even though the termination condition is met.
This program takes two types of input:
Line 1 - How many data points there are following (N)
Lines 2 to N - The data points
The program should then print the smallest difference between all of the data points.
So, for instance, a sample input would be (on separate lines): 3 5 8 9
There are 3 data points (5 8 9), and the smallest difference is between 8 and 9, so the program should return 1.
I am trying to build the program in a way in which the data points are populated into an array at the same time as the comparisons are made. Obviously I could separate those concerns, but I am experimenting. Here it is:
package com.m3c.vks.test;
import java.util.*;
import java.io.*;
import java.math.*;

class Solution {

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt(); //How many data points there will be
        int strengthArray[] = new int[N]; //Initialise the array to be of length = N, the first input line
        int tempStrengthDifference=99999; //junk difference set arbitrarily high - bad practice I know
        int lowestStrengthDifference=99999;
        for (int i = 0; i < N; i++) //Go through all elements of array
        {
            strengthArray[i] = in.nextInt(); //read a value for the ith element
            System.out.println("i: " + i); //test
            if (i > 0) //do not execute the next for loop if i = 0 as cannot evaluate sA[-1]
            {
                for (int j = i - 1; j < 1; j--) // **this is line 20** from wherever the array has populated up to, work backwards to compare the numbers which have been fed in thus far
                {
                    System.out.println("j: " + j); //test
                    tempStrengthDifference = Math.abs(strengthArray[i] - strengthArray[j]); //finding the difference between two values
                    if (tempStrengthDifference < lowestStrengthDifference) //store the lowest found thus far in lowestSD
                    {
                        lowestStrengthDifference = tempStrengthDifference;
                    }
                }
            }
        }
        System.out.println(lowestStrengthDifference);
    }
}

Everything is fine up until when i = 1 on line 20. At this point, j is set to i - 1 = 0 and the difference is found. However, when the for loop comes back around again, the termination condition of j < 1 is not met, and instead the loop continues to set j = -1, at which point it throws an out of bounds error as it clearly cannot evaluate strengthArray[-1]
Any ideas? Thanks

A: Have a look at your loop: for (int j = i - 1; j < 1; j--)
You start with j = 0 when i == 1  and thus j < 1 is ok.
The next iteration has j = -1 (0-1) and hence you get the problem.
Do you mean to use j >= 0 as your loop condition instead? Note that the second parameter is not a termination condition but a continuation condition, i.e. as long as that condition is met the loop will execute.

A: The reason behind your failure is the inner loop variable change.
When i=1, j=0 and after executing the loop once, J is decremented, and thus j becomes - 1. The condition j<1 is satisfied since you have written j--, change it to j++ and you should be fine.


text:
Q: Removing ./ with browserify I'm on a windows machine and I'm using browserify and gulp.
I want to remove the ./ in my require statements, is this possible?
Example:
Instead of require('./config.js'); I want it to be require('config.js');
My gulp file currently looks like this:
gulp.src('client/app.js')
  .pipe(browserify({
      paths: ['./node_modules', './client']
  }))
  .pipe(gulp.dest('website/public/js'))
  .on('error', function (error) {
    console.error('' + error);
});

If I try to compile the code:
var clientConfig = require('config.js');
then the result is literally "var clientConfig = require('config.js');" which isn't correct since it's supposed to include the contents.
If I use var clientConfig = require('./config.js'); then it works. Is there anyway to remove the ./ or is it required?

A: You can accomplish this using the pathmodify browserify plugin.


text:
Q: Best Practice: Should cascading updates be handled by the frontend or the REST API? I am designing a timesheet app for logging user tasks using React for frontend and Django REST Framework for backend. The database is PostgreSQL and I have a table for recording the tasks with 4 columns: date, start_time, duration, description.
I need a way to support the updating of a task after the user had created several. The problem is that each task is dependent on all the previous tasks, since its start_time will change if the duration of a task before it changes. So for example, suppose that task 1 has a start_time of 13:00 and a duration of 1 hour, task 2 has a start_time of 14:00 and a duration of 1 hour, and so on. If the user decided to update the duration of task 1 from 1 hour to 2 hours, that means the  start_time of task 2 and all subsequent tasks  must be increased by 1 hour.
I'm wondering what is the best way to implement such cascading updates. First option is to make the API backend responsible for it, so whenever the React frontend sends out a PUT request for a task, the DRF backend will not only update that task but also all subsequent tasks as well. Second option is to offload everything to the React frontend, making it responsible for sending out multiple PUT requests, for the updated task as well as all subsequent tasks.
I would think the first option of letting the backend handles everything is a better design, since this problem is technically a form of database constraint. But not too sure if it is appropriate for a REST API to handle. What would be the best practice in this case?

A:
I would think the first option of letting the backend handles everything is a better design

Yes.
There are tradeoffs, of course.
The heuristic to use is to think about how we would do this on the web:  is it OK to have the client submit one form, and in response the server modifies multiple web pages?  Of course.
The semantics of the request message are specific to one resource (specifically, the resource identified by the target-uri), but it is perfectly normal that the implementation might modify many resources during the handling of that request.
What you do need to be aware of is caching; a general purpose client is not going to know that many resources are going to change, and may therefore end up using a stale copy of some other resource.  In the language of the browser: the page you changed refreshes "automatically", but another web page may show the old data until you force the cache to invalidate its local copy of the old value.
It's not really all that different from what happens when somebody else edits a page on the server; you continue looking at your old copy until it is invalidated by the cache.  Or the case where you fetch two similar pages, but a change happens between retrieving a copy of the first and retrieving a copy of the second.

A: One additional thing you need to consider is whether violations of constraints should be prevented by the web service or can be left to be handled by the client.
In your example, a task sequence plan where a dependent task is started before the prerequisite task ends might be invalid but admissible as an intermediate state while editing the whole plan, so it might make sense to let the client sort it out.
However, consider a customer buying something from a web shop using some credit he has at that shop. Should the client be allowed to post an order and then deduct the amount from his account in a second step?
That would certainly attract quite a number of new customers, not the kind you wish to have, though :-)
So in general, it is desirable that each single modifying REST action leaves the domain in a consistent state. If overlapping tasks are not allowed, don't rely on the client to ensure consistency.


text:
Q: PyRo and python I use PyRo in my python programm. And I have a problem. class B: In callFromProxy print 0, but in callfun print right value = 10. Why? How to fix?
class A(Pyro.core.ObjBase):
 # set link to item class B
 def set(self, real_B):
  self.item_B = real_B

 # call function callfun in item_B
 def callfun(self):
  self.item_B.callfun(10)

class B(Pyro.core.ObjBase):
 # init class B
 def __init__(self):
  self.elements = {"name":0}

 # set proxy to item class A
 def set(self, proxyA):
  self.proxyA = proxyA

 # print
 def printvalue(self):
  print self.elements["name"]

 # call from proxy
 def callFromProxy(self):
  self.proxyA.callfun()
  self.printvalue() # this is not print 10, print 0

 # call function
 def callfun(self, value):
  self.elements["name"] = value
  self.printvalue() # but this is print 10

itemA = A()

# proxyA connect from PyRo to itemA

itemB = B()
itemB.set(itemA)

itemA.set(itemB)

itemB.callFromProxy() # this is not print 10

A: I believe (and correct me if I'm wrong) PyRo uses asynchronous calls, at least by default.
So when you call callFromProxy, printvalue might get executed before callfun on itemB, because it takes time to call A.callfun and B.callfun. If/when this happens, elements["name"] will still be 0 when printvalue is called for the first time.


text:
Q: html_nodes returning two results for a link I'm trying to use R to fetch all the links to data files on the Eurostat website. While my code currently "works", I seem to get a duplicate result for every link.
Note, the use of download.file is to get around my company's firewall, per this answer
library(dplyr)
library(rvest)

myurl <- "http://ec.europa.eu/eurostat/estat-navtree-portlet-prod/BulkDownloadListing?dir=data&sort=1&sort=2&start=all"

download.file(myurl, destfile = "eurofull.html")

content <- read_html("eurofull.html")

links <- content %>%
  html_nodes("a") %>% #Note that I dont know the significance of "a", this was trial and error
  html_attr("href") %>%
  data.frame()

# filter to only get the ".tsv.gz" links
files <- filter(links, grepl("tsv.gz", .))

Looking at the top of the dataframe
files$.[1:6]

[1] /eurostat/estat-navtree-portlet-prod/BulkDownloadListing?
sort=1&file=data%2Faact_ali01.tsv.gz
[2] /eurostat/estat-navtree-portlet-prod/BulkDownloadListing?
sort=1&downfile=data%2Faact_ali01.tsv.gz
[3] /eurostat/estat-navtree-portlet-prod/BulkDownloadListing?
sort=1&file=data%2Faact_ali02.tsv.gz
[4] /eurostat/estat-navtree-portlet-prod/BulkDownloadListing?
sort=1&downfile=data%2Faact_ali02.tsv.gz
[5] /eurostat/estat-navtree-portlet-prod/BulkDownloadListing?
sort=1&file=data%2Faact_eaa01.tsv.gz
[6] /eurostat/estat-navtree-portlet-prod/BulkDownloadListing?
sort=1&downfile=data%2Faact_eaa01.tsv.gz

The only difference between 1 and 2 is that 1 says "...file=data..." while 2 says "...downfile=data...". This pattern continues for all pairs down the dataframe.
If I download 1 and 2 and read the files into R, an identical check confirms they are the same.
Why are two links to the same data being returned? Is there a way (other than filtering for "downfile") to only return one of the links?

A: As noted, you can just do some better node targeting. This uses XPath vs CSS selectors and picks the links with downfile in the href:
html_nodes(content, xpath = ".//a[contains(@href, 'downfile')]") %>%
  html_attr("href") %>%
  sprintf("http://ec.europa.eu/%s", .) %>%
  head()
## [1] "http://ec.europa.eu//eurostat/estat-navtree-portlet-prod/BulkDownloadListing?sort=1&downfile=data%2Faact_ali01.tsv.gz"
## [2] "http://ec.europa.eu//eurostat/estat-navtree-portlet-prod/BulkDownloadListing?sort=1&downfile=data%2Faact_ali02.tsv.gz"
## [3] "http://ec.europa.eu//eurostat/estat-navtree-portlet-prod/BulkDownloadListing?sort=1&downfile=data%2Faact_eaa01.tsv.gz"
## [4] "http://ec.europa.eu//eurostat/estat-navtree-portlet-prod/BulkDownloadListing?sort=1&downfile=data%2Faact_eaa02.tsv.gz"
## [5] "http://ec.europa.eu//eurostat/estat-navtree-portlet-prod/BulkDownloadListing?sort=1&downfile=data%2Faact_eaa03.tsv.gz"
## [6] "http://ec.europa.eu//eurostat/estat-navtree-portlet-prod/BulkDownloadListing?sort=1&downfile=data%2Faact_eaa04.tsv.gz"


text:
Q: Implementing methods in ByteBuddy to change runtime-discoverable fields I am using Byte Buddy to create classes of bean-like interfaces at runtime, reducing tons of boilerplate code. It's trivial to create fields from getters and setters, but I want to leverage Byte Buddy more. For starters, I don't want to have to write code like this all over the place:
    if (obj.getMax() < obj.getMin()) {
        int temp = obj.getMax();
        obj.setMax(obj.getMin());
        obj.setMin(temp);
    }

    obj.setMax(obj.getMax() + 1);
    int currentMax = getMax();

when I can just do:
    obj.enforceMinMaxOrder();
    int currentMax = obj.incrementAndGetMax();

Here's an abbreviated example. How can I use Byte Buddy to make the above two work? Presumably using an interceptor class, but I have not come across any examples that modify fields. Important things:

*

*the fields are not known at compile time, they will be extracted from the method names (i.e. "enforceMinMaxOrder" method name uses "min" and "max" as the field names)

*I'd like to avoid runtime reflection used after Byte Buddy generates the classes, but holding references to fields or methods and invoking those is fine.
DynamicType.Builder<? extends Object> builder = new ByteBuddy().subclass(Object.class);
builder = builder.implement(MyInterface.class);
builder = builder.method(
    (isGetter().or(isSetter())))
    .intercept(FieldAccessor.ofBeanProperty());
for (Method m : MyInterface.class.getMethods()) {
    String methodName = m.getName();
    Class<?> t = m.getReturnType();
    if (t != void.class && methodName.startsWith("get")) {
        String fieldName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4);
        builder = builder.defineField(fieldName, t, Visibility.PUBLIC);
        builder = builder.method(named(fieldName)).intercept(FieldAccessor.ofField(fieldName));
    }
}

MyInterface obj = (MyInterface) builder.make().load(BeanUtil.class.getClassLoader()).getLoaded().getConstructor().newInstance();

obj.setMin(10);
obj.setMax(5);

obj.incrementAndGetMin();
obj.ensureMinMaxOrder();
// now, the values should be min=5, max=11

A: I think your best call would be using Advice which let's you write code templates that are later inlined into a generated class:
class MinMaxAdvice {
  @Advice.OnMethodExit
  static void minMax(@Min int min, @Max int max) { ... }
}

The method implements your code and can override any field values. Since your resolution is method-name sensitive, you would need to add your own bindings for custom annotations @Min and @Max, have a look at the Advice.withCustomBinding() API to learn how this is done. You can reuse the field bindings that exist already, but you have to locate those fields in the manner you want to achieve this.


text:
Q: How to Install phpunit 3.5 on mac with MAMP I'm trying to install PHPUnit 3.5 on Mac OS X with MAMP. I did install PHPUnit 3.5 via PEAR of MAMP. This is all correctly and phpunit is located /Applications/MAMP/bin/php5.3/lib/php/PEAR/PHPUnit. The executable is located in /Applications/MAMP/bin/php5.3/bin/.
But when I want to execute phpunit it doesn't do anything, even when I do execute it in the bin folder of MAMP php.
Can somebody help me with this?
Update
which phpunit: /Applications/MAMP/bin/php5.3/bin//phpunit
which pear: /Applications/MAMP/bin/php5.3/bin//pear
pear list
Installed packages, channel pear.php.net:
Package          Version State
Archive_Tar      1.3.7   stable
Console_Getopt   1.2.3   stable
PEAR             1.9.1   stable
Structures_Graph 1.0.3   stable
XML_Util         1.2.1   stable
Content of phpunit
#!/Applications/MAMP/bin/php5.3/bin/php
<?php

require_once 'PHP/CodeCoverage/Filter.php';
PHP_CodeCoverage_Filter::getInstance()->addFileToBlacklist(__FILE__, 'PHPUNIT');

if (extension_loaded('xdebug')) {
    xdebug_disable();
}

if (strpos('/Applications/MAMP/bin/php5.3/bin/php', '@php_bin') === 0) {
    set_include_path(dirname(__FILE__) . PATH_SEPARATOR . get_include_path());
}

require_once 'PHPUnit/Autoload.php';

define('PHPUnit_MAIN_METHOD', 'PHPUnit_TextUI_Command::main');

PHPUnit_TextUI_Command::main();

A: What is the output of which phpunit and which pear and pear list?
Also did you install phpunit with the --alldeps option?

A: I succeeded in installing PHPUnit with XAMPP on Mac, but it took me some time.
One of the trick was to edit the phpunit script to configure it to use XAMPP (or MAMP) PHP executable, and not the default one on Mac.


text:
Q: Disable E_STRICT errors in php.ini file still throws the errors I'm trying to disable E_STRICT errors in my php.ini file but it still throws the error. I'm using PHP 5.4.10 with a MAMP (not PRO version).
With phpinfo I've located the php.ini file in /Applications/MAMP/bin/php/php5.4.10/conf/php.ini
I've changed:
error_reporting = E_ALL

to
error_reporting = E_ALL & ~E_STRICT

Then i've restarted Apache but it still throw the error, where I'm wrong?

A: Use error_reporting = E_ALL ^ E_STRICT.
If you didn't have access to php.ini, you could put this in your .htaccess file:
php_value error_reporting 30711

This is the E_ALL value (32767) and the removing the E_STRICT (2048) and E_NOTICE (8) values.
If you don't have access to the .htaccess file or it's not enabled, you can put this at the top of the PHP section of any script
error_reporting(E_ALL ^ E_STRICT)


text:
Q: Adding  with javascript to admin bar. Works in Chrome/Safari, not Firefox I'm trying to add a new menu item to the WordPress admin bar. The sub menu item contains a select drop down to switch themes. In Firefox with href => false it generated  and when I clicked the select it reloaded the page. I changed it to . That fixed the page reload when clicking on the select... but the javascript isn't working.
The code itself works just fine in Chrome and Safari on Mac. I haven't tested IE or any browsers on Windows yet. In Firefox on Mac it does nothing.
Here's the code generated by the plugin:

    Switch Themes

                            <select name="themeswitcher" onchange="location.href=this.options[this.selectedIndex].value;" style="color: #000; text-shadow: none;">
                                    <option value="http://themes.fusionized.com?wptheme=Abstract" style="color: #000; text-shadow: none;">Abstract</option>
                                    <option value="http://themes.fusionized.com?wptheme=Ambience" style="color: #000; text-shadow: none;">Ambience</option>
                            </select>

Nothing fancy in the code to generate the admin bar items...
$wp_admin_bar->add_menu( array( 'id' => 'switch_themes', 'title' => __( 'Switch Themes', 'textdomain' ), 'href' => '#' ) );
$wp_admin_bar->add_menu( array( 'parent' => 'switch_themes', 'title' => $theme_switcher->theme_switcher_markup('dropdown'), 'href' => '#' ) );

A: Obviously you cannot put a select tag inside a A anchor. What happens is related to event bubbling: Firefox takes the A anchor click into account, not the select control.
Change your html to:

                            <select name="themeswitcher" onchange="location.href=this.options[this.selectedIndex].value;" style="color: #000; text-shadow: none;">
                                    <option value="http://themes.fusionized.com?wptheme=Abstract" style="color: #000; text-shadow: none;">Abstract</option>
                                    <option value="http://themes.fusionized.com?wptheme=Ambience" style="color: #000; text-shadow: none;">Ambience</option>
                            </select>

and it should work cross-platform.

A: If you want to add content to the menu item outside the  tag, you can add this in the ['meta']['html'] argument. So your code would look like this:
$wp_admin_bar->add_menu( array(
    'parent' => 'switch_themes',
    'meta' => array(
        'html' => $theme_switcher->theme_switcher_markup( 'dropdown' ),
    ),
    'href' => '#',
    'title' => ' ', // An empty title will not be accepted
    'id' => 'wpse17434_child', // If the title is empty, you need to specify the ID yourself
) );

This will generate an ugly empty  block above your dropdown, but you can hide this with the correct style.
Have you considered not using a dropdown but just a submenu to list the different themes? This would be more in line with the current menu bar style.

A: Since I couldn't edit the  tags that were being added but I could edit what was inside them, I added a closing  tag and re-opened a new  tag at the end of what I was inserting. Then just used CSS to hide the blank line they were adding around my content. Also set the href on both tags to #....
Fixed the Firefox issue which seemed to be the only thing picky enough... even the W3 validator said the code was ok.
Here's the resulting code:

Switch Themes

            <select name="themeswitcher" onchange="location.href=this.options[this.selectedIndex].value;" style="color: #000; text-shadow: none; margin: 10px;">
                <option>Blah</option>
            </select>


text:
Q: Dynamically change the textview.keyboardType using segment control -(void)segmentAction
{
  if(segmentedControl.selectedSegmentIndex == 0)
  {
      textview.keyboardType = UIKeyboardTypeNumberPad;
  }
  else
  {
      textview.keyboardType = UIKeyboardTypeDefault;
  }
}

A: This is an objective C/iPhone question.
Is the function 'segmentAction' hooked up to the segmentedControl properly in Interface builder ? Make sure this gets called, for instance, on 'valueChanged' for segmented control, and it should change your keyboard.
Either segmentAction needs to be an IBAction or it needs to be called from one.
Make sure segmentedControl is properly hooked up, as an IBOutlet.
Also, where is 'textview' coming from. Your textView delegate functions return a variable called textview, if this is a member variable called textView things are going to get confusing quickly for you.


text:
Q: How set custom environment variable for a standalone Blazor WASM app? Using these docs we can easily set custom environment per app, but not custom environment variables. Is there anything similar but for variables?
Perhaps something like Blazor-Environment-Variable with a name and a value using some separator. And then these variables could be used in a usual way (like in a desktop .NET app), through IConfiguration and IOptions.


text:
Q: Atiyah-Macdonald Sum of Submodules Vs Intersection of Submodules On page 19 in Atiyah-Macdonald, if $M$ is an $A$-modules and $(M_i)_{i \in I}$ is a collection of submodules of $M$, then their sum $\sum M_i$ is defined to be the set of all finite sums $\sigma x_i$ where $x_i \in M_i$ for all values of $i$ and all but finitely many values of $i$ are zero.  It goes on to say that $\sum M_i$ is the smallest submodule of $M$ which contains all of the $M_i$.
Immediately after, it states that $\bigcap M_i$ is again a submodule of $M$.
My question is that I am tempted to think of the smallest submodule of $M$ containing all of the $M_i$ as precisely being the intersection $\bigcap M_i$, since it clearly contains all of the $M_i$ but it seems like this is not the case.
Is it not true in general that $\sum M_i = \bigcap M_i$?  I.e., is it not true in general that the intersection of all submodules $M_i$ is the smallest submodule of $M$ which contain all of the $M_i$?

A: The intersection of submodules is contained in each of the submodules, not the other way around. If $M_i\neq M_j$ then $M_i$ and $M_j$ are both not contained in $M_i\cap M_j$. They both contain $M_i\cap M_j$.
For a very tangible example, you can make explicit what finite sums and intersections of submodules of $\Bbb{Z}$ look like. It is easy and very illustrative.

A: A sum of modules is the smallest module containing the union. So it's like the opposite of the intersection. The intersection is contained inside of each $M_i$ and each $M_i$ is in turn contained in the union. The inclusions go this way:
$$ \bigcap_{i \in I} M_i \subseteq M_i \subseteq \bigcup_{i \in I} M_i \subseteq \sum_{i \in I} M_i. $$
For instance, consider two lines inside a vector space: $V_i = \{t v_i : t \in \mathbb{F}\}$. The intersection of these two lines is just $\{0\}$ and the union is not a subspace. But the sum is $V_1 + V_2 = \{sv_1 + tv_2 : (s, t) \in \mathbb{F}^2\}$ which is the plane containing each of the two lines.


text:
Q: SQL Server: set all column rows to 0 or 1 in a temporary table I have two tables table_1 and table_2.
Both tables contain 250 columns each, with an ID code which allows the two tables to be joined, many to many. Each column row has a value for ranging 0 - 500, with the exception of the ID codes.
I need to do some further analysis, and would like to be able to produce a temporary table or query output where, for each row for each column, the value is set to 0 or 1, where 1 is where the sum of the column by id code is >= 1.
I can do this using case when, but with 500 columns I wonder if there is a more clever way of doing this. If it helps, all the columns in each of the tables end in the word "_bin".

A: You haven't specified SQL server version, starting from SQL 2012 you can also use IIF or CHOOSE logical functions for this instead of 'case when' but it still require to do it for all columns.
more details here :
https://www.mssqltips.com/sqlservertip/2570/new-logical-functions-in-sql-server-2012-iif-and-choose/


text:
Q: Mongo adding a field to a specific object in an array of objects using updateOne during a bulkUpdateOps Use case
Adding a field to a specific object in an array of objects using updateOne during a bulkUpdateOps
Blockers

*

*I have been unable to find a way to identify and update a specific object in the subdocument array of a specific record.

*I only have access to this DB through MongoDB Compass, and I plan to use the provided mongosh tool.

Data example
Our purchaseorders model looks like this:
{
   _id: uuid,
   ...rest,
   documents:[
      {
         _id:uuid,
         forignKey2:string (optional),
         keyIWantToAdd:string (optional),
         ...rest
      }
   ]
}

So if I have
{
   _id:*1,
   documents:[
      {
         _id:*2,
         forignKey2:'no-test',
         ...rest
      },
      {
         _id:*3,
         forignKey2:'test',
         ...rest
      },
   ]
}

I want to add a key and value like this (really I'm willing to do anything to set these values, this is just the closest I have been able to get):
var bulkUpdateOps = db.purchaseorders.initializeOrderedBulkOp();
bulkUpdateOps.find('*1').updateOne({
   $set:{
      documents.[index of document object with forignKey2:'test' or _id:*3 whichever is easier].keyIWantToAdd:'valueIWantToAdd'
   }
})
bulkUpdateOps.execute();

Any help or suggestions would be greatly appreciated.

A: @rickhg12hs posted exactly what I was looking for. For anyone else using mongodb.com/docs/manual/reference/method/Bulk.find.arrayFilters the bulk find is being ran on an array of objects like this: { grades:[ { grade: 85, mean: number } ] }


text:
Q: live changes with any modification on the DOM I am using jQuery to apply some UI effects like adding a class to a number of elements, in the JS file i use :
$('.dataGrid').each(function(){
$(this).find('tr:odd').css('background-color', '#F7F8FA');
});

but when i use ajax to load an element with the class .dataGrid the rules up there doesn't apply, my solution was to make a function joins all cases like this one and call it every time i make an ajax request ! .. this off course is not a pro one .. i found .live() , i used and it worked fine with events like :
 $('dataGrid').live('moveover', function(){ ... }); .
the .live solution is very good with events ... is there any way to use the same concept with the effects like mentioned up there ? ... i mean a way to reapply the rules set before, every time a change takes place on these elements ( adding new one for example )
I wish i was clear enough, Thanks in advance :)

A: The Livequery-plugin supports triggering functions when new nodes are added to the DOM.
Something like this should work:
$('.dataGrid').livequery(function() {
    $(this).find('tr:odd').css('background-color', '#F7F8FA');
}

A: Depending on how you are loading elements i.e. which AJAX technique you are using, you can achieve this in many ways. If you are using jQuery Ajax then you can use the jQuery.when method.
Basically with this method you can have deferred execution. You can say something like "when the ajax call completes then do this function". The syntax goes like
$.when( $.ajax("test.aspx") ).then(function(ajaxArgs){
     alert(ajaxArgs[1]); /* ajaxArgs is [ "success", statusText, jqXHR ] */
});

Following link will give you more information
http://api.jquery.com/jQuery.when/

A: Since you are using ajax to append your .dataGrid elements you could register a handler for ajaxComplete() that will handle the application of your :odd class.
$(document).ajaxComplete(function() {
  $('.dataGrid').each(function(){
    $(this).find('tr:odd').css('background-color', '#F7F8FA');
  });
});