text:
Q: SQL error 1064. Statement works in mysqladmin but not in PHP script I have a PHP script installed on the admin side of our website that is supposed to allow us to run SQL queries.  However, I'm not getting the same results as I am when running it through mysqladmin on our host company's OPS page.
When I submit:
SELECT orders_id FROM `orders_status_history` WHERE `comments` LIKE '%12345%'

I get one result (my test record) in mysqladmin.  So it's successful.
However, when I submit it through the PHP program, I get:
MySQL error 1064: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use near '\'%12345%\'' at line 1

While executing:

SELECT orders_id FROM `orders_status_history` WHERE `comments` LIKE \'%12345%\'

I'm assuming the syntax is different when submitting through PHP but I can't, for the life of me, figure out what it's supposed to be.  I've tried prefacing the single quotes with a slash.  I've tried double quotes.  I've spent a couple hours surfing the web.  I've tried so many things I can't even keep them straight anymore.  I'm assuming it is something simple.  Can anyone point me in the right direction?
Here is the code from the php program.  The user pastes the SQL query in a text area and hits a SEND button.  Again, the exact same query works in mysqladmin but not when using this PHP program:
<?php
/*
  $Id: sql_interface.php,v 1.00 2004/08/13 00:28:44 draven Exp $
*/

  require('includes/application_top.php');
  $text_heading = INITIAL_TITLE;

    function sqlquery($query) {
    $result = mysql_query($query);
    global $query_result;
      if (mysql_errno()) {
        $query_result = "MySQL error ".mysql_errno().": ".mysql_error()."\n\nWhile executing:\n\n$query\n------------------------------------------------------------------------------------------\n\n";
      } else {
        $query_result = "Your query was successful!\nRows Affected: " . mysql_affected_rows();
      }
    return $result;
  }

  $action = (isset($HTTP_GET_VARS['action']) ? $HTTP_GET_VARS['action'] : '');

  if (isset($HTTP_POST_VARS['action']) && ($HTTP_POST_VARS['action'] == 'process')) {
    sqlquery($HTTP_POST_VARS['query_entry']);
    $text_heading = POST_QUERY_TITLE;
    $tryagain = TRY_AGAIN_TEXT;
  }
?>
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html <?php echo HTML_PARAMS; ?>>

<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
<title><?php echo HEADING_TITLE; ?></title>
<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">

<?php require(DIR_WS_INCLUDES . 'header.php'); ?>

    <td width="<?php echo BOX_WIDTH; ?>" valign="top"><table border="0" width="<?php echo BOX_WIDTH; ?>" cellspacing="1" cellpadding="1" class="columnLeft">

<?php require(DIR_WS_INCLUDES . 'column_left.php'); ?>

<?php echo tep_draw_form('sql_interface', 'sql_interface.php', 'post') . tep_draw_hidden_field('action', 'process'); ?>

            <?php echo HEADING_TITLE; ?>

                    <?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?>

                    <?php echo '' . $text_heading . ':'; ?>
                    <?php echo $tryagain; ?>

                    <?php echo tep_draw_textarea_field('query_entry', '', 137, 30, $query_result, '', false); ?>

                    <?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?>

                <?php echo tep_draw_separator('pixel_trans.gif', '10', '1'); ?>
                <?php echo tep_image_submit('button_send.gif', IMAGE_BUTTON_EXECUTE_SQL) . tep_draw_separator('pixel_trans.gif', '10', '1'); ?></form>

<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>

<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>

A: I'm not sure if you're supposed to be escaping your single quotes on that particular query, as I'm not sure what the exact php code you're using is.
$query = "SELECT orders_id FROM orders_status_history WHERE comments LIKE '%12345%'";

That will work just fine. You would only need to escape them if you were doing:
$query = 'SELECT orders_id FROM orders_status_history WHERE comments like \'%12345%\'';

If this doesn't solve your issue, please post the relevant php code.
Edit: Try using stripslashes() on your query, and take a look at mysql_real_escape_string() leaving slashes in MySQL

A: In case the above answer doesn't work for anyone, check that all the default values match the data type and that all values are set to database type. One of mine wasn't set to InnoDB so it didn't work, but it did not return any error!


text:
Q: Maya Mel Script - How to get bottom point of model? How to get bottom point of model via Mel script?

If I can get the Y-coordinate of the bottom point, I can get the point of the bottom, but I can't figure out how to get it.

A:
If I can get the Y-coordinate of the bottom point, I can get the point of the bottom, but I can't figure out how to get it.

I figure it out: Y-coordinate of the bottom point = Y-coordinate of the lowest vertex of the model. So do it like this: Loop through all vertices to get the lowest vertex.
Assume the target object is: "pCube1". Here is the code to get the lowest Y.
int $vtxIdx;
int $vCount[] = `polyEvaluate -vertex pCube1`; //Get vertex count
float $lowestY = 2147483647.0;
float  $crtY = 0.0;
for ($vtxIdx = 0; $vtxIdx < $vCount[0]; $vtxIdx++)//Loop through vetex
{
    float $pos[] = `xform -q -ws -t ("pCube1.vtx["+$vtxIdx+"]")`;//Get vertex position
    $crtY = $pos[1];
    if($crtY < $lowestY)
    {
        $lowestY = $crtY;//Get the lowest Y
    }
}
print ($lowestY);

So the lowest point = (pCube1.X, lowestY, pCube1.Z).

A: Looping through all vertices can be slow, especially with a dense mesh. What can be done instead is to use the object's bounding box:
float $bb[] = `getAttr pCube1.boundingBoxMin`;
print($bb[1]); // Lowest position in Y

Another benefit of this is that you aren't relying on vertices, so it doesn't have to be a polygonal mesh.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Composer : Why some of my packages got automatically removed on installing a new package My composer status while installing the new package
I tried installing stripe package on yii2 via composer. It got installed successfully but also removed some of the packages automatically. I didn't edit composer.json or lock file, I just execute the composer require command to install the package. Why the composer removed those packages and how can I recover them back? Is there any way to prevent it in future?
Thanks!

A: Say your project A requires dependency B.
Version 1.1.x of dependency B requires package C.
Now if you update to version 1.2.x of dependency B which does NOT depend on package C anymore composer will automatically detect the orphaned dependency and therefore remove package C.
If you still want package C to be available to your application after the update you need to explicitly require it - making it an explicit dependency instead of an implicit one (installed as a dependency of another package).
composer automatically updates the other dependencies of your project (respecting the existing version constraints your composer.json) if you invoke composer require.
To prevent automatic dependency updates use:
composer require --no-update <package>


text:
Q: How can I call/execute an imageJ macro with R? I've written a macro in imageJ that spits out a data frame which I then analyze in R.   I'd love to be able to have the whole procedure work in R without having to first run the macro manually in imageJ.  Currently the macro prompts the user for the input and output directories and then does it's thing.  I'm thinking there must be a function in R that will allow me to specify the macro and the input and output directories (I could then recode these variables in the macro to somehow take these arguments through the R script?)
I gather that I can use the system() command and found this tantalizing clue from somewhere else on the web:
system("./JavaApplicationStub  directory file[i] -batch zmacro")

but I am not sure how to implement this (my macro already utilizes batch processing so that part would be unnecessary).

A: Thanks to both nograpes & Kota (and more google searching) the problem is solved.
To call an imageJ macro through R is as follows from Kota:
system("/Applications/ImageJ/ImageJ.app/Contents/MacOS/JavaApplicationStub -batch
/Users/xxxx/Desktop/testmacro.txt")

The particular macro I am using requires both input and output directories.  To code this in R, I added an argument onto the system call:
system("/Applications/ImageJ/ImageJ.app/Contents/MacOS/JavaApplicationStub -batch
/Users/acgerstein/Desktop/testmacrobatch.txt
/Users/acgerstein/Desktop/130829Pos_24h/*/Users/acgerstein/Desktop/temp/")

As far as I can tell imageJ only supports one argument being passed in.  So I separated my input directory and output directories by " * ".
The code in imageJ then looks like this:
folders = getArgument;
delimiter = "*";
parts=split(folders, delimiter);
dir1 = parts[0];
dir2 = parts[1];

The nicest slightly unexpected thing is that the log files that are usually printed through the macro in imageJ now show up in the R console.
Mischief managed.

A: Here is an example to run a macro file "test.ijm" from CL (in osx). You could probably wrap this command in R (not tested). The path to the macro file should be a full path, not a relative path.
/Applications/ImageJ/ImageJ.app/Contents/MacOS/JavaApplicationStub -batchpath /tmp/test.ijm

A: Have you tried Bio7? It is a distribution of ImageJ, embedded in an Eclipse RCP application, which features lots of great R integration using Rserve.
For what it's worth, we are also working on R scripting integration in ImageJ2.


text:
Q: how to implement sqlite.net extension in xamarin forms? I am trying to implement the sqlite.Net Extension in my xamarin forms project. I added the sqlite.net extension from nuget. Now I am trying to create the connection with db, but not getting can I do that. I am trying to do it like https://bitbucket.org/twincoders/sqlite-net-extensions
I am not getting "UpdateWithChildren" or "GetWithChildren" methods in my connection object.
Here is the code that I am using to create the connection:
 public SQLiteAsyncConnection GetConnection()
    {
        var sqliteFilename = "SQLiteEx.db3";
        string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder
        string libraryPath = Path.Combine(documentsPath, "..", "Library");
        var path = Path.Combine(libraryPath, sqliteFilename);

        if (!File.Exists(path))
        {
            File.Create(path);
        }

        var conn = new SQLiteAsyncConnection(path, true);

        return conn;
    }


text:
Q: Matrix exponential of an upper triangular matrix Let $a,b,c,d$ be real and nonzero. I am trying to find $e^{At}$ where
$$A = \begin{bmatrix}
a & b & c & d & e\\
 0& a & b& c &d \\
 0& 0 &a  &b&c \\
 0& 0 & 0 &a  &b \\
 0& 0& 0 & 0 & a
\end{bmatrix}.$$
I don't think diagonalizing would be a good approach here. I think there is some way I can split this up into different matrices added together and then go from there, but I am not sure what to do. Everything I try seems to be computationally heavy, but for some reason I feel like there is a simple way to do this.
Does anyone know how?

A: You can deal with this using two tricks. Firstly, if $AB = BA$ then $e^{A+B} = e^Ae^B$. Secondly, use the definition of exponential as
$$
e^A = \sum_{i=0}^\infty \frac{A^n}{n!}.
$$
Write out your matrix as
$$
\begin{bmatrix}
a & b & c & d & e\\
 0& a & b& c &d \\
 0& 0 &a  &b&c \\
 0& 0 & 0 &a  &b \\
 0& 0& 0 & 0 & a
\end{bmatrix} = \begin{bmatrix}
a & 0 & 0 & 0 & 0\\
 0& a & 0& 0 &0 \\
 0& 0 &a  &0&0 \\
 0& 0 & 0 &a  &0 \\
 0& 0& 0 & 0 & a
\end{bmatrix} +
\begin{bmatrix}
0 & b & c & d & e\\
 0& 0 & b& c &d \\
 0& 0 &0  &b&c \\
 0& 0 & 0 &0  &b \\
 0& 0& 0 & 0 & 0
\end{bmatrix}
$$
and apply the above. It will be a bit computational heavy but you will see a nice pattern when making the powers of the part with zero diagonal. (Also note, that the condition of $AB = BA$  is crucial as the general case given by the Hamilton-Cayley Theorem is more tricky.)


text:
Q: Submitting an HTML table row to php I need help figuring out how to submit data from a table row into PHP to be processed. I would need it to be able to submit multiple rows of data. Any ideas?
I have a table here. I want to be able to check the row and submit the data to php to process the data. It is an HTML table. I just want to know how to pass the variables to php, e.g. an array or something
Ok guys something like this:
$("submit_btn").click(function () {

       $('#diary tbody>tr input:checked').each(function() {
           $.post('process.php',
                data: "an array",
                success: "data submitted");
       }

});

How would I get the table row data in an array to submit it? (Answer is below)
Ok Part 2:
Sending the table row data to php.
jQuery code:
    rows = JSON.stringify(rows); // submit this using $.post(...)
    alert(rows);
    $.post('classes/process.php', rows, function(data) {
      $('#results').html(data);
    })
        .error(function() { alert("error"); })
    });

PHP Code:
<?php

$rowsArray = json_decode($_POST['rows']);

echo $rowsArray;
?>

Error:
Notice: Undefined index: rows in C:\...\classes\process.php on line 6

A: $('#submit_btn').click(function(){
    var rows = [];
    $('#box-table-a tbody tr input[type=checkbox]:checked').each(function(i,v){
        var tds = $(v).parents('tr').children('td');
        rows.push({
            'name': tds.eq(1).find('select').val(),
            'units': tds.eq(2).text(),
            'calories': tds.eq(3).text(),
            'sugar': tds.eq(4).text()
        });
    });
    rows = JSON.stringify(rows); // submit this using $.post(...)
    $.post('classes/process.php', {'rows': rows}, function(data){
        console.log(data);
    });
});

submit rows using a $.post() and then, in the server side, you can convert back into an array using json_decode();
Sample output:
[{"name":"Water","units":"1","calories":"2","sugar":"3"},{"name":"Food","units":"4","calories":"5","sugar":"6"}]
Demo:
http://jsfiddle.net/cp6ne/84/

A: You could use the jQuery library to make an AJAX request to a PHP script that then 'processed' the data in the table.
You could also use the jQuery .each() function to perform this action on multiple rows.


text:
Q: Transpile javascript binaryExpression with + operator to bash equivalent I am trying to write a PoC typescript/javascript to bash transpiler.
(I have little to no background in writing compilers or transpilers)
I am using the typescript compiler API to lex and generate the Parse Tree.
I am able to convert simple expressions to bash as follows:
let a =1
let b=2;
let c = (a+(b*2));
console.log(c,"d",1);

transpiles to:
a=1
b=2
c=($(($a + ($(($b * 2))))))
echo  "$c" "d" 1

But I don't know how to convert the concatenation operator, As there is no concatenation operator in bash and the way you concat in bash is "$word1 $word2".
for example:
let strLitIdentifier = "abc"
let a3 = a + ((2*3)+strLitIdentifier)

Now the expected output would be:
strLitIdentifier="abc"
a3="$a$((2 * 3))$strLitIdentifier"

But while iterating and when I am within the BinaryExpression node of (a+?) I don't have a way to realize if the identifier is a number or the output from the right operand is going to be a string. And I can't keep the '+' operator as bash doesn't use '+' for concatenation.
from @Ed Morton's comments, I have been able to make slight progress by using the typeof method but:
let a = 1 + 1; #works, output: 2
let b = 1 + "a"; #works, output: 1a
let c = 1 + "1";  #Invalid, output: 2, expected: 11

Example Generated Code:
function bashtype_is_num {
    local re='^[0-9]+$'
    if ! [[ $1 =~ $re ]] ; then
        echo "NaN"
    else
        echo "NUMBER"
    fi
}

function bashtype_add_or_concat  {
    if [[ $(bashtype_is_num $1) == "NUMBER" &&  $(bashtype_is_num $2) == "NUMBER" ]]; then
        echo $(($1 + $2))
    else
        echo "$1$2"
    fi
}

a=$(bashtype_add_or_concat 1 1)
b=$(bashtype_add_or_concat 1 "a")
c=$(bashtype_add_or_concat 1 "1")


text:
Q: Looping through Numbered Columns into Numbered Temp Tables I am joining two tables - the first a long table with my universe of dates and the second a wide table with multiple indexed dates of interest. Both share a common ID variable. I am trying to keep only the observations from table_long whose dates fall within each of the wide indexed dates from table_wide, but to loop through the one at a time and save them into separate temp tables to append later. There can be up to 100's of wide indexed dates, so being able to loop through would save a lot of duplicate coding lines.
Example initial data:
Table_long

id
strt_dt
end_dt
spend

ABC
1/15
1/15
100

ABC
3/10
3/11
50

ABC
4/21
4/21
50

ABC
8/4
8/8
200

DEF
2/12
2/13
50

DEF
6/26
6/27
125

DEF
9/1
9/1
75

Table_wide

id
strt_dt_1
rnout_dt_1
strt_dt_2
rnout_dt_2

ABC
1/15
7/15
4/21
10/21

DEF
2/12
8/12
NULL
NULL

Attempted code:
declare @n int
set @n = 1

while @n <= 2
begin
     select
         l.*, w.strt_dt_@n, w.rnout_dt_@n
     into #table_ideal_post_join_@n
     from #table_long l
     left join #table_wide w
     on l.id = w.id
     where l.strt_dt >= w.strt_dt_@n and l.end_dt <= w.rnout_dt_@n
set @n = @n + 1
end;

Ideal outcome example data:
table_ideal_post_join_1

id
strt_dt
end_dt
spend
strt_dt_1
rnout_dt_1

ABC
1/15
1/15
100
1/15
7/15

ABC
3/10
3/11
50
1/15
7/15

ABC
4/21
4/21
50
1/15
7/15

DEF
2/12
2/13
50
2/12
8/12

DEF
6/26
6/27
125
2/12
8/12

table_ideal_post_join_2

id
strt_dt
end_dt
spend
strt_dt_2
rnout_dt_2

ABC
4/21
4/21
50
4/21
10/21

ABC
8/4
8/8
200
4/21
10/21

I am getting invalid column name all variables including @n in the name. Is something like this possible to do in SQL Server?


text:
Q: Transactions across microservices with Seneca I'm start to develop a web application in microservice architecture with SenecaJS framework.
It has good documentation but I don't understand if I can solve the problem of "transaction across microservices" with it or I should implement something by myself.
Have you a suggestions?


text:
Q: How to parse text file with multiple delimiters I have a text file I'm trying to parse. The data is a single string and uses four types of deliminators. There's also a record count at the end of the file that's not pertinent to the data that I can ignore.
Deliminators:
Beginning of data: ~
Field Seperator: |
End of record: #
End of data: ^
Sample text file:
~001|John|Smith|300#002|Abby|Williams|250#003|Tom|Jones|400#004|Claire|Benton|300^
Count:4

The parsed data should be stored in a list or collection of objects "Account"
public class Account
        {
            public string IdNum { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string AmtDue { get; set; }
        }

I'm still new to programming so please teach me what would be the best way to parse and store this data?
Thanks in advance.

A: If you know all delimiters, you can use something like this:
var s = "~001|John|Smith|300#002|Abby|Williams|250#003|Tom|Jones|400#004|Claire|Benton|300^Count: 4";

// select a line between "~" and "^".
var data = new string(s.SkipWhile(c => c == '~').TakeWhile(c => c != '^').ToArray());
var records = data.Split('#');
var accounts = records.Select(record => record.Split('|'))
  .Select(items => new Account
  {
    IdNum = items[0],
    FirstName = items[1],
    LastName = items[2],
    AmtDue = items[3]
  })
  .ToList();

foreach (var account in accounts)
{
  Console.WriteLine(account.IdNum);
  Console.WriteLine(account.FirstName);
  Console.WriteLine(account.LastName);
  Console.WriteLine(account.AmtDue);
  Console.WriteLine();
}

Just first of all split by row delimiters, then split by field delimiter.
P.S. Don't forget check variables on null or array length like you need.


text:
Q: Python Exceptions - Connection Aborted vs. Connection Refused What's the difference between ConnectionAbortedError and ConnectionRefusedError?
The documentation only specifies one is when a connection is aborted and the other when a connection is refused... not much help.
If I have a simple server and client in python and I'm using sockets how do I reproduce each exception?


text:
Q: App crashes after capturing image After capture camera image when i save then not return in activity and crash app but everything is ok in my Samsung mobile but giving this error in redmi phone and others mobile
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.toString()' on a null object reference
         at com.logiclump.technologies.gigmedico.Home.onActivityResult(Home.java:101)
         at android.app.Activity.dispatchActivityResult(Activity.java:6562)
         at android.app.ActivityThread.deliverResults(ActivityThread.java:3768)

This is my first activity
 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA_REQUEST_CODE && resultCode==RESULT_OK)

    {
        Uri uri = data.getData();
        Log.e("Image : ", uri.toString());
        Intent intent = new Intent(this, PictureActivity.class);
        intent.putExtra("imgUrl", uri.toString());
        startActivity(intent);
    }
}

This is second activity where i am getting intent
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
    Log.e("ashish", bundle.getString("imgUrl") + "");
    path = Uri.parse(bundle.getString("imgUrl"));
}

ImageView selfiiii = (ImageView) findViewById(R.id.mySelfie);
selfiiii.setImageURI(path);

A: Try this
Camera Intent:
private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File

        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                    "com.example.android.fileprovider",
                    photoFile);

            mTempCameraPhotoFile = photoFile;
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, PHOTO_REQUEST);
        }
    }
}

Save Image File In Storage:
private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    return image;
}

In onActivityResult:
if (requestCode == PHOTO_REQUEST && resultCode == RESULT_OK) {
        try {

            String filePath = mTempCameraPhotoFile.getPath();

            Uri uri = Uri.fromFile(mTempCameraPhotoFile);

            Bitmap bitmap = null;

            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);

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


text:
Q: Getting information about class inside its method I'm having one function which is inherited in other classes. What I would like in that function is to get current class name in which is running. For example:
public class A {
    public void foo() {
        System.out.println(this.class.getName()); // I know this syntax is incorrect
    }
}

public class B extends A {
}

I would like when I call instance of class A,  for function foo() to print "A", and when running foo from instance of class B to write "B", without having to explicitly overload foo() function.
EDIT:
As Arvind said it solution I was looking for was:
this.getClass().getName()

A: System.out.println(this.getClass().getName());


text:
Q: Compare a List to a SQL column value to decide if a list item appears in the column
Possible Duplicate:
check whether a List<string> contains an element in another List<string> using LINQ

A SQL database column stores a bunch of strings like so: /String1/String2/String3/... with the first and last characters being '/'. I need to compare this column to a List<string> to decide whether a parameter string in the list is contained in the column value.
Column value: "/One/Two/Three/Four/"
Parameter: List<string> parameters = new List<string>{"Two", "Three"};
Compare the parameter list to the column value. Since at least one item appears in the column value, return true / select the row.
I'm using LINQ-to-SQL.

A: Use  String.Split Method, Enumerable.Intersect Method and Enumerable.Any Method:
//I guess you can get the string representation of the column value
string value = "/One/Two/Three/Four/";
List<string> parameters = new List<string> { "Two", "Three" };

bool result = value.Split('/')
                   .Intersect(parameters)
                   .Any();


text:
Q: UITesting Xcode - select specific element? I am trying to select a specific element (an image) in a scrollview.
Now if I use UITest recording this is the code it creates for me:
[[phocusByHasselbladWindow.scrollBars childrenMatchingType:XCUIElementTypeValueIndicator].element click];
    [[[[phocusByHasselbladWindow childrenMatchingType:XCUIElementTypeSplitGroup].element childrenMatchingType:XCUIElementTypeSplitGroup].element childrenMatchingType:XCUIElementTypeScrollView].element click];

Now because the list may change I want to select the specific image by name, but I can't figure out how.
This is one of my tries (just below), however it just comes up and says it can't find any element by that name.
[[phocusByHasselbladWindow.scrollbars childrenMatchingType:XCUIElementTypeValueIndicator].element click];
    [[[[[phocusByHasselbladWindow childrenMatchingType:XCUIElementTypeSplitGroup].element childrenMatchingType:XCUIElementTypeSplitGroup].element childrenMatchingType:XCUIElementTypeScrollView] elementMatchingType:XCUIElementTypeTextField identifier:@"TestImage"] click];

Can someone see what I am doing wrong?

A: You can use accessibilityIdentifier or accessibiltyLabel and get after you can have access to it.
label.accessibiltyLabel = "label"
XCTAssertTrue(app.staticTexts["label"].exists) // true


text:
Q: Restrict Access of A Product based on few criterias Goal:
Show all products to all users who have access rights to the purchase module.
However besides the above rule show only products who have value 'secfab' in the reference field to the users who created the same product.
Problem:
I tried using access records but my logic to build it is weak and I need help.
Case 1:
[('default_code','!=','secfab'),('created_id','=',user.id)]
If I code this then I only get one record and other records are not shown.
Case 2:
['|',('default_code','!=','secfab'),('created_id','=',user.id)]
If I code this then I only all the records and I am not able to achieve privacy that I wanted.
Any Help will be highly appreciated.

A: Your second case seems to be correct, except the clause for filtering on the creator looks misspelled. This typo could cause the rule to match all records, because the condition on the non-existing field created_id cannot be verified. Shouldn't it be:
['|', ('default_code', '!=', 'secfab'), ('create_uid', '=', user.id)]

which translates to "show all products that don't have secfab as code, plus all products, that the user created, regardless of their code", and seems to do what you want?
create_uid is one of the 4 fields automatically added by the system to all models that have _log_access set to True, which is the default. This is explained in the OpenERP technical memento and in the special fields documentation.


text:
Q: Running macro from ssis I developed an SSIS package that ran Excel macros (VS2008, SQL Server 2008 and Windows Server 2008 if I remember correctly - servers were decommissioned). The package was migrated to Azure using SQL Server 2016 and VS2015.
We are now running it for the first time in over a year and it's failing. Original code for running the macro from SSIS was taken from here  Run an Excel Macro from SSIS.
Code:
using System;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop;
using Excel = Microsoft.Office.Interop.Excel;

public void Main()
{
    Excel.Application xlApp = new Excel.Application();
    Excel.Workbook xlWorkBook = xlApp.Workbooks.Open("C:\\ExcelDirectory\\DATA.xlsm"); // absolute path needed
    xlApp.Run("Formatting"); // method overloads allow you to send it parameters, etc.
    xlWorkBook.Close(true); // first parameter is SaveChanges
    xlApp.Quit();
}

Error on line 1 of Public void Main:

Additional information: Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

Interop reference was added although manually because the install (exe) from MS would not do the job.  Maybe the .dll's are no good?  Please help and keep in mind I am a novice in this area.

A: Problem solved!!  The issue is, as others have stated in other posts, I need Office installed.  Interop on its own will NOT run macros or interact with Office products.


text:
Q: Is it possible in VueJS to give component prop more than one type and more than one default value? I know I can give any prop its expected type and default value like this:
export default {
            name: "myComponent",
            props: {
                myProp: { type: String, default: 'any text' }
           }
    }

And I so in documentation I can give 2 types as array like this:
export default {
        name: "myComponent",
        props: {
            myProp: [String, Array]
            }
}

BUT I would expect I can also give any of these types a default value also (this is not working): Is it possible?
export default {
        name: "myComponent",
        props: {
          myProp: **[{type: String, default: ''}, {type: Array, default: []} ]**
       }
}

A: I think it's impossible, for example if you have
export default {
    name: "myComponent",
    props: {
      myProp: [
        {type: String, default: ''},
        {type: Array, default: []}
      ]
   }
}

then when you write your component without passing myProp:
<my-component />

Then my-component doesn't know it should take value from default String or default Array definition.


text:
Q: JAXB Wrapped generic object's Setter method NEVER called I am trying to unmarshall an ArrayList of a generic class called Key.
the Key has setValue() method which recieves a generic parameter.
Key class
@XMLRootElement(name = "Key")
public class Key<T>{

    @XMLElement(name = "Key")
    public setKey(T value){
    this.value = value
    }
}

The specific ArrayList
@XMLElementWrapper(name = "Keys")
@XMLElement(name = "Key")
public setKeys(ArrayList<Key> keys){
this.keys = keys;
}

This part of the XML file
<Keys>
    <Key>2</Key>
</Keys>

Running the code would create the ArrayList and WILL have a single Key object in it.
But the Key would be Null.
(Ive tried debugging and could notice that it does not call the setKey() setter of the class)
Anything to do with the fact it's generic?
Thanks in advance.
EDIT
In the past day ive debugged this alot, i can say now that the problem is with the fact that after instantiating the ArrayList, while creating each Key per Key Tag in the XML, the unmarshaller uses the Key's empty constructor and just NEVER calls the setter of it, therefore i have an ArrayList containing Keys which their 'value' data member is null.
Can anyone please explain what am I doing wrong? Why does the setter not getting called?
Thank you.

A: You are probably out of luck.  How is the unmarshaller supposed to know that 2 is an integer and not a double or a long or a timestamp or some other class with a custom adapter that can parse 2 into itself.
The annotations you want are basically below (minus the @XmlJavaTypeAdapter which I will explain in a moment) but if you try and run that code without the adapter you will get a NullPointerException because JAXB cannot handle the @XmlValue annotation on an Object (which is how it treats T).  The reason JAXB cannot handle it is because it has no way of knowing what the object is.
Now, if you have your own custom rules for determining the type of T (e.g. when coming from XML T is always an Integer or T is an Integer if it doesn't contain a '.' and a Double otherwise) then you can implement your own logic using an adapter which is what I've demonstrated below (I used the second rule).
@XmlRootElement(name="root")
public class SO {

    private List<Key<?>> keys;

    @XmlElementWrapper(name="Keys")
    @XmlElement(name="Key")
    public void setKeys(List<Key<?>> keys) {
        this.keys = keys;
    }

    public List<Key<?>> getKeys() {
        return keys;
    }

    @XmlType
    public static class Key<T> {

        private T val;

        @XmlValue
        @XmlJavaTypeAdapter(ToStringAdapter.class)
        public void setKey(T val) {
            this.val = val;
        }

        public String toString() {
            return "Key(" + val + ")";
        }

    }

    public static class ToStringAdapter extends XmlAdapter<String, Object> {

        @Override
        public Object unmarshal(String v) throws Exception {
            if(v.contains(".")) {
                return Double.parseDouble(v);
            } else {
                return Integer.parseInt(v);
            }
        }

        @Override
        public String marshal(Object v) throws Exception {
            return v.toString(); //Will never be called anyway so you could also throw an exception here
        }

    }

    private static final String XML_INT = "<root><Keys><Key>2</Key></Keys></root>";
    private static final String XML_DOUBLE = "<root><Keys><Key>2.7</Key></Keys></root>";

    public static void main(String [] args) throws Exception {
        JAXBContext jaxbContext = JAXBContext.newInstance(Key.class, SO.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        SO so = (SO) unmarshaller.unmarshal(new StringReader(XML_INT));
        System.out.print(so.keys);
        System.out.println(" " + so.keys.get(0).val.getClass().getSimpleName());
        so = (SO) unmarshaller.unmarshal(new StringReader(XML_DOUBLE));
        System.out.print(so.keys);
        System.out.println(" " + so.keys.get(0).val.getClass().getSimpleName());
    }

}


text:
Q: When redirecting between different pages of website in codeiginiter there is white screen which comes for 2 seconds and after that the page is loaded I am having trouble with a website that uses codeigniter, when i redirect from 1 page to another everything is fine except there is a gap of 2 seconds when a white screen is displayed after which the page is loaded.
How can i fix this ?

A: probably to many HTTP request so browser have problem to load or maybe u have some css or js that blocking browser to render so that provide delay to load page.


text:
Q: How many parameters is optimal for constructor? I have a C# project that needs to refactor. Project uses WPF+MVVM Light toolkit. I found the MainViewModel(...) constructor that receives about 50 parameters (factories interfaces). I think not. Am I right? I'm interested, because I want to improve my OOP thinking. Thanks.
P.S. Sorry for my grammar. Check me if you find errors.

A: Clean Code: A Handbook of Agile Software Craftsmanship, page 40, states that...

The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification - and then shouldn't be used anyway.

Consider the book as guidelines for software design, and as such, recommendations when thinking about your code structure.

A: 50 factory interfaces means your ViewModel is way too big and trying to do too many things at the same time. You should break it into separate ViewModels that will appear as properties on the main view model.
WPF allows composition and any framework that allows ViewModel first (ie anything except PRISM) will compose the corresponding views form the ViewModel it encounters. I'm not sure about MVVM Light but with Caliburn.Micro this is almost a non-issue.
If MVVM Light doesn't automate this, you'll have to bind the WPF controls that will contain a specific child model's view to the child model property on the main view model.
Another option is to bundle multiple factory interfaces into parameter objects and pass these to the constructor, bringing the number of parameters to 4-5 instead of 50. This is the Introduce Parameter Object refactoring. Some tools like ReSharper provide automation support for this refactoring.
If you combine this with a DI container the parameter objects can get initialized automagically simply by registering the individual interfaces.
The best solution though is to break the main model into submodels

A: You might look into using a Dependency Injector like Unity.  Register all your Service, Factory, and associated Classes you need with the Unity Container and then you only need a single parameter for your ViewModel constructor which is the Unity Container.
50 parameters for a constructor seems insane to me...


text:
Q: Angular js Controllers I am using angular js for my front end web application...
I have encountered a problem..the problem.is..
1)In login page i am giving username and password which has one controller for this screen.
2)I have a forget password link on this screen.
3)Separate screen appears when clicked on forget password link.
4)I have a separate controller for this forget password screen.
5)I want to get username value to forget password screen when i enter username in login screen and clicked on forget password link.
6)I am trying to use a service instead of $rootscope..
Please help me on this...

A: You can use service to pass data between controllers. Please see Demo in plunker.
http://plnkr.co/edit/g622YzgpqkJStPZaNj5i?p=preview
    var app = angular.module('app', []);
app.controller('LoginScreenController', ['$scope', 'User', function($scope, User) {

$scope.userName = User.userName;

$scope.forgotPassword = function(userName) {
    User.userName = userName;
};
}])
.service('User', ['$window', function(win) {
this.userName = "";
}])
.controller('ForgotPasswordController', ['$scope', 'User', function($scope, User) {
$scope.$watch(function() {
    return User.userName
}, function(newValue) {
    $scope.userName = newValue;
});

}]);


text:
Q: Alignment of a TikZ environment with a minipage environment I have a TikZ environment with a minipage environment, and I would like them aligned at the top. I use the option baseline=(current bounding box.north) with the TikZ environment, and the the option [t] with the minipage environment.  The displays of the two environments are not aligned.
\documentclass{amsart}
\usepackage{amsmath}
\usepackage{amsfonts}

\usepackage{tikz}
\usetikzlibrary{calc,positioning,intersections,quotes,decorations.markings,decorations.pathreplacing}

\begin{document}

\noindent \begin{minipage}[t]{3.75in}
\raggedright{$\triangle\mathit{ABC}$ is a right triangle, and its right angle is at $C$. $\mathit{CP}$ is an altitude of it. What is the value of $x - y$?}
\begin{tabbing}
\hspace*{3em} \= \kill
\> \textbf{a.) }$-30$ \\
\> \textbf{b.) }$-15$ \\
\> \textbf{c.) }0 \\
\> \textbf{d.) }15 \\
\> \textbf{e.) }30
\end{tabbing}
\end{minipage}
%
\hspace{-1.5cm}
%
\begin{tikzpicture}[baseline=(current bounding box.north)]

\coordinate (A) at (0,0);
\coordinate (C) at (5,2);

%B is the intersection of the line through C that is perpendicular to $\overline{AC}$ and
%the line through A inclined at an angle of 30 degrees.
\path[name path=a_line_through_A_to_locate_B] (A) -- ($(A) +(-15:7)$);
\path[name path=a_line_through_C_perpendicular_to_AC_to_locate_B] (C) -- ($(C)!4.5cm!90:(A)$);
\coordinate[name intersections={of=a_line_through_A_to_locate_B and a_line_through_C_perpendicular_to_AC_to_locate_B, by=B}];
\draw (A) -- (B) -- (C) -- cycle;

%A right-angle mark is drawn at C.
\coordinate (U) at ($(C)!4mm!-45:(B)$);
\draw (U) -- ($(C)!(U)!(B)$);
\draw (U) -- ($(C)!(U)!(A)$);

\coordinate (P) at ($(A)!(C)!(B)$);
\draw (C) -- (P);

%A right-angle mark is drawn at P.
\coordinate (V) at ($(P)!4mm!-45:(A)$);
\draw (V) -- ($(P)!(V)!(A)$);
\draw (V) -- ($(P)!(V)!(C)$);

%The labels for A, B, and C are typeset.
\node (label_for_A) at ($(A)!3mm!-90:(B)$){$A$};
\node (label_for_B) at ($(B)!3mm!90:(A)$){$B$};
\node (label_for_P) at ($(P)!3mm!-90:(B)$){$P$};
\node (label_for_C) at ($(C)!-3mm!(P)$){$C$};

%The angle at A is labeled x.
\draw[blue] let \p1=($(A)-(C)$), \n1={atan(\y1/\x1)} in (-15:0.5) arc (-15:\n1:0.5);
\draw let \p1=($(A)-(C)$), \n1={atan(\y1/\x1)} in node[font=\footnotesize, anchor={0.5*(\n1-15)-180}] at ({0.5*(\n1-15)}:0.5){$x$};

%An angle at C is labeled y.
\draw[blue] let \p1=($(C)-(P)$), \n1={atan(\y1/\x1)}, \p2=($(C)-(B)$), \n2={atan(\y2/\x2)} in ($(C) +({\n1-180}:0.5)$) arc ({\n1-180}:\n2:0.5);
\draw let \p1=($(C)-(P)$), \n1={atan(\y1/\x1)}, \p2=($(C)-(B)$), \n2={atan(\y2/\x2)} in node[font=\footnotesize, anchor={0.5*(\n1-180+\n2)-180}] at ($(C) +({0.5*(\n1-180+\n2)}:0.5)$){$y$};

\end{tikzpicture}
\end{document}

A: Adding the following line at the end of your tikzpicture:
\draw (current bounding box.south west) rectangle (current bounding box.north east);

reveals the bounding box of the picture:

Two problems can be spoted:

*

*Above the label $C$ in the figure there is a bit of space. This can be removed if you use [inner sep=0pt] for the node (label_for_C)

*More important, option [t] of minipage does not align the content at the top of the "bounding box" of the minipage, but instead at the baseline of its top line. This can be solved by a little hack: to add \vskip0pt as the first content of the minipage. This way, the first "line" of the box is empty and you get the right alignment.

Using both tricks, the result is:

We can now remove the frame:


text:
Q: remove debug log from hadoop console output I want to remove DEBUG Messages from my hadoop console output. I have already set
 export HADOOP_ROOT_LOGGER=WARN,DRFA
 export HADOOP_JHS_LOGGER=WARN,DRFA

in the hadoop-env.sh file and
hadoop.root.logger=WARN,console
hadoop.security.logger=WARN,console

in the log4j.properties file in hadoop/bin
Currently when I run
    hadoop fs -lsr /directory/
 the output is the below. I only want to see the actual files rather than all the debug/info statements. thanks.
12:03:58.408 [sendParams-0] DEBUG org.apache.hadoop.ipc.Client - IPC Client (47)     connection to ...
12:03:58.408 [IPC Client (47) connection to xxxxxx from xxxx]         DEBUG org.apache.hadoop.ipc.Client - IPC Client (47) connection to ...
12:03:58.408 [main] DEBUG org.apache.hadoop.ipc.RPC - Call: getListing 1
drwxr-xr-x   - abc supergroup          0 2013-02-21 18:01 /user/xxxx/res
12:03:58.409 [sendParams-0] DEBUG org.apache.hadoop.ipc.Client - IPC Client (47)      connection to xxxxxx/xxxxx from xxxx sending #13
12:03:58.410 [IPC Client (47) connection to xxxxxx/xxxxx from xxxx]     DEBUG org.apache.hadoop.ipc.Client - IPC Client (47) connection to      xxxxxx/xxxxxx from xxxx got value #13
12:03:58.410 [main] DEBUG org.apache.hadoop.ipc.RPC - Call: getListing 1
drwxr-xr-x   - xxxxx supergroup          0 2013-02-21 12:20 /user/xxxxx/rhipeTest
12:03:58.410 [sendParams-0] DEBUG org.apache.hadoop.ipc.Client - IPC Client (47)       connection to xxxxx/xxxx from tenglin sending #14
12:03:58.411 [IPC Client (47) connection to xxxxxx from xxxxx]        DEBUG org.apache.hadoop.ipc.Client - IPC Client (47) connection to        xxxxxx/xxxxxx from xxxxxxx got value #14
12:03:58.411 [main] DEBUG org.apache.hadoop.ipc.RPC - Call: getListing 1
-rw-r--r--   2 xxxxx supergroup       1229 2013-02-21 12:20        /user/xxxx/rhipeTest/ibm.n_1361467245357.dat
drwxr-xr-x   - xxxxx supergroup          0 2013-02-22 11:47 /user/xxxx/test
12:03:58.412 [sendParams-0] DEBUG org.apache.hadoop.ipc.Client - IPC Client (47)        connection to xxxx/xxxxx from tenglin sending #15
12:03:58.413 [IPC Client (47) connection to xxxx from xxxxx]         DEBUG org.apache.hadoop.ipc.Client - IPC Client (47) connection to          xxxxx/xxxxx from xxxxx got value #15
12:03:58.414 [main] DEBUG org.apache.hadoop.ipc.RPC - Call: getListing 2
-rw-r--r--   2 tenglin supergroup       5092 2013-02-22 11:47        /user/xxxxx/test/aa.us_1361551612607.dat
-rw-r--r--   2 tenglin supergroup       5125 2013-02-22 11:47 /user/xxxxx/test/aapl.q_1361551612607.dat
....


text:
Q: Get computername from hostname in C++? The IP address is 192.168.23.4. I am able to get the hostname from the ipaddress using the following code snippet:
struct sockaddr_in sa;
char str[INET_ADDRSTRLEN];
inet_pton(AF_INET, "192.168.23.4", &(sa.sin_addr));

struct sockaddr_in saGNI;
char hostname[NI_MAXHOST];
char servInfo[NI_MAXSERV];
u_short port = 27015;
saGNI.sin_family = AF_INET;
saGNI.sin_addr.s_addr = sa.sin_addr.s_addr;
saGNI.sin_port = htons(port);

DWORD dwRetval = getnameinfo((struct sockaddr *) &saGNI,
    sizeof(struct sockaddr),
    hostname,
    NI_MAXHOST, servInfo, NI_MAXSERV, NI_NUMERICSERV);
printf("HostName: %s", hostname);

I am getting an output of the form

ComputerName.domain.com

How do I get the Computername from the hostname?
Eg Input

ComputerName.domain.com

Eg Output

ComputerName

Is there any way to directly get the ComputerName of a system whose IP address is known?
I am looking for the same result as displayed using the Hostname command on the remote system.

A: Check the manual pages for getnameinfo
http://man7.org/linux/man-pages/man3/getnameinfo.3.html
According to the manual pages, you should set the NI_NOFQDN flags.
 NI_NOFQDN
          If set, return only the hostname part of the fully qualified
          domain name for local hosts.

A: As suggested by emirc,
the following code is printing Computername:
struct sockaddr_in sa;
char str[INET_ADDRSTRLEN];
inet_pton(AF_INET, "192.168.23.4", &(sa.sin_addr));

struct sockaddr_in saGNI;
char hostname[NI_MAXHOST];
char servInfo[NI_MAXSERV];
u_short port = 27015;
saGNI.sin_family = AF_INET;
saGNI.sin_addr.s_addr = sa.sin_addr.s_addr;
saGNI.sin_port = htons(port);

DWORD dwRetval = getnameinfo((struct sockaddr *) &saGNI,
    sizeof(struct sockaddr),
    hostname,
    NI_MAXHOST, servInfo, NI_MAXSERV, NI_NOFQDN);
printf("HostName: %s", hostname);

Note:
I have changed the flag from
NI_NUMERICSERV
to
NI_NOFQDN

A: You mean, you want to truncate the string before the first period?
std::string host(hostname);
size_t pos = host.find('.');
if (pos != std::string::npos)
{
   host = host.substr(0,pos);
}
strcpy(hostname, host.c_str());

A: If you are interested in finding the host name of the computer on which the code is running, Boost.Asio could simplify the task:
#include <iostream>
#include <string>
#include <boost/asio.hpp>

int main() {
  std::string hostname = boost::asio::ip::host_name();
  std::cout << "hostname = " << hostname << std::endl;
}

Note that this needs to be compiled with the -lpthread option.


text:
Q: kotlin class type that contains other type There is A Mongo Document named Product
one product has many ProductOption and option has type from 1 to 5.
the properties type is differ by its option type(example below).
What I want to do is defining QuestionThisType below.
can you recommend for me?
@Document("Product")
data class Product(
    val id: Int,
    val options: List<ProductOption>,
) {
    data class ProductOption(
        val type: Int,
        val properties: QuestionThisType
    )
}

if type == 1
then
data class Property1(
   val one: String
)

if type == 2
then
data class Property2(
   val a: String,
   val b: String,
)
...

A: This may work for you - create your own Spring Data Converter
First, imagine a general way to store the data of ProductOption in a data type that Mongo can represent, e.g. Map<String,Any> that contains nested Map<String,Any>.  Then remove the inner class:
@Document("Product")
data class Product(
    val id: Int,
    val options: List<ProductOption>,
)

Now you need an interface to link the real ProductOptions together for types 1,2,3,4,5 and then concrete classes for each of them
interface ProductOption {
    val type: Int
    val properties: Any
}

data class ProductOption1(
    override val type: Int = 1,
    override val properties: Property1,
) : ProductOption {
    data class Property1(
        val one: String,
    )
}

data class ProductOption2(
    override val type: Int = 2,
    override val properties: Property2,
) : ProductOption {
    data class Property2(
        val a: String,
        val b: String,
    )
}

etc...

Then you need to create a converter that takes these concrete classes that implement ProductOption and converts them to/from what get stored in Mongo: ProductOptionGeneral
import org.springframework.core.convert.converter.Converter
import org.springframework.data.convert.ReadingConverter
import org.springframework.data.convert.WritingConverter

class MapToProductOptionConverter : Converter<Map<String,Any>, ProductOption> {
    override fun convert(source: Map<String,Any>): ProductOption? {
        val properties = source["properties"] as Map<String, Any>
        when (source["type"] as Int) {
            1 -> {
                ProductOption1(
                    properties = ProductOption1.Property1(
                        one = properties["one"] as String
                    )
                )
            }
            else -> TODO()
        }
    }
}

@WritingConverter
class ProductOptionToMapConverter : Converter<ProductOption, Map<String,Any>> {
    override fun convert(source: ProductOption): Map<String,Any>? {
        TODO()
    }
}

Lastly register your converters
@Configuration
@EnableMongoRepositories
class MongoConfig {

    @Bean
    fun customConversions(): MongoCustomConversions {
        return MongoCustomConversions(
            listOf(
                MapToProductOptionConverter(),
                ProductOptionToMapConverter(),
            )
        )
    }

(If you had asked about handling JSON deserialization into a polymorphic class structure, this is possible in a much simpler way.  This could be wholly different approach for you.  You'd retrieve the data from Mongo as a BSON object, convert to JSON and use Jackson's ObjectMapper in the way I describe in this Stackoverflow Answer: https://stackoverflow.com/a/72106352/1847378)


text:
Q: Sublime Python Input in Console (Automate the boring stuff) I have been trying to learn Python using Al Sweigart's book.
Using the Sublime Text 3 I found it hard to run this code which is identical to the code in the book. I have changed the setting over to View > Syntax > Python. The code is:
print ('Hello world!')
print ('What is your name?')
myName = input()
print ('It is good to meet you,' + myName)
print ('The length of your name is:')
print (len(myName))

The console has the following output:
Hello world!
What is your name?

I typed in a name. But nothing happened from then on.
Because of two posts on here (Post 1; Post 2), I installed the SublimeREPL package, but I am not entirely sure how to use it and whether it is what I need. I can find the packaged under Tools > SublimeREPL > Python > and then a bunch of versions.
Can someone help? Help is much appreciated.


text:
Q: Display PDF on new tab after ajax call MVC C# I am new at C# and I want to display a newly and dynamically created PDF to the web browser client side, on a new tab, using HttpResponseMessage.
The PDF created is valid.
This is my controller code :
    [HttpGet]
    public HttpResponseMessage ShowPDF()
    {

        MemoryStream ms = new GetPDF();
        Byte[] bytes = ms.GetBuffer();

        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        Response.AppendHeader("Content-Disposition", "inline; filename=test.pdf");

        result.Content = new StreamContent(ms);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

        return result;
    }

After clicking on button on HTML page, nothing is happening, no error but no new pdf displayed too. I tried using both MemoryStream or Buffer, but nothing seems to work.
EDIT
Here is my view code :
        <button id="GetPDF" class="btn btn-primary pull-right">GET PDF</button>

Javascript :
    $('#GetPDF').click(function (e) {
        e.preventDefault();
        $.ajax({
            url: '@Url.Action("ShowPDF", "Controller")',
            method: 'GET',
            success: function (data, textStatus, jqXHR) {
             //Showing something but what
            },
            error: function ( jqXHR, textStatus, errorThrown ) {
             //Showing error message
            }
        });
    });

A: Okay, I managed to make it work. Here is my solution, I will optimise it tomorrow ...
Javascript :
        $('#GetPDF').click(function (e) {
        window.open('@Url.Action("ShowPDF", "Controller")');
    });

Controller Method :
    [HttpGet]
    public ActionResult ShowPDF()
    {
        try
        {
            MemoryStream ms = new MemoryStream(GetPDF().ToArray());
            FileStreamResult filestream = new FileStreamResult(ms, "application/pdf");
            return filestream;
        }
        catch (Exception ex)
        {
            throw new Exception();
        }
    }

GetPDF returns a MemoryStream, but closed. You have to get Byte[] element by using ToArray(), then to create another MemoryStream using constructor.
Thanks a lot to Adyson and mason for the help.


text:
Q: SQL (MySQL) to generate continuous dates/month for reporting I am doing a migration task, migrating a java application from Oracle Datastore to MySql 5.
You can imagine that some queries need to be rewritten. everything goes well until I came to Reporting module. Hope you guys could give me some hints.
Shortly I have a table: (say table name "Foo")
+-------------+-------------+
|             |             |
| d (datetime)| v (number)  |
+-------------+-------------+
| 2000-01-01  |     3       |
| 2000-01-11  |     2       |
| 2002-07-01  |     1       |
+-------------+-------------+

What i have done so far:
when user gives startdate, enddate as parameters, i generate sum-report by Day and by month:
e.g. startDate 2000-01-01, endDate: 2003-01-01
+-------------+-------------+
| day         | Sum         |
+-------------+-------------+
| 2000-01-01  |     3       |
| 2000-01-11  |     2       |
| 2002-07-01  |     1       |
+-------------+-------------+

+-------------+-------------+
| Month       | Sum         |
+-------------+-------------+
| 2000-01     |     5       |
| 2002-07     |     1       |
+-------------+-------------+

but the requirement is, if the date is not in table, list the Day/month anyway, with sum=0. like:
+-------------+-------------+
| Month       | Sum         |
+-------------+-------------+
| 2000-01     |     5       |
| 2000-02     |     0       |
| 2000-03     |     0       |
| 2000-04     |     0       |
| 2000-05     |     0       |
|  ...        |    ...      |
| 2002-07     |     1       |
|  ...        |     0       |
+-------------+-------------+

This was achieved with Oracle, but I am stuck with Mysql. Can anyboy give some hints, better with example codes, how to achieve it with mySql?
thank you.


text:
Q: How to check Unicode char in python def order_check_uni(body):
    ccnt=0
    for x in body:
        if x.isUpper():
            ccnt+=1
        if ccnt>2:
            print 'success'

I try to find char non ASCII or special char or unicode char or cyrillic char like абвгдеёжзийклмнопрстуфхцчшщъыьэюя ®©™ in string body with that script, i try to replace isUpper() with isascii() and len(x) == len(x.encode), with unichr() and the other function but still find error, can somebody help me?

A: for x in body:
    if ord(x) > 127:
        # character is *not* ASCII

This works if you have a Unicode string. If you just want to detect if the string contains a non-ASCII character it also works on a UTF-8 encoded byte string.
Update for Python 3: the above still works on Unicode strings, but ord no longer works for byte strings.  But that's OK, because indexing into a byte string already returns an integer - no conversion necessary!  The code becomes even simpler, especially if you combine it with the any function:
if any(x > 127 for x in body):
    # string is *not* ASCII

A: Not Sure, whats your exact requirement is
>>> u'aあä'.encode('ascii', 'ignore')
'a'

I Found this at Python: Convert Unicode to ASCII without errors

A: you can chech if a string is unicode by using the method isinstance()
s = u'aあä'
if isinstance(s, unicode):
  do_something()


text:
Q: Ursina not importing in python I'm getting error:
Traceback (most recent call last):

  File "C:\Users\user\Downloads\blocky\main.py", line 1, in <module>
    import ursina as ue
ModuleNotFoundError: No module named 'ursina'

I tried:
pip install ursina
wait I also did
python -m pip install ursina

A: Since you're using import ursina as (custom name), you currently importing ursina as a local namespace and doing this will be annoying for most beginners.
Example: (namespace).function()/PACKAGE CONTENT.function()
I recommend that you use from ursina import * because this will extract everything and remove the need for namespace on every function/PACKAGE CONTENT.
Example: function()/PACKAGE CONTENT.function()
Also, try reinstalling python.

A: Try using pipwin.
First do
pip install pipwin,

Then do pipwin install ursina

A: You must have any other libraries installed in the same virtual
environment or the default, that causes conflict with 'ursina'
Try store the libraries u use in the project in a new empty virtual environment

1, Install https://pypi.org/project/virtualenv/

 pip install virtualenv

2, Create a new folder for your environment (by convention it is advisable to call it venv.) locate the folder with the console

source /python -m virtualenv .

3, Active (to deactivate it would be the same but in the end it is placed deactivate.)

-- in Windows
 source /venv/Scripts/activate

-- in Linux
 source /venv/bin/activate

the name of the virtual environment will appear at the beginning of the line in the command terminal, (venv in this case).

4, To see the packages that we have installed in our virtual environment we execute the following command:

(venv) source  /pip list

5, install 'ursina' n all the libs u need

(venv) source  /pip install ursina

A: If you can't install ursina (neither one option from above worked), just download the GitHub repository and import ursina from there. You will need to put the folder inside your project directory.

A: use this instead
from ursina import *

app= Ursina()
(code)
app.run()

this will help your issue


text:
Q: Why Python can't see assignments if they were made inside the scope of a function? Here's my code:
player1 = player2 = ball = score1 = score2 = None

def reset_game():
    player1 = Pad(PAD_WIDTH, (WINDOW_HEIGHT / 2) - (PAD_HEIGHT / 2), FIRST_PLAYER)
    player2 = Pad(WINDOW_WIDTH - (PAD_WIDTH * 2), (WINDOW_HEIGHT / 2) - (PAD_HEIGHT / 2), SECOND_PLAYER)
    ball = Ball((WINDOW_WIDTH / 2) - (BALL_SIZE / 2), (WINDOW_HEIGHT / 2) - (BALL_SIZE / 2))
    score1 = Score(((WINDOW_WIDTH / 2) - (SCORE_SIZE / 2.8) - SCORE_SPACING * 2), SCORE_SPACING, 1)
    score2 = Score(((WINDOW_WIDTH / 2) - (SCORE_SIZE / 2.8) + SCORE_SPACING * 2), SCORE_SPACING, 2)

reset_game()

I define them initially like this (I know it's a bit java-ish, but anyway), because when I press ESCAPE, I want to reset the whole game to its initial values:
if e.key == pygame.K_ESCAPE:
    reset_game()

It's pathetic to copy and paste the whole thing. Running like this, Python gives me the error:

That's because Python just can't see the assignment inside the function.
def redraw():
    pygame.display.flip()
    screen.fill((0, 0, 0))

    if game_screen == SINGLE_PLAYER or game_screen == MULTIPLAYER:
        draw_middle_line()
        player1.draw()
        player2.draw()
        score1.draw()
        score2.draw()
        ball.draw()

If I make the assignments in global scope, it works. Why Python can't see the assignments even if I "declared" as None and called the function with the assignments afterwards? (I know this is c/c++/java-ish thinking, but it makes sense nonetheless).

A: It isn't that "Python can't see assignments", but simply that you didn't declare your names as global.
https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces
https://docs.python.org/3/reference/simple_stmts.html#global
Change your function to look like this and try it:
def reset_game():
    global player1, player2, player3
    player1 = Pad(PAD_WIDTH, (WINDOW_HEIGHT / 2) - (PAD_HEIGHT / 2), FIRST_PLAYER)
    player2 = Pad(WINDOW_WIDTH - (PAD_WIDTH * 2), (WINDOW_HEIGHT / 2) - (PAD_HEIGHT / 2), SECOND_PLAYER)
    ball = Ball((WINDOW_WIDTH / 2) - (BALL_SIZE / 2), (WINDOW_HEIGHT / 2) - (BALL_SIZE / 2))
    score1 = Score(((WINDOW_WIDTH / 2) - (SCORE_SIZE / 2.8) - SCORE_SPACING * 2), SCORE_SPACING, 1)
    score2 = Score(((WINDOW_WIDTH / 2) - (SCORE_SIZE / 2.8) + SCORE_SPACING * 2), SCORE_SPACING, 2)

PS.  Using global variables is very poor design.  I recommend using a different approach to organizing your program's data and code.

A: x = None

def foo():
    global x
    x = 10

foo()
print x #prints 10

Any assignment in a local scope, is considered a local variable, you need to get it from the global scope

A: If you don't send variables to the function it will try to create it locally, so to allow the access it must be declared globally inside the function.
Example:
player1 = None

     def reset_game():
          global player1  #now you can modify player1
          player1 = Pad(PAD_WIDTH, (WINDOW_HEIGHT / 2) - (PAD_HEIGHT / 2), FIRST_PLAYER)

reset_game()


text:
Q: Representations of Nilpotent Lie Subalgebras Does every nilpotent lie subalgebra of gl(V) is representable by triangular matrices with 0 on the diagonal?

A: This is not true for rather simple reasons: Any one-dimensional subspace in $\mathfrak{gl}(V)$ is an Abelian (and hence nilpotent) Lie subalgebra. This can be represented by upper triangular matrices with $0$ on the diagonal if and only if it is spanned by a nilpotent map.
Engel's theorem as mentioned in the comment by @peter_a_g is not a theorem about nipotent Lie subalgebras in $\mathfrak{gl}(V)$ but about Lie subalgebras consisting of nilpotent endomorphisms of $V$. (It then implies that such a subalgebra is nilpotent, but the converse is not true.)


text:
Q: JPQL find entity by exact array match I have entity Monitor that contains attribute categories which is Set of entity Category. Is it possible to use JPQL to find entity Monitor by Set of Categories?
Something like this:
@Query("SELECT m from Monitor m where m.categories = :cats")
Monitor findByCategories(@Param("cats") Set<MessageCategory> cats);

This snippet throws an error com.impossibl.postgres.jdbc.PGSQLSimpleException: syntax error at or near "."
Thanks in advance

A: If your Monitor has only one categorie, so you can use IN clause in the query:
@Query("SELECT m from Monitor m where m.categories IN :cats")

But if your Monitor.categories field is a list this won't be working. There should be more complicated logic.
Updated 11.08.2017:
As I wrote in comments, you can transform list of category ids into the one string and compare with another. For this case the best way is create a view, but unfortunately this decision depends on SQL-engine. For PostgreSQL you can use something like this:
select m.*, string_agg(mc.catid, ',') as catids
FROM monitor as m
LEFT JOIN messagecategories as mc on mc.monitor_id = m.id
GROUP BY m.id;


text:
Q: Find all calls to interface implementers? There are a large number of classes in this codebase which use a specific interface.  However, picking a few at random, I've been unable to find one which is actually called anywhere; as such, I don't have a great idea of how to use it.
Is there a way in Eclipse to find every instance of any class which implements this interface?
In other words, suppose there exists an interface Interface, and classes ClassA, ClassB, ClassC, ..., ClassX,  which all implement it.  I want to see every point in the code where something like `ClassX obj = new ClassX().  Most of the classes I'm finding that implement this interface don't have any point where they're actually used; I assume they're for future use.

A: Yes, highlight the interface name and hit F4 or right click -> Open type hierarchy.
Update after OP's edit:
If you are using a framework that uses dependency injection like spring probably you don't find any reference because some of the implementations are defined in a xml file.
Also consider if some implementations are created and invoked via reflection.

A: Open the interface class, hold Control and move your mouse to interface's name, select open implementation. That's the simplest and easiest way to do.

A: Some classes might be loaded during runtime e.g. using reflection. To catch-them-all you can set a method entry breakpoint on the interface method. This is explained in this answer. That way all calls to implementation methods will suspend the JVM regardless of what is the object type.

Do note that unlike the line breakpoints the method breakpoints will really slow down the performance of the JVM.


text:
Q: Allocate contiguous static arrays in C (gcc compiler) I need to use 64kb of RAM for a buffer which will be used once in a lifetime. My total RAM is running short so I am planning to reuse the already allocated buffers to store the 64kb of data I need.
I am thinking about a way of allocating at compile time a set of static arrays in continuous location in order to reach my goal.
I am currently using a gcc compiler, the purpose of my procedure is to temporarily store data in RAM before transferring it in FLASH.
One idea, I don't know exactly how easy it would be, is to predetermine at a linker level which are the sector of data used for the already allocated buffers. At the moment the number of buffer present is reduced to 3 for some kb of space. This solution can not be the best one in the case that new buffers will be needed; asking developers to allocate some specific area of memory in the scatter file can be tedious and maybe can complicate stuff too much.
Thanks in advance.


text:
Q: How do I find if any one of the words in a file is in a very long string, which changes frequently in CMD batch I have this filename which gets dropped into a directory on a windows share, where it needs to be located into the right location on the users' local machines, depending on if the filename has one of the keywords in it or not.
For instance:
z:\mailbox\in\Very_but#very-very!long#filenameWITH-keyword+in^it

where z: is accessible from a set of win-7 or win-10 machines. And on these machines, there are these two directories:
c:\incoming\special
c:\incoming\regular

if the filename has one of the keywords embedded in it, it needs to be copied into the c:\incoming\special folder, if not it needs to go into c:\incoming\regular folder.
my keywords are in a file, say, c:\keywords.txt
at any given time (checked every 5 minutes) there may be no files, or only one file in the z:\mailbox\in directory.
so, this is what I come up for, which is not working: (the batch file assumes there is a file to process, I haven't figured what to do, if there isn't one, yet)
dir /b z:\mailbox\in > tmp.out
set /p file=<tmp.out
del tmp.out

set keyword_found_flag=0
for /F "tokens=*" %%keyword in (c:\keywords.txt) do (

echo %file% | find /i "%%keyword"
if errorlevel=0 set keyword_found_flag=1

)

The errorlevel is always zero regardless if the keyword is found or not
IF keyword_found_flag=1 (
    copy z:\mailbox\in\%file% c:\incoming\special
) ELSE (
    copy z:\mailbox\in\%file% c:\incoming\regular
)

I am not sure what to do here. Any help is appreciated

A: Why not use operator (&&) to set your flag if execution is match?

echo %file% | find /i "%%keyword" >nul && set keyword_found_flag=1

You also don't need create/delete tmp.out file for your process, use double for to for the file name in z:\mailbox\in and, and use another for to check file contains in c:\keywords.txt with file names in z:\mailbox\in...
@echo off

set "keyword_found_flag=" && for /f tokens^=* %%i in ('dir /on /b /a:-d "z:\mailbox\in\*.*"
')do for /F tokens^=* %%K in ('type c:\keywords.txt')do echo="%%~i"| find /i "%%~K" && (
     set "keyword_found_flag=1") || (set "keyword_found_flag=0")

Or...
@echo off

set "keyword_found_flag=" && for /f tokens^=* %%i in ('dir /on /b /a: -d "z:\mailbox\in\*.*"
')do for /F tokens^=* %%K in ('type c:\keywords.txt')do echo="%%~i"|find /i "%%~K" >nul && (
set "keyword_found_flag=1" && copy /v "%%~dpnxi" "c:\incoming\special\" ) || (
set "keyword_found_flag=0" && copy /v "%%~dpnxi" "c:\incoming\regular\" )


text:
Q: Mysql Query where max(time) less than today I have two tables, the first table ( job ) stores the data and the second table ( job_locations ) stores the locations for each job, I'm trying to show the number of jobs that job locations are less than today
I use the DateTime for the Date Column
unfortunately, the numbers that appear after test the next code are wrong
My code
SELECT *
FROM `job`
left join job_location
    on job_location.job_id = job.id
where job_location.cutoff_time < CURDATE()
group by job.id

Please help me to write the working Query.

A: I think you need to rephrase your query slightly.  Select a count of jobs where the cutoff time is earlier than the start of today.
SELECT
    j.id,
    COUNT(CASE WHEN jl.cutoff_time < CURDATE() THEN 1 END) AS cnt
FROM job j
LEFT JOIN job_location jl;
    ON j.id = jl.job_id
GROUP BY
    j.id;

Note that the left join is important here because it means that we won't drop any jobs having no matching criteria.  Instead, those jobs would still appear in the result set, just with a zero count.

A: As a note, you can simplify the count (in MySQL).  And, assuming that all jobs have at least one location, you don't need a JOIN at all.  So:
SELECT jl.job_id, sum( jl.cutoff_time < CURDATE() )
FROM job_location jl
GROUP BY jl.job_id;

If this is not correct (and you need the JOIN), then the condition on the date should go in the ON clause:
SELECT jl.job_id, COUNT(jo.job_id)
FROM job LEFT JOIN
     job_location jl
     ON jl.job_id = j.id AND jl.cutoff_time < CURDATE()
GROUP BY jl.job_id;


text:
Q: Grafana Microsoft SQL Server Datasource with service principal auth I am trying to configure in grafana a sql server datasource with service principal authentication.

But I have seen that I only have these two options.
does anyone know any possibility to connect to sql server like in azure monitor?

I've been looking for information about it, but haven't found anything.
For security reasons I need to change the authentication that I have right now with SQL Server Authentication (user/pass) for service principal authentication.
Thanks in advance.


text:
Q: Count difference in PIG query and MySql query results in GROUP BY My PIG Query is given below

emp = LOAD 'hdfs://master:9000/hrms/DimEmployee' AS  (EmployeeID,OrganizationID,EmploymentType);
grouped = group emp by (OrganizationID, EmploymentType);
AggEmploymentType = FOREACH grouped GENERATE group.OrganizationID, group.EmploymentType,COUNT(emp.EmployeeID) as cnt;
DUMP AggEmploymentType;

Below given is the step by step description of above pig query.

*

*LOAD 100097 records from HDFS file which is tab delimited.

*Group by the records by Company,EmploymentStatus

*Count the records by EmployeeID.

*Dump the output.

After execution of above query, Pig shell says, successfully read 100115 records.
I am getting below given three problems after Pig query executes successfully:

*

*Why pig is ready more records than available in HDFS
(100115>100097)

*Why There is warning message "ACCESSING_NON_EXISTENT_FIELD 27 TIMES"

*The result has count difference of 9 when I run same group by query in MySQL.

Please solve my problem as soon as possible. My pig,hadoop project is depending upon your prompt response. I am struck since last 5 days due to above problem

A: I don't think it is coincidence that you are loading extra records and you are also getting accessing non existent fields error. The non existent field error shows up when you are loading and there aren't enough columns. For example, you might get the error if you see a line like: hello,world when you are expected 3 columns.
Suggestion: The other thing to note is that COUNT(x) does not count items that are null. Try swapping out COUNT(emp.EmployeeID) with COUNT_STAR(emp.EmployeeID). COUNT_STAR takes nulls into account.
Suggestion: One thing that Pig will do when it doesn't have the fields is just put nulls in it. I suggest you add a filter before the GROUP that removes records with nulls (and also potentially "bad" records).
emp = FILTER emp BY EmployeeID IS NOT NULL AND
                    OrganizationID IS NOT NULL AND
                    EmploymentType IS NOT NULL;


text:
Q: How to mute SpeechRecognizer's beep sound without muting music from MediaPlayer Is it possible to mute SpeechRecognizer's beep sound without muting played music from MediaPlayer?
Here code:
speech = SpeechRecognizer.createSpeechRecognizer(this);
speech.setRecognitionListener(this);
recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, "en");
recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName());
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);

timer =  new Timer();
timer.schedule(new UpdateTimeTask(),500,2000);

MediaPlayer mp = new MediaPlayer();
AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.breathe);
mp.reset();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
AudioManager myAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
myAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, 0, 0);
try {
    mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
    mp.prepare();
}
catch (IOException e) {
    e.printStackTrace();
}

mp.start();

class UpdateTimeTask extends TimerTask {
public void run() {

    mActivity.runOnUiThread(new Runnable() {

        @Override
        public void run() {
            speech.stopListening();
            speech.startListening(recognizerIntent);
        }
    });
}

audio focus doesn't solve the problem, music is playing and I can hear beeps
I can't mute STREAM_MUSIC (or whole STREAM_SYSTEM) because I use it for MediaPlayer
Mute STREAM_ALARM isn't working for SpeechRecognizer
So how to mute that beep while MediaPlayer plays music
update
boolean gotFocus = requestAudioFocusForMyApp(MainActivity.this);
        if (gotFocus) {
            MediaPlayer mp = new MediaPlayer();
            AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.breathe);
            mp.reset();
            mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
            AudioManager myAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            myAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, 0, 0);
            try {
                mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
                mp.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mp.start();
        }

anti mostly code anti mostly code anti mostly code anti mostly codeanti mostly code anti mostly code anti mostly code anti mostly codeanti mostly code anti mostly code anti mostly code anti mostly codeanti mostly code anti mostly code anti mostly code anti mostly code

A: I updated my answer. This should work. Check it!
boolean gotFocus = requestAudioFocusForMyApp(this); /* bind with your context. */
/* You should pass your context of your service, because you are playing music via service. this parameter represents the context of your service */
                if(gotFocus) {
                   MediaPlayer mp = new MediaPlayer();
        AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.breathe);
        mp.reset();
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        AudioManager myAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        myAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, 0, 0);
        try {
            mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
            mp.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mp.start();
                }

private boolean requestAudioFocusForMyApp(final Context context) {
        AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);

        // Request audio focus for playback
        int result = am.requestAudioFocus(null,
                // Use the music stream.
                AudioManager.STREAM_MUSIC,
                // Request permanent focus.
                AudioManager.AUDIOFOCUS_GAIN);

        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            Log.d("AudioFocus", "Audio focus received");
            return true;
        } else {
            Log.d("AudioFocus", "Audio focus NOT received");
            return false;
        }
    }

https://developer.android.com/reference/android/media/AudioFocusRequest.html


text:
Q: How to configure maven to checkout multiple modules before module reactor fails How should I configure maven parent pom to checkout code before Module list fails because the pom cannot be found.
It seems the maven's reactor test for a module's pom occurs before the generate-sources phase when scm checkouts the projects with the projects' pom.
How can I fix this ?
<modules>
  <module>target/mod-1</module>
  <module>target/mod-2</module>
</modules>

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-scm-plugin</artifactId>
      <version>1.9.4</version>
      <executions>
        <execution>
          <id>mod-1</id>
          <phase>generate-sources</phase>
          <configuration>
            <connectionUrl>${mod-1.url}</connectionUrl>
            <scmVersionType>${mod-1.versionType}</scmVersionType>
            <scmVersion>${mod-1.version}</scmVersion>
            <checkoutDirectory>${mod-1.directory}</checkoutDirectory>
          </configuration>
          <goals>
            <goal>checkout</goal>
          </goals>
        </execution>
        <execution>
          <id>mod-2</id>
          <phase>generate-sources</phase>
          <configuration>
            <connectionUrl>${mod-2.url}</connectionUrl>
            <scmVersionType>${mod-2.versionType}</scmVersionType>
            <scmVersion>${mod-2.version}</scmVersion>
            <checkoutDirectory>${mod-2.directory}</checkoutDirectory>
          </configuration>
          <goals>
            <goal>checkout</goal>
          </goals>
        </execution>
      </executions>

.....

</build>


text:
Q: QBrush texture without tiling Is there an easy way to get rid of tiling when using a QBrush with texture?
QImage*   texture = CreateQImage();       // create texture
QBrush*   brush   = new QBrush(*texture); // create texture brush
QPainter* painter = CreateQPainter();     // create painter

painter->fillRectangle(0, 0, 500, 500, *brush);

Suppose we have a QImage texture with size of 20x20 pixels. The code above will tile this texture all across the rectangle being filled. Is there an easy way to draw only a single instance of this texture? The QBrush usage is crucial.
Theoretically, I could reload every fill and draw method of the QPainter that takes a QBrush as input and use a QPainter.drawImage() method, but I think there must be a simplier way.

Thanks, Tony.

A: I don't think there is (see Qt::BrushStyle - the only style with a texture tiles it), and it wouldn't really make sens IMO. If you just want one image, use the drawImage functions as you've stated.
(One of the problems with not tiling is: what do you fill the rest of the rectangle with? Nothing? Some default background color? Some other QBrush attribute?)


text:
Q: Installing Ubuntu On Dell Precision 5510 Has anyone had any success installing Ubuntu 14.04, 15.10, or any variety on the new Dell Precision 5510?
I have been trying for 3 days with very little success.
Issues I'm Facing

*

*The Intel 8260 wireless network card is not recognized.

*

*Fixed in by installing 14.04 and updating to kernel 4.2, which causes the thunderbolt 3 Ethernet dongle to not work.

*Can't hibernate or shut down.

*

*Tried Many things including:

*

*+acpi=off. Works for shutdown, but won't hibernate.

*I can't remember what else I've tried, but they were numerous.

*When installing Ubuntu 15.10:

*

*+First: get Missing Parameter in configuration file. Keyword Path
*fixed: tab -> live.

*I get a bunch of error messages about nouveau then the system hangs.

System Information

*

*Precision 5510 with a core i5, and the touch screen 4k display.

A: On my side I am now using Ubuntu 16.04 LTS (daily build image) which brings kernel 4.4 and it works pretty smoothly out of the box !
http://cdimage.ubuntu.com/daily-live/current/
EDIT : actually I am currently struggling with external monitors. I have been trying both nvidia and i915 drivers and I have to hot-plug my screen after login in to my session otherwise I get a freeze at the login screen. I also get 1 out 2 times a freeze when hotplugging my monitor once in the session.
dmesg reports :
[drm:intel_cpu_fifo_underrun_irq_handler [i915_bpo]] *ERROR* CPU pipe A FIFO underrun

A: How to Install Ubuntu 16.04 LTS on the Dell Precision 5510
[edit: Aside from the "Allow Linux to see your storage device" step, on newer install media, this guide is no longer necessary. Just install normally, everything works.]
I was able to get Ubuntu 16.04 LTS installed over the last few days. These are my notes from the installation. Multi-monitor connections via HDMI work. The thunderbolt 3 port also works for Ethernet and Display Port. Please feel feel to revise this, and read carefully, as there are almost certainly some errors. I'm not a Linux expert by any measure.
Disable nouveau in order to boot from the Linux live disk
Do this at grub before booting from Ubuntu install media to avoid crashes due misbehaving video card drivers.

Symptoms are random freezes and infinite errors, something like the
  following: nouveau PFIFO SCHED_ERROR. Fix by pressing 'e' on grub menu
  during boot and add "nouveau.modeset=0" to the end of the line
  starting with "linux". Now boot the live disk by pressing F10.

Allow Linux to see your storage device
When booting, press F2 or CTRL+p to access the UEFI configuration menu. Navigate to SATA Operation on the left, and set it on the right to either AHCI if you have a hard drive, or Disabled if you have only the NVMe drive. The reason that the setting SATA Operation > RAID 0 hides the NVMe drive from Linux is that it turns on a proprietary RAID + AHCI driver, stored in firmware, called Intel RST. Linux has a difficult time communicating with the Intel RST driver without a lot of tinkering.
Once you've booted in, and with no external monitor connected, install
normally. The following should be done only after you've rebooted into your newly installed system.
Install kernel 4.6 for Ubuntu
On newer install media this step isn't necessary. Run uname -a to see what kernel is running on your Ubuntu live cd. If it's version 4.6 or later, skip this step.
mkdir -p ~/Downloads/Precision_5510_install/kernel
cd ~/Downloads/Precision_5510_install/kernel
BASE_URL="http://kernel.ubuntu.com/~kernel-ppa/mainline/v4.6.2-yakkety"
wget "$BASE_URL"/CHECKSUMS
wget "$BASE_URL"/CHECKSUMS.gpg
wget "$BASE_URL"/linux-headers-4.6.2-040602_4.6.2-040602.201606100516_all.deb
wget "$BASE_URL"/linux-headers-4.6.2-040602-generic_4.6.2-040602.201606100516_amd64.deb
wget "$BASE_URL"/linux-image-4.6.2-040602-generic_4.6.2-040602.201606100516_amd64.deb
gpg --keyserver keyserver.ubuntu.com --recv 17C622B0 # Import the gpg keys from Ubuntu's mainline kernel team.
gpg --verify CHEKSUMS.gpg CHECKSUMS # Verify that the list of checksums is from Ubuntu.
sha256sum -c CHECKSUMS | grep 'OK' # Check the integrity of the downloaded files.
sudo dpkg -i *.deb

You can find the gpg keys to verify the files haven't been tampered with here.
Enable hibernation
First test to see if hibernation works:
sudo pm-hibernate

If you're able to resume, create a file to allow hibernation from the GUI.
cat <<EOF | sudo tee /etc/polkit-1/localauthority/50-local.d/com.ubuntu.enable-hibernate.pkla
[Re-enable hibernate by default]
Identity=unix-user:*
Action=org.freedesktop.upower.hibernate
ResultActive=yes

[Re-enable hibernate by default in logind]
Identity=unix-user:*
Action=org.freedesktop.login1.hibernate;org.freedesktop.login1.hibernate-multiple-sessions
ResultActive=yes
EOF

Install Dell drivers from the Ubuntu Driver Support Pack
This step can be problematic, since you're installing .debs intended for an older version of Ubuntu. There is probably a better solution for this, but I haven't figured it out yet.
Starting the laptop with a monitor plugged in via HDMI caused my machine to crash until I did this. It may require some troubleshooting on your end.
cd ../
wget http://downloads.dell.com/FOLDER01797540M/1/xps13_ult_x03.fish.tar.gz
tar xf xps13_ult_x03.fish.tar.gz
cd debs
sudo apt-get install libxdo3 xdotool
sudo dpkg -if workaround-screen-lock-malfunction_1_all.deb

ALSA defaults to sending sound to HDMI even if there's nothing plugged in. Fix it with this:
echo "options snd-hda-intel model=dell-headset-multi,dell-headset-multi" >> /etc/modprobe.d/alsa-base.conf

Set up Nvidia Optimus
First install bumblebee
sudo apt-get install bumblebee bumblebee-nvidia primus

Next, remove any exising nvidia packages and install newer ones.
sudo apt-get purge nvida-*
sudo add-apt-repository ppa:graphics-drivers/ppa
sudo apt-get update
sudo apt-get install nvidia-current nvidia-prime
sudo service lightdm restart

Add an indicator so you can tell whether Intel or Nvidia is being used.
sudo add-apt-repository ppa:nilarimogard/webupd8
sudo apt-get update
sudo apt-get install prime-indicator
nohup prime-indicator &

Increase the text size on TTY consoles (for 4k screens)
On the 4k screen variety of this laptop, the font size is nearly unreadable when switching to a TTY ( for example, when pressing CTRL+ALT+F1 from Unity ). You can change it like so:

*

*sudo dpkg-reconfigure console-setup

*Choose UTF-8

*Choose the default Combined - Latin, ... option ("Latin" includes the English alphabet)

*Select the terminus font

*Select 16x32

Hope it helps!

A: I haven't tried Ubuntu yet, but I was able to get Arch working on it. To do so, I got help from an Ubuntu post on installing Ubuntu on an XPS 15 9550. The Precision 5510 is basically the same computer with slight differences like which graphics card and processor it uses.
See this link for help, including getting past the nouveau crashes (those happened to me in Arch as well):
http://ubuntuforums.org/showthread.php?t=2301071
I'm pretty certain you'll want to use the latest Ubuntu version and not the LTS releases since these computers are brand new and support for some of the devices has only been added to the more recent kernel versions.

A: Steve,
I have been testing different versions of Ubuntu for use on one of the latest Dell Precision 5510's (i7, with Skylake) I ran into issues outside the scope of the problem described at first, but was able to get past them. Later, I ran into very similar problems as your describing, and following a post decided to try Ubuntu Gnome. I had success with the Ubuntu Gnome 15.04 found here, and then applying all updates. The resolution was changeable all hardware seemed to be working, but one issue remained. I was unable to shut down the laptop from the desktop power menu. It would get hung and unusable whenever I tried to restart or shutdown, so I had to use the power button. I found a post where someone suggested installing the following:
sudo apt-get update && sudo apt-get install laptop-mode-tools

They also said they had success with upgrading to 15.10 afterward, but it didn't work out so well on my model, here are the issues I experienced after upgrading to 15.10.

*

*Required adding "nomodeset" to kernel parameters in order to even see a Graphical greeter, would just hang on a gray screen.

*Required to manually unplug, then replug USB mouse in order to have it recognized.

*The resolution was locked at 4k and the display settings had no other options available for selection.

Hope this helps!