text:
Q: Preventing vs Ignoring Errors with a Try-Catch in Java I have been working on a few projects lately that use a flood fill on a 2D array to create a grid map for a game.
Part of the flood fill algorithm I am using grabs the neighboring "cells" in the grid and floods them if they are an open space and ignores them if they are not.
However, because I am grabbing neighbor cells, I am grabbing items from the array relative to the current cell like this: grid[y][x-1].
Obviously, when x == 0 an out of bounds error is thrown.  In order to address this I have been using a conditional statement to check that the index I am accessing is in the array. Like this:
if(x - 1 >= 0){do what I need to that neighbor}
I know I can also address the error by using a try catch.
However, I am not sure which is the proper solution.
There are a few specific questions I have:
1) Does using the conditional method to prevent an error from occurring, require more overhead and create less efficiency? (I may be flooding thousands of cells)
2) How exactly does the catch block work? Is it conditionally checking for errors in the background some how?
I also made a very small demo code to show you exactly what I am talking about, just scaled down:
public static void main(String[] args) {

    //declare our test array and initialize size 3
    String [] testArray = new String[3];

    //This is here for one of the methods I have been trying to avoid errors on
    int indexAdjuster = 5;

    //this the index of the array we are adjusting
    int i = 0;

    //now throw an error! uncomment to confirm there is an error if you want
    //testArray[i-indexAdjuster] = "error";
    //testArray[i+indexAdjuster] = "error";

    //IGNORE the error with a try catch
    try{
        //this would result in an out of bounds exception below index 0 (-5 specifically)
        testArray[0-indexAdjuster] = "error";

        //this would result in an out of bounds exception above index 2 (5 specifically)
        testArray[0+indexAdjuster] = "error";

    }catch(ArrayIndexOutOfBoundsException e){
        System.out.println("There was an error, but I ignored it");
    }

    //PREVENT an error with a condition test
    //it first checks if the adjusted index is at least 0
    //then it checks if the adjusted index is less than the length of the array
    if(i - indexAdjuster >= 0 && i + indexAdjuster < testArray.length){

        //this would result in an out of bounds exception below index 0 (-5 specifically)
        testArray[0 - indexAdjuster] = "This would be an error, but it is prevented";

        //this would result in an out of bounds exception above index 2 (5 specifically)
        testArray[0 + indexAdjuster] = "This would be an error, but it is prevented";

    }else{

        System.out.println("We just prevented the error");

    }

    System.out.println("Test Complete");

}

A: It depends, specifically on what you primary focus is: Speed or clean code.
If the error condition occurs rarely and the check is costly, catching an exception may be cheaper than checking beforehand. This conflicts the commonly accepted rule that catch blocks should not be used for regular flow control. Exceptions should be used to catch unexpected error conditions, an index outside an array is hardly unexpected.
The test can also be extracted into a separate method, making the code easier to read:
static boolean isValidIndex(String[] array, int i) {
    return i >= 0 && i < array.length;
}

Or use a resilient access method:
static String getIndex(String[] array, int i) {
    return i >= 0 && i < array.length ? array[i] : null;
}

(You may want to replace null with a constant value indicating an invalid value).
In your code you can simply use the getIndex() method for whatever index you calculated and act on the value it returns instead of the index. Same can be done for assigning to an index, if its appropiate to just ignore attempted assignments to non-existing indices:
static void setIndex(String[] array, int i, String value) {
    if (i >= 0 && i < array.length)
        array[i] = value;
}

The main issue you face is deciding if an out-of-bounds condition is just a normal case that has a reasonable default handling option or if it represents a real error that warrants aborting the method or program.
If its a real error condition, don't prevent it, don't catch it. Let it throw and bubble up the call stack. Whatever caller level initiated the whole action should be the one that responds to the execption. Its important to decide sensibly who is responsible for the handling, a deep-down detail method has often not enough information to make a reasonable decision what an error means - in those cases assign the responsibility to the caller (repeat until the caller can make the decision).

A: Using if statement to check your boundaries cause lots of overhead in each loop iteration.
I suggest you allocate a bigger array by 1 like:
String [] testArray = new String[3+1];

This cause that you don't need any if condition.
In response to your question about exception handling, it does not run any condition in background. It runs your code and after causing access violation determines you catch clauses.


text:
Q: Run time error 13 on for-each loop after a few items I am trying to list all email in Excel within all sub folders from Outlook:
I have searched and researched this for weeks without any luck.
'Requires reference to Outlook library
Option Explicit

Public Sub ListOutlookFolders()

    Dim olApp As Outlook.Application
    Dim olNamespace As Outlook.Namespace
    Dim olFolder As Outlook.MAPIFolder
    Dim rngOutput As Range
    Dim lngCol As Long
    Dim olItem As Outlook.MailItem

    Dim rng As Excel.Range
    Dim strSheet As String
    Dim strPath As String

    Set rngOutput = ActiveSheet.Range("A1")

    Set olApp = New Outlook.Application
    Set olNamespace = olApp.GetNamespace("MAPI")

    For Each olFolder In olNamespace.Folders
        rngOutput = olFolder.Name
        rngOutput.Offset(0, 1) = olFolder.Description
        Set rngOutput = rngOutput.Offset(1)
        For Each olItem In olFolder.Items
            Set rngOutput = rngOutput.Offset(1)
            With rngOutput
                .Offset(0, 1) = olItem.SenderEmailAddress ' Sender
            End With
        Next

        Set rngOutput = ListFolders(olFolder, 1, rngOutput)
    Next

    Set olFolder = Nothing
    Set olNamespace = Nothing
    Set olApp = Nothing

End Sub

Function ListFolders(MyFolder As Outlook.MAPIFolder, Level As Integer, theOutput As Range) As Range
    Dim olFolder As Outlook.MAPIFolder
    Dim olItem As Outlook.MailItem
    Dim lngCol As Long

    For Each olFolder In MyFolder.Folders
        theOutput.Offset(0, lngCol) = olFolder.Name
        Set theOutput = theOutput.Offset(1)

        If (olFolder.DefaultItemType = olMailItem) And (Not olFolder.Name = "Slettet post") Then
            For Each olItem In olFolder.Items
                If olItem.Class = olMail Then
                    With theOutput
                        .Offset(0, 1) = olItem.SenderEmailAddress ' Sender
                    End With
                    Set theOutput = theOutput.Offset(1)
                End If
            Next olItem <--- ERROR 13 here
        End If
        If olFolder.Folders.Count > 0 Then
            Set theOutput = ListFolders(olFolder, Level + 1, theOutput)
        End If
    Next olFolder
    Set ListFolders = theOutput.Offset(1)

End Function

The code runs fine for 10-20 items and then gives me an run time error 13 in the line stated above and when I hit debug it tells me that olItem is = Nothing !? - When I hit single step the code runs again fine for a while again.
I have tried to insert a "ON ERROR" but then my list doesn't contain all emails.

A: I'm baring my code to you :)
Change
Dim olItem As Outlook.MailItem
to
Dim olItem As Object
Not all the folder items will be mailitems, so avoid dimensioning your olItem variable in this manner. This change worked fine on my machine, while originally I had the same error you did

redpajama_set_name: RedPajamaStackExchange


text:
Q: Difference between handling missing and null values I have a dataset with a variable indicating how many days has passed (within a limited period of time) till a certain event happens.
Some of the records have null values as that event never happened to them (within that period of time).
When dealing with missing values, sometimes we use imputation with some algorithm or mean, median, etc. In dealing with this kind of null values, however, my intuition is that we should replace those null values with a huge number and use those records in modeling bec those null values provide information too.
Is my intuition correct?


text:
Q: Why installation is failed Installation did not succeed.
The application could not be installed: INSTALL_PARSE_FAILED_MANIFEST_MALFORMED
Installation failed due to: 'null'
Session 'app': Installation did not succeed.
                The application could not be installed: INSTALL_PARSE_FAILED_MANIFEST_MALFORMED
                Retry

A: Check following things in manifest file.
Check your Activity name in manifest file.
or the Package name in main activity/class
<activity android:name="MainActivity"></activity>

Check permission tags in manifest tag in manifest file or package name should not contain any capital letters.
More information can found here.


text:
Q: Test 2 stings for same words (C) i am working on algorithm, that would compare two sentences and find if they are made of same words.
Basically the input of this function are 2 strings, i cut them by " " and each word put in array. So i have something like this:
sent1[0]="one"
sent1[1]="two"
sent1[2]="three"
sent1[3]="four"

sent2[0]="four"
sent2[1]="two"
sent2[2]="one"
sent2[3]="three"

My algoritm works that for each word from sent1 it compares each word in sent2.If the sentences are equal it return 1 , otherwise it return 0;
//n = max index of sent1 and m is max index of sent2

int equal =0;
for (i = 0; i < (n); i++){
     for (x = 0; x < (m); x++){
            if(strcmp(sent1[i],sent2[x])==0){
                equal =1;
            }
     }
     if(equal==0){
         return 0;
     }
     equal=0;
}

return 1;

Problem of this algoritm is that it is very uneffective and slow, in order to make it faster it would be best to somehow delete index of array i already found equal word so every time i do new search it would search smaller array.Problem is that i dont know how to implement this in C because my every try ended with memory problems.
Thank you for any help.

A: In C language you cannot delete an element from its array, because an C array a contiguous block of memory.
But you can shift left the elements after you "delete" an item.
However an another suggestion about your code:
When the 'strcmp' function success (found equal) then you no need continue the actual loop, you can terminate that with 'break' command.
int equal =0;
for (i = 0; i < (n); i++){
     for (x = 0; x < (m); x++){
            if(strcmp(sent1[i],sent2[x])==0){
                equal =1;
                break;
            }
     }
     if(equal==0){
         return 0;
     }
     equal=0;
}

return 1;


text:
Q: From a function, how to get details about the module which actually called this function? In a general-purpose function, I would like to get informations about the module which calls this function (especially the base directory, which can itself be retrieved inside a module with path.dirname(module.filename)).
What I tried
For now, the only way I found to do it is to add module as a parameter for the function:
lib/my-lib.js:
const path = require('path');

exports.print_calling_module_path = function(calling_module) {
    console.log(path.dirname(calling_module.filename));
}

main.js:
const my_lib = require('./lib/my-lib.js');

console.log('Here is the path of this actual module:');
my_lib.print_calling_module_path(module);

... but it forces to use an extra parameter, which pollutes the argument list of functions with a (possibly?) deductible information.
What I'm looking for
For example:
lib/my-lib.js:
const path = require('path');

exports.print_calling_module_path = function(/* no extra argument */) {
    let calling_module = .... ;  // <== How to get this ??
    console.log(path.dirname(calling_module.filename));
}

main.js:
const my_lib = require('./lib/my-lib.js');

console.log('Here is the path of this actual module:');
my_lib.print_calling_module_path(/* no extra argument */);

Inside the print_calling_module_path() function, how can I get the calling module object, without passing it as a parameter? Maybe something dealing with the stack trace?

A: Check out documentation https://nodejs.org/api/modules.html#modules_the_module_object
They mention require.main and require.parent properties.
If it will not work for you, then use a.p's comment about using new Error().stack

A: I finally use new Error().stack as a.p suggested; here the final code, following the example in the question:
lib/my-lib.js:
function unique_filter(value, index, self) {
    return self.indexOf(value) === index;
}

function get_module_stack() {
    return new Error().stack.split(/\n/)
        .map(line => line.match(/\(([^:\)]*)/))  // Match lines with filenames
        .filter(match => match !== null)         // Remove null matches
        .map(match => match[1])                  // Map to the the actual filenames
        .filter(unique_filter)                   // Make filenames unique
}

exports.print_calling_module_path = function()
{
    console.log(get_module_stack()[1]);
}

However I'm not sure if this method is reliable enough to use it for production.
Any comment about it will be welcome.


text:
Q: Vba if function in formula I would like to use if function in vba with loop, so a i have a code like below
Worksheets("Teszt_dec").Cells(i, j + oszlop_number + 5).Formula = "=IIf(Teszt!" & Worksheets("Teszt_dec").Cells(i, j + oszlop_number + 5).address(False, False) & "<$F22,1,0)"

and i got these message:

(that means  #name error just in hungarian)
And if i select the cells, and press enter the error message suddenly disappear and works fine....
So anyone have any idea how can i solve this problem?

A: Iif is a VBA function. In your case, you are in need of an Excel formula, because you are calling like this:
Worksheets("Teszt_dec").Cells(i, j + oszlop_number + 5).Formula
The Excel formula is =IF.
Thus try with Cells(1,1).Formula = "=IF(condition,true,false)"


text:
Q: php ajax auto login without form action php ajax auto login works well in form action, but is it possible to execute without form action?
$email = 'xxx@gmail.com';
$password = 'password';

<script>
    var user = <?php $email; ?>;
    var pass = <?php $password; ?>;
    console.log(email=' + user + ', password=' + pass);
    $.ajax({
        url: 'http://www.example.com/login',
        type: 'POST',
        data: JSON.stringify({ email: user, password: pass }),
        success: function(data, status) {
            // do something after login
            console.log('success');
        },
        error: function() {
            console.log('error');
        }
    });

    return false;

    </script>

A: You should use GET method instead.
$email = 'xxx@gmail.com';
$password = 'password';
<script>
var user = <?php $email; ?>;
var pass = <?php $password; ?>;
$.ajax({
    url: 'http://www.example.com/login',
    type: 'GET', //send it through get method
    data: {
    email: user,
    password: pass
    },
    success: function(response) {
    //Do Something
    },
    error: function(xhr) {
    //Do Something to handle error
    }
});
</script>

Then check in your login page if email and password parameters have been set by GET or POST methods.
<?php

if (isset($_GET['email']) && isset($_GET['password']) || isset($_POST['email']) && isset($_POST['password'])){
// check your database and take actions.
}else{
// do nothing and show the post from again.
}

?>

A: Following code may work on page load if the username and password is auto-filled.
I hope this may help you.
<script>

 $(document).ready(function(){

    var user = $('[name="username"]').val();
    var pass = $('[name="password"]').val();

    if(user !== '' && pass!== ''){

        $.ajax({
            url: 'http://www.YourUrl.com/login',
            type: 'POST',
            data: {
                email: user,
                password: pass
            },
            success: function(response) {
                   //When successfully logged in
            },
            error: function() {
                  //If error on server side script
            }
        });

      }

   });

As here we have created POST request, you need to handle is by $_POST server side.


text:
Q: UISearchBar issue in displaying search result In my app I have 3 NSMutableArrays namely empJsonArray searchArray and nameArray
empJsonArray is populated using JSON.
 nameArray is populated with valueForKey:@"Name" from empJsonArray and searchArray is initially populated with contents of empJsonArray.
the data is displayed in a UITableView
Now I am using UISearchBar for searching through my UITableView and display the relevant data. UISearchBar is working fine but the problem arises when the search data is displayed.
suppose I have 2 names that contain letter "T" when I search for "T" UITableView display 2 items but form the top of the nameArray (i.e. index 0 and 1) not the items that contain "T".
I am also using NSSortDescriptor.
Here's the code:-
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYCell"];
if (!cell) {
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MYCell"];
}
sorter = [[NSSortDescriptor alloc]initWithKey:@"Name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
sortedArray = [self.empJsonArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sorter]];
cell.textLabel.text = [[sortedArray objectAtIndex:indexPath.row]objectForKey:@"Name"];
nameArray = [[NSMutableArray alloc]initWithArray:[sortedArray valueForKey:@"Name"]];

return cell;

}

Search Method:
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {

if ([searchText length]==0) {
    [searchArray removeAllObjects];
    [searchArray addObjectsFromArray:nameArray];

}
else {
    [searchArray removeAllObjects];
    for (NSString *string in nameArray) {
        NSRange r = [string rangeOfString:searchText options:NSCaseInsensitiveSearch];
        if (r.location != NSNotFound) {
            [searchArray addObject:string];
        }
    }
}
[empTable reloadData];

}

you can see the screenshots here
1.Before search
2.After Search

A: Problem solved.
Instead of displaying the search result in cell
cell.textLabel.text = [[searchArray objectAtIndex:indexPath.row]

I was displaying
cell.textLabel.text = [[sortedArray objectAtIndex:indexPath.row]objectForKey:@"Name"];


text:
Q: query returning wrong result for like'%' like % not working . the query returning result for full string match not the substring match.
 Booking::whereHas('agent', function ($query) use ($agent_name) {
            $query->where('first_name', 'like', "'%".$agent_name."%'");
    })->select('id','agent_id','file_number','title','first_name','last_name','ref_number','pax_adult','pax_child')->with(array('agent'=>function($query){
        $query->select('id','first_name','last_name');
    }))->get();

A: Update your query to:
$query->where('first_name', 'like', "%".$agent_name."%");

You had a extra ' at the start and end of the LIKE.


text:
Q: Vue.js catch json response I have some problems with catching message with my Vue app. I'm using Vuexy admin template and in one file is defined how they return error message.
So Code looks like this:
module.exports = function settle(resolve, reject, response) {
  var validateStatus = response.config.validateStatus;
  if (!validateStatus || validateStatus(response.status)) {
    resolve(response);
  } else {
    console.log(response.data)
    reject(createError(
      'Request failed with status code ' + response.status,
      response.config,
      null,
      response.request,
      response
    ));
  }
};

And It's returning that message with status code, but as you see I'm trying to console.log response.data, and I'm getting info that I need. Console log looks like
{"response":false,"status":400,"message":"Provided details are not correct!"}

But when I try to catch message like response.data.message I'm receiving that message is undefined, any ideas why?
!=
BTW: response.status is getting status from HTTP response, not from json status code!


text:
Q: SQL 2000 Logs disk drive bust We;ve had a disk go on our SQL server (2000) that contained all the log files, so we replaced the drive (no raid config so data lost) and now when trying to connect to Enterprise manager we cant, just getting the general connection failed message. The service seems to start ok?
Any ideas? I didn't think the log files going would screw it up this much?
Thanks,
John

A: Are you sure the service started ok? How are you checking?
If the databases were not cleanly shutdown then SQL Server won't automatically recreate log files as there is information in the missing log files that is required to properly run crash recovery on those databases. (See my article in TechNet Magazine Understanding Logging and Recovery in SQL Server).
Do you have backups of the databases? If not you may be looking at having to perform an undocumented and unsupported transaction log rebuild on some of the databases to make them accessible again - which usually leads to corruption (because active transactions didn't get a chance to roll-back properly), which you fix using DBCC CHECKDB.
Thanks

A: I think there is enough control with the query analyzer to log in and re-tell the database where the log files are.
Otherwise, you may have to cycle the SQL server service to re-create the log files and start writing to them again.


text:
Q: Qt: c++/carbon OSX - Getting Application Icon from Process ID On my C++ application, I am using carbon for some mac platform specific work.
I have: Mac Process ID for a running application.
I need: a Qt image object (can be pixmap, QImage, QIcon) for the running application belonging to that Process ID.
Any pointers?

A: GetProcessForPID() will get you the ProcessSerialNumber of the pid. ProcessInformationCopyDictionary() will then get you a CFDictionary containing the path to the application bundle.
Use QFileIconProvider to get the icon from the path.


text:
Q: Error when including struct in a header file C++ "cannot overload functions distinguished by return type alone" I have the following structures that work fine when included in a single main.cpp file. But, when I try to move things to a header.h I get an error.
An example, main.cpp with full definitions (before moved to header.h file):
using namespace std;

    static const int nx = 10;
    static const int ny = 10;

struct cplx_buffer
{
  fftw_complex* a;
  int rows;
  int cols;

  fftw_complex& operator()(int i, int j) const { return a[i * cols + j]; }
};
cplx_buffer my_fftw_allocate_cplx(int x, int y) { return cplx_buffer{ fftw_alloc_complex(x * y), x, y }; }
void print_matrix(cplx_buffer const& m)
{
  std::cout << std::fixed << std::setprecision(2);

  for (int i = 0; i < m.rows; i++)
  {
    for (int j = 0; j < m.cols; j++)
    {
      std::cout << std::setw(16) << std::complex<double> { m(i, j)[0], m(i, j)[1] };
    }
    std::cout << '\n';
  }
  std::cout << '\n';
}
int main(){

cplx_buffer outY = my_fftw_allocate_cplx((ny+1), nx);

   //stuff

}

Then my attempt of dividing things to header.h, header.cpp, and main.cpp files as the following:
header.h
using namespace std;
static const int nx = 10;
static const int ny = 10;

struct cplx_buffer
{
  fftw_complex* a;
  int rows;
  int cols;

  fftw_complex& operator()(int i, int j) const { return a[i * cols + j]; }
};
void print_matrix(cplx_buffer const& m);

cplx_buffer my_fftw_allocate_cplx(int x, int y);

header.cpp looks like:
#include "header.h"
using namespace std;

struct cplx_buffer
{
  fftw_complex* a;
  int rows;
  int cols;

  fftw_complex& operator()(int i, int j) const { return a[i * cols + j]; }
};
cplx_buffer my_fftw_allocate_cplx(int x, int y) { return cplx_buffer{ fftw_alloc_complex(x * y), x, y }; } //ERROR

void print_matrix(cplx_buffer const& m)
{
  std::cout << std::fixed << std::setprecision(2);
  for (int i = 0; i < m.rows; i++)
  {
    for (int j = 0; j < m.cols; j++)
    {
      std::cout << std::setw(16) << std::complex<double> { m(i, j)[0], m(i, j)[1] };
    }
    std::cout << '\n';
  }
  std::cout << '\n';
}

The Main.cpp is:
#include "header.h"
using namespace std;

int main(){
cplx_buffer outY = my_fftw_allocate_cplx((ny+1), nx);

   //stuff

}

The error comes from the header.cpp file in line:
cplx_buffer my_fftw_allocate_cplx(int x, int y) { return cplx_buffer{ fftw_alloc_complex(x * y), x, y }; } //ERROR

The full error message:
cannot overload functions distinguished by return type alone

A: As someone in the comments suggested, the solution was to only define my struct in the header.h file and not to redefine it again in the header.cpp file.


text:
Q: Is the usage of the participle clause correct, here? I read in Advanced Grammer In Use that sometimes the participle clause has its own subject, like:

The collection of vases is priceless, some being over two thousand years old.

According to the above rule, I want to write the same sentence for this snapshot, https://ieltsmaterial.com/ielts-academic-writing-task-1-map-band-9-model-sample/, like below. Is the below sentence correct?

The evergreen trees on the west of the district do not undergo a change in their numbers, some grown on the east of the island demolishing,

A: I am not sure that I fully agree with FumbleFingers' assertion that

The collection of vases is priceless, some being over 2000 years old

is extremely unnatural. I agree I'd prefer as a matter of style

The collection of vases, some [being] over 2000 years old, is priceless.

But the key point is that "some being over 2000 years old" is a modifier of "vases" that explains "priceless. I am not sure that it is helpful to think of "some" as an independent subject in this case, but I will not argue about what people call things.
Leaving aside the fact that "demolishing" makes no sense in this context, your variant does not work because you are not modifying "trees on the west" with "grown," but introducing a whole new, contrasting subject. Moreover, if you meant "decreasing," "some" does not make sense if you are talking about the entire population.

The population of evergreens growing in the west of the district is stable, but that growing in the east is declining

is grammatical. And I'd prefer to say that "that" is the subject of "is" and "growing" modifies that subject. But let's not argue about names.


text:
Q: wllvm error: C compiler cannot create executables I'm trying to build the LLVM bitcode of libosip2-4.1.0 with wllvm.
I exported the following variables:
export LLVM_COMPILER=/home/oren/GIT/LatestKlee/llvm/Release/bin/clang
export LLVM_COMPILER_PATH=/home/oren/GIT/LatestKlee/llvm/Release/bin/

Then created a dedicated build library, and ran configure from there:
CC=wllvm ../libosip2-4.1.0/configure

However, configure script complains that wllvm cannot create executables:

configure: error: C compiler cannot create executables

When I run it without CC=wllvm (usual compilation with gcc) everything works fine. What should I do? Thanks!

A: It turns out that:
export LLVM_COMPILER=clang (works fine)

But not with an absolute path:
export LLVM_COMPILER=/home/oren/GIT/LatestKlee/llvm/Release/bin/clang (doesn't work)

Here is my final script that works fine and builds an llvm bitcode for libosip2-4.1.0:
wget https://ftp.gnu.org/gnu/osip/libosip2-4.1.0.tar.gz
tar xf libosip2-4.1.0.tar.gz

mkdir build
cd build
CC=wllvm LLVM_COMPILER=clang ../libosip2-4.1.0/configure --enable-test --disable-shared
LLVM_COMPILER=clang make -j

cd ./src/test
extract-bc ./torture_test
file ./torture_test.bc

And the desired terminal output that proves mission accomplished:
./torture_test.bc: LLVM IR bitcode


text:
Q: Spark 2.1 - Error While instantiating HiveSessionState With a fresh install of Spark 2.1, I am getting an error when executing the pyspark command.
Traceback (most recent call last):
File "/usr/local/spark/python/pyspark/shell.py", line 43, in <module>
spark = SparkSession.builder\
File "/usr/local/spark/python/pyspark/sql/session.py", line 179, in getOrCreate
session._jsparkSession.sessionState().conf().setConfString(key, value)
File "/usr/local/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1133, in __call__
File "/usr/local/spark/python/pyspark/sql/utils.py", line 79, in deco
raise IllegalArgumentException(s.split(': ', 1)[1], stackTrace)
pyspark.sql.utils.IllegalArgumentException: u"Error while instantiating 'org.apache.spark.sql.hive.HiveSessionState':"

I have Hadoop and Hive on the same machine.  Hive is configured to use MySQL for the metastore.  I did not get this error with Spark 2.0.2.
Can someone please point me in the right direction?

A: Spark 2.1.0 - When I run it with yarn client option - I don't see this issue, but yarn cluster mode gives "Error while instantiating 'org.apache.spark.sql.hive.HiveSessionState':".
Still looking for answer.

A: The issue for me was solved by disabling HADOOP_CONF_DIR environment variable. It was pointing to hadoop configuration directory and while starting pyspark shell, the variable caused spark to initiate hadoop cluster which wasn't initiated.
So if you have HADOOP_CONF_DIR variable enabled, then you have to start hadoop cluster started before using spark shells
Or you need to disable the variable.

A: I was getting same error in windows environment and Below trick worked for me.
in shell.py the spark session is defined with .enableHiveSupport()
 spark = SparkSession.builder\
            .enableHiveSupport()\
            .getOrCreate()

Remove hive support and redefine spark session as below:
spark = SparkSession.builder\
        .getOrCreate()

you can find shell.py in your spark installation folder.
for me it's in "C:\spark-2.1.1-bin-hadoop2.7\python\pyspark"
Hope this helps

A: I had the same problem. Some of the answers sudo chmod -R 777  /tmp/hive/, or to downgrade spark with hadoop to 2.6 didn't work for me.
I realized that what caused this problem for me is that I was doing SQL queries using the sqlContext instead of using the sparkSession.
sparkSession =SparkSession.builder.master("local[*]").appName("appName").config("spark.sql.warehouse.dir", "./spark-warehouse").getOrCreate()
sqlCtx.registerDataFrameAsTable(..)
df = sparkSession.sql("SELECT ...")

this perfectly works for me now.

A: You are missing the spark-hive jar.
For example, if you are running on Scala 2.11, with Spark 2.1, you can use this jar.
https://mvnrepository.com/artifact/org.apache.spark/spark-hive_2.11/2.1.0

A: I saw this error on a new (2018) Mac, which came with Java 10.  The fix was to set JAVA_HOME to Java 8:
export JAVA_HOME=`usr/libexec/java_home -v 1.8`

A: I too was struggling in cluster mode. Added hive-site.xml from sparkconf directory, if you have hdp cluster then it should be at /usr/hdp/current/spark2-client/conf. Its working for me.

A: I was getting this error trying to run pyspark and spark-shell when my HDFS wasn't started.

A: I have removed   ".enableHiveSupport()\"  from shell.py file  and its working perfect
/*****Before********/
 spark = SparkSession.builder\
            .enableHiveSupport()\
            .getOrCreate()
/*****After********/
spark = SparkSession.builder\
        .getOrCreate()
/*************************/

A: Project location and file permissions would be issue. I have observed this error happening inspite of changes to my pom file.Then i changed the directory of my project to user directory where i have full permissions, this solved my issue.


text:
Q: Creating clojure atoms with a function I want to 1) create a list of symbols with the function below; then 2) create atoms with these symbols/names so that the atoms can be modified from other functions. This is the function to generate symbols/names:
(defn genVars [ dist ]
    (let [ nms (map str (range dist)) neigs (map #(apply str "neig" %) nms) ]
        (doseq [ v neigs ]
            (intern *ns* (symbol v) [ ] ))
     ))

If dist=3, then 3 symbols, neig0, ... neig2 are created each bound with an empty vector. If it is possible to functionally create atoms with these symbols so that they are accessible from other functions. Any help is much appreciated, even if there are other ways to accomplish this.

A: your function seems to be correct, just wrap the value in the intern call with atom call. Also I would rather use dotimes.
user>
(defn gen-atoms [amount prefix]
  (dotimes [i amount]
    (intern *ns* (symbol (str prefix i)) (atom []))))
#'user/gen-atoms
user> (gen-atoms 2 "x")
nil
user> x0
#atom[[] 0x30f1a7b]
user> x1
#atom[[] 0x2149efef]

A: The desire to generate names suggests you would be better served by a single map instead:
(def neighbours (atom (make-neighbours)))

Where the definition of make-neigbours might look something like this:
(defn make-neighbours []
  (into {} (for [i (range 10)]
             [(str "neig" i) {:age i}])))

Where the other namespace would look values up using something like:
(get-in @data/neighbours ["neig0" :age])

Idiomatic Clojure tends to avoid creating many named global vars, preferring instead to collocating state into one or a few vars governed by Clojure's concurrency primitives (atom/ref/agent). I encourage you to think about whether your problem can be solved with a single atom in this way instead of requiring defining multiple vars.
Having said that, if you really really need multiple atoms, consider storing them all in a single map var instead of creating many global vars. Personally, I have never encountered a situation where creating many atoms was better than a single big atom (so I would be interested to hear about situations where this would be important).
If you really really need many vars, be aware that defining vars inside a function is actually bad style (https://github.com/bbatsov/clojure-style-guide#dont-def-vars-inside-fns). With good reason too! The beauty of using functions and data comes from the purity of the functions. def inside a function is particularly nasty as it is not only a side-effect, but is an potentially execution flow altering side-effect.
Of course yes there is a way to achieve it, as another answer points out.
Where it comes to defining things that goes beyond def and defn, there is quite a lot of precedence to using macros. For example defroutes from compojure, defschema from Schema, deftest from clojure.test. Generally anything that is a convenience form for creating vars. You could use a macro solution to create defs for your atoms:
(defmacro defneighbours [n]
`(do
  ~@(for [sym (for [i (range n)]
              (symbol (str "neig" i)))]
    `(def ~sym (atom {}))))

In my opinion this is actually less offensive than a functional version, only because it is creating global defs. It is a little more obvious about creating global defs by using the regular def syntax. But I only bring it up as a strawman, because this is still bad.
The reason functions and data work best is because they compose.
There are tangible considerations that make a single atom governing state very convenient. You can iterate over all neighbors conveniently, you can add new ones dynamically. Also you can do things like concatenating neighbors with other neighbors etc. Basically there are lots of function/data abstractions that you lock yourself out of if you create many global vars.
This is the reason that macros are generally considered useful for syntactic tricks, but best avoided in favor of functions and data. And it has a real impact on the flexibility of your code. For example going back to compojure; the macro syntax is actually very limiting, and for that reason I prefer not to use defroutes at all.
In summary:

*

*Don't make lots of global defs if you can avoid it.

*Prefer 1 atom over many atoms where possible.

*Don't def inside a function.

*Macros are best avoided in favor of functions and data.

*Regardless of these guidelines, it is always good to explore what is possible, and I can't know your circumstances, so above all I hope you overcome your immediate problem and find Clojure a pleasant language to use.


text:
Q: How can I create Join table in MySQL database using hibernate in Java? I have two entity table called appointment and service. One appointment can be many services. Services already store in the database. We can newly add appointment. When add new appointment we selected added services from the drop down menu. Can add many services with one appointment. I need to store new record on appointment table and store relevant appointment id and services id's on another join table. Here attached image with my problem.

Already I tried many ways for do this. Bellow is one attempt.
Here is appointment class
@Entity
@Table(name="appointment")
public class Appointment extends AbstractPersistable<Long> implements Serializable {

    @OneToMany
    @JoinTable(name = "service_x_appointment", joinColumns = @JoinColumn(name = "appointment_id"),
            inverseJoinColumns = @JoinColumn(name = "beautyservice_id"))
    Set<BeautyService> beautyServices;

    private String type;
    private Date date;
    private String time;
    private String description;
    private int approval;

    @ManyToOne
    @JoinColumn(name = "userid")
    private User user;

    //getter and setter

}

Here is BeautyService class
@Entity
@Table(name="beauty_service")
public class BeautyService extends AbstractPersistable<Long>  {

    private String serviceName;
    private String timeDuration;
    private String amount;

    //getter and setter
}

Here is appointment controller class code,
@RequestMapping(value="/createAppointment",method = RequestMethod.POST)
    public String createAppointment(@RequestBody Appointment appointment){

        String response = null;
        response = appointmentService.save(appointment);
        return response;
    }

Here is appointment service class code
public String save(Appointment appointment) {
        appoinmentRepository.save(appointment);
        return "Appointment added successfully";
    }

Here is the my request body.
{
    "type":"Type02",
    "date":null,
    "time":"20:56",
    "description":"Hellow World",
    "approval":0,
    "user":{
        "id":2,
        "name" : "Alex",
        "telephone" : "0774466886",
        "age":21,
        "email": null
    },

    "beautyServices" : [

        {
            "id":1,
            "serviceName":"hair strate",
            "timeDuration" : "02 Hours",
            "amount" : 5000
        },
        {
            "id":2,
            "serviceName":"Eye brows",
            "timeDuration" : "02 Hours",
            "amount" : 5000
        },
        {

            "id":3,
            "serviceName":"Near cutting",
            "timeDuration" : "02 Hours",
            "amount" : 5000
        }
        ]

}

Why not record in the join table? Only appointment table.

A: You definitely shouldn't create Joined table entity as you mentioned as it's more the underlying database representation than the object oriented one.
You can achieve the join table by defining something like:
@Entity
@Table(name="appointment", schema="ADMIN")
public class Appointment implements Serializable {
//...

@OneToMany(mappedBy="appointment")
@JoinTable(name="Join_Table")
Set <ServiceT> service;

use relation mapping ManyToOne or OneToMany according to your table.
@Entity
@Table(name="service", schema="ADMIN")
public class ServiceT implements Serializable {
//...

@ManyToOne
Appointment appointment;

If you want to explicitely set your column name you can use

@JoinColumn

annotation.

A: You can do it in multiple ways. One has been specified @Aritra Paul, which is actually Bidirectional representation of OneToMany mapping.
I think you want to use UniDirectional representation. In that case you won't have to use mappedBy.
Just create your entities like below:
@Entity
@Table(name="appointment", schema="ADMIN")
public class Appointment implements Serializable {

     @OneToMany
     @JoinColumn(name = "appointment_id")
     @JoinTable(name = "service_appointment", joinColumns = @JoinColumn(name = "appointment_id"),
        inverseJoinColumns = @JoinColumn(name = "service_id"))
     Set<Service> services;
}

@Entity
public class Service {
       // Some Properties. No need to specify reference of Appointment here.

}

If you define your entities like that you will have a join table like this
+----------------+------------+------+-----+---------+-------+
| Field          | Type       | Null | Key | Default | Extra |
+----------------+------------+------+-----+---------+-------+
| appointment_id | bigint(20) | NO   | MUL | NULL    |       |
| service_id     | bigint(20) | NO   | PRI | NULL    |       |
+----------------+------------+------+-----+---------+-------+

Hope this helps!!

A: Can you please check if the beautyServices are actually being bound from the @RequestBody properly.
The property name is beautyServices while in Json it says "service".
In the Json it should say "beautyServices" instead of "service".
Also, check if the ids 1, 2, 3 already pre-exists on the beautyServices table.
If Not, if you want those to get inserted as well by saving appointment, you need to add CASCADETYPE.PERSIST.


text:
Q: Sublime Text 2 - plugin to show objects and variables? Is there any plugin or way for Sublime Text 2 to show you your objects, functions, and variables on the side?
I am working with PHP and Javascript. Thanks!

A: you don`t need a Plugin to do this.
Just press Control + R (on Win) to get a List of all available functions, objects and variables.
Hope it helps.

A: For the MAC users the command is CMD + R
This will open a popup with all the functions.

A: You have to vote here in order to see this functionality implemented in SublimeText : http://sublimetext.userecho.com/topic/19343-a-class-browser-integrated-with-minimap/
In the meantime, CTRL+R is the only alternative...


text:
Q: Upload images to Wordpress, include in slideshow I would like to upload images to a post or to a custom post type(s). Every image should then be wrapped with a li tag as shown below, in order to create a slideshow with the images. The whole post should be wrapped inside a div and a ul, also shown below.
To get an idea of how it looks look here. Right now I use posts and every post is coded manualy. There are four different slideshows but they have the same images. You will find navigation-arrows next to every picture.

Is it possible? What method should I use? Thanks.

A: Take a look at this link: http://johnford.is/programmatically-pull-attachments-from-wordpress-posts/
Essentially what you will need to do is to go through the attachments of each post then spit out the list. I'm not sure how you want to implement this though, you could put it in the post template or perhaps make a shortcode to use it.


text:
Q: Работа с двусвязным списком. Поиск максимального элемента Структура двусвязного списка:
struct list
{
    int inf;
    list* next;
    list* prev;
};

Функция с ошибкой:
int find_max(list* head, int size)
{
    list* ptr; //вспомогательный указатель
    ptr = head;
    int max = ptr->inf; //даем значение максимуму
    //по всему списку
    for (int i = 0; i < size; i++)
    {
        if (max < ptr->inf) max = ptr->inf;
        ptr->next;
    }
    return max;
}

Подскажите, пожалуйста, что сделано неправильно, так как всегда возвращается 1 элемент списка.

A: int find_max(list* head)
{
    list* ptr; //вспомогательный указатель
    ptr = head;
    int max = ptr->inf; //даем значение максимуму
    //по всему списку
    while (ptr)
    {
        if (max < ptr->inf) max = ptr->inf;
        ptr = ptr->next;
    }
    return max;
}


text:
Q: How do I download originals for a certain album in Photos when using "Optimize Device Storage" on iPad? I use Optimize iPad Storage in the Apple Photos app for my iPad, but sometimes I want an entire album offline to show someone. Is there a better way to do this than flicking through the photos one by one and waiting for them to download?
If this is not possible, I don't mind downloading all the photos. Selecting Download and Keep Originals doesn't seem to download the photos until I view them.

A: There are actually multiple levels of download. Even when you view an image, a device-optimized version is retrieved. Only when you Edit or Share a photo is it fully downloaded from iCloud (possibly when you zoom in all the way, also).
With that being said, you can't bulk-Edit; however, you can bulk-Share. Here are the steps that worked for me:

*

*Go into the album you wish to download locally.

*Tap Select.

*Tap Select All.

*Tap the Share icon in the bottom-left hand corner.

*Select Email.

*Wait for the Preparing progress indicator to complete. This may take a while depending on how large your album is and on the speed of your connection.

*When your email is ready, Cancel out of it.

Remember that these photos are eligible for purging if your device becomes low on storage.
Note: I tried this on a relatively small album (20 photos and videos). I don't know if your iPhone might crash attempting to share 500 photos at once.
If you choose to Download and Keep Originals, I believe your iPhone does that while your device is locked, on Wi-Fi, and has sufficient charge. It might help to have Photos as the foreground app when locking the iPhone.

A: I'm not sure this can be done directly, as Apple has created this mode in order to save space and not to leave Originals on the interested device in order to take a quick look at those even when Offline.
But there's a way around you may find very useful and suitable for your specific case, and not only.

iXpand flash drive
Earlier this year, San Disk and other brands have released a new type of flash drives, this flash drives are specifically designed to have a USB connector and a Lightning one.
This allows you to connect it directly either to your Computer or to your iDevice.
This way you can save all your important files, photos and videos in it and access them Offline, even while flying, via your iDevice, simply connecting the flash drive to it.

The San Disk flash drive is called iXpand, and it comes in different storage capacities, from 16GB up to 128GB.
Of course you're not restricted to purchase a San Disk one, even because I'm not promoting them in any way, but their flash drive's been the first one I've personally heard of.
Although, if you're interested to take a closer look at it, you can find further more details on their dedicated page here.
Otherwise, you can check out this 9to5mac article which features some of the best new lighting flash drives for iDevices.

A: As of Photos 3.0, you can right-click on an Album name under My Albums, and select Download Originals to this Mac.


text:
Q: What would I have to do to get WNA3100v1 drivers on Xubuntu 14.03? As I have no access to ethernet nor native WiFi, I used an external WiFi adapter. In this case, I need it for internet on my Xubuntu computer. What do I do to get it to work?

A: I suggest you download these files on to the USB drive: http://mirrors.kernel.org/ubuntu/pool/universe/n/ndiswrapper/ndiswrapper-common_1.59-2_all.deb and also, if yours is a 32-bit system: http://mirrors.kernel.org/ubuntu/pool/universe/n/ndiswrapper/ndiswrapper-utils-1.9_1.59-2_i386.deb Or 64-bit: http://mirrors.kernel.org/ubuntu/pool/universe/n/ndiswrapper/ndiswrapper-utils-1.9_1.59-2_amd64.deb
Confirm:
arch

A 32-bit system will report i686; 64-bit will report x86_64.
Also download the driver files at post #89 here: http://ubuntuforums.org/showthread.php?t=1695036&page=9
Transfer all from the USB to the desktop of the Ubuntu machine. Install the .deb files first:
cd ~/Desktop
sudo dpkg -i ndis*.deb

Note and post any errors.
Right-click the Broadcom file and select 'Extract Here.' Now back to the terminal:
cd ~/Desktop/Broadcom_bcm43xx_USB_32_64bit_v2_amended

If yours is a 32-bit system:
sudo ndiswrapper -i bcmn43xx32.inf

If yours is a 64-bit system:
sudo ndiswrapper -i bcmn43xx64.inf

In both cases:
sudo ndiswrapper -ma
sudo modprobe ndiswrapper

Your device should now be working.


text:
Q: Python regexp matching or tokenizing I have a dump of a data structure which i'm trying to convert into an XML. the structure has a number of nested structures within it. So i'm kind of lost on how to start because all the  regex expressions that i can think of will not work on nested expressions.
For example, let's say there is a structure dump like this:
abc = (
        bcd = (efg = 0, ghr = 5, lmn = 10),
        ghd = 5,
        zde = (dfs = 10, fge =20, dfg = (sdf = 3, ert = 5), juh = 0))

and i want to come out with an output like this:
< abc >
  < bcd >
    < efg >0< /efg >
    < ghr >5< /ghr >
    < lmn >10< /lmn >
  < /bcd >
.....
< /abc >

So what would be a good approach to this? tokenizing the expression, a clever regex or using a stack?

A: Use pyparsing.
$ cat parsing.py
from pyparsing import nestedExpr

abc = """(
        bcd = (efg = 0, ghr = 5, lmn 10),
        ghd = 5,
        zde = (dfs = 10, fge =20, dfg = (sdf = 3, ert = 5), juh = 0))"""
print nestedExpr().parseString(abc).asList()

$ python parsing.py
[['bcd', '=', ['efg', '=', '0,', 'ghr', '=', '5,', 'lmn', '10'], ',', 'ghd', '=', '5,', 'zde', '=', ['dfs', '=', '10,', 'fge', '=20,', 'dfg', '=', ['sdf', '=', '3,', 'ert', '=', '5'], ',', 'juh', '=', '0']]]

A: Here is an alternate answer that uses pyparsing more idiomatically. Because it provides a detailed grammar for what inputs may be seen and what results should be returned, parsed data is not "messy." Thus toXML() needn't work as hard nor do any real cleanup.
print "\n----- ORIGINAL -----\n"

dump = """
abc = (
        bcd = (efg = 0, ghr = 5, lmn 10),
        ghd = 5,
        zde = (dfs = 10, fge =20, dfg = (sdf = 3, ert = 5), juh = 0))
""".strip()

print dump

print "\n----- PARSED INTO LIST -----\n"

from pyparsing import Word, alphas, nums, Optional, Forward, delimitedList, Group, Suppress

def Syntax():
    """Define grammar and parser."""

    # building blocks
    name   = Word(alphas)
    number = Word(nums)
    _equals = Optional(Suppress('='))
    _lpar   = Suppress('(')
    _rpar   = Suppress(')')

    # larger constructs
    expr = Forward()
    value = number | Group( _lpar + delimitedList(expr) + _rpar )
    expr << name + _equals + value

    return expr

parsed = Syntax().parseString(dump)
print parsed

print "\n----- SERIALIZED INTO XML ----\n"

def toXML(part, level=0):

    xml = ""
    indent = "    " * level
    while part:
        tag     = part.pop(0)
        payload = part.pop(0)

        insides = payload if isinstance(payload, str) \
                          else "\n" + toXML(payload, level+1) + indent

        xml += "{indent}<{tag}>{insides}</{tag}>\n".format(**locals())

    return xml

print toXML(parsed)

The input and XML output is the same as my other answer. The data returned by parseString() is the only real change:
----- PARSED INTO LIST -----

['abc', ['bcd', ['efg', '0', 'ghr', '5', 'lmn', '10'], 'ghd', '5', 'zde',
['dfs', '10', 'fge', '20', 'dfg', ['sdf', '3', 'ert', '5'], 'juh', '0']]]

A: I don't think regexps is the best approach here, but for those curious it can be done like this:
def expr(m):
    out = []
    for item in m.group(1).split(','):
        a, b = map(str.strip, item.split('='))
        out.append('<%s>%s</%s>' % (a, b, a))
    return '\n'.join(out)

rr = r'\(([^()]*)\)'
while re.search(rr, data):
    data = re.sub(rr, expr, data)

Basically, we repeatedly replace lowermost parenthesis (no parens here) with chunks of xml until there's no more parenthesis. For simplicity, I also included the main expression in parenthesis, if this is not the case, just do data='(%s)' % data before parsing.

A: I like Igor Chubin's "use pyparsing" answer, because in general, regexps handle nested structures very poorly (though thg435's iterative replacement solution is a clever workaround).
But once pyparsing's done its thing, you then need a routine to walk the list and emit XML. It needs to be intelligent about the imperfections of pyparsing's results. For example, fge =20, doesn't yield the ['fge', '=', '20'] you'd like, but ['fge', '=20,']. Commas are sometimes also added in places that are unhelpful. Here's how I did it:
from pyparsing import nestedExpr

dump = """
abc = (
        bcd = (efg = 0, ghr = 5, lmn 10),
        ghd = 5,
        zde = (dfs = 10, fge =20, dfg = (sdf = 3, ert = 5), juh = 0))
"""

dump = dump.strip()

print "\n----- ORIGINAL -----\n"
print dump

wrapped = dump if dump.startswith('(') else "({})".format(dump)
parsed = nestedExpr().parseString(wrapped).asList()

print "\n----- PARSED INTO LIST -----\n"
print parsed

def toXML(part, level=0):

    def grab_tag():
        return part.pop(0).lstrip(",")

    def grab_payload():
        payload = part.pop(0)
        if isinstance(payload, str):
            payload = payload.lstrip("=").rstrip(",")
        return payload

    xml = ""
    indent = "    " * level
    while part:
        tag     = grab_tag() or grab_tag()
        payload = grab_payload() or grab_payload()
        # grab twice, possibly, if '=' or ',' is in the way of what you're grabbing

        insides = payload if isinstance(payload, str) \
                          else "\n" + toXML(payload, level+1) + indent

        xml += "{indent}<{tag}>{insides}</{tag}>\n".format(**locals())

    return xml

print "\n----- SERIALIZED INTO XML ----\n"
print toXML(parsed[0])

Resulting in:
----- ORIGINAL -----

abc = (
        bcd = (efg = 0, ghr = 5, lmn 10),
        ghd = 5,
        zde = (dfs = 10, fge =20, dfg = (sdf = 3, ert = 5), juh = 0))

----- PARSED INTO LIST -----

[['abc', '=', ['bcd', '=', ['efg', '=', '0,', 'ghr', '=', '5,', 'lmn', '10'], ',', 'ghd', '=', '5,', 'zde', '=', ['dfs', '=', '10,', 'fge', '=20,', 'dfg', '=', ['sdf', '=', '3,', 'ert', '=', '5'], ',', 'juh', '=', '0']]]]

----- SERIALIZED INTO XML ----

<abc>
    <bcd>
        <efg>0</efg>
        <ghr>5</ghr>
        <lmn>10</lmn>
    </bcd>
    <ghd>5</ghd>
    <zde>
        <dfs>10</dfs>
        <fge>20</fge>
        <dfg>
            <sdf>3</sdf>
            <ert>5</ert>
        </dfg>
        <juh>0</juh>
    </zde>
</abc>

A: You can use re module to parse nested expressions (though it is not recommended):
import re

def repl_flat(m):
    return "\n".join("<{0}>{1}</{0}>".format(*map(str.strip, s.partition('=')[::2]))
                     for s in m.group(1).split(','))

def eval_nested(expr):
    val, n = re.subn(r"\(([^)(]+)\)", repl_flat, expr)
    return val if n == 0 else eval_nested(val)

Example
print eval_nested("(%s)" % (data,))

Output
<abc><bcd><efg>0</efg>
<ghr>5</ghr>
<lmn>10</lmn></bcd>
<ghd>5</ghd>
<zde><dfs>10</dfs>
<fge>20</fge>
<dfg><sdf>3</sdf>
<ert>5</ert></dfg>
<juh>0</juh></zde></abc>


text:
Q: Single transaction for multiple steps (scheduled job t-sql) I wonder if it is possible to cover all the steps of a job with a single transaction. Like,
TRY (BEGIN TRAN; STEP1 ) CATCH(ROLLBACK)
TRY (STEP2) CATCH(ROLLBACK)
TRY (STEP3-last step) CATCH(ROLLBACK)COMMIT;

Thanks.

A: Not that I'm aware of; steps are atomic units of work in a job.  If you need to cover them all in a transaction, you should move all of the activities into a single step.


text:
Q: Odoo8 | my custom website theme isn't loading its GUI I'm trying to make a new theme for odoo-8 website.. By following these steps in odoo-theme-tutorial . when went through step of Extend the default header I didn't get the expected output. All I get is a page og text without applying neither the CSS effect nor the JS. I don't know what am I missing.. any help will be appreciated.
Here's my code:
in openerp file:
{
    # Theme information
    'name': "theme_businesscasual",

    'description': """
    """,

    'category': 'Theme',

    'version': '1.0',

    'depends': ['website', 'website_less'],

    # templates

    'data': [
        'views/layout.xml',
    ],

    'application': True
}

in layout.xml file:

<template id="custom_header" inherit_id="website.layout" name="Custom Header">

  <xpath expr="//div[@id='wrapwrap']/header" position="attributes">

    <attribute name="id">my_header</attribute>

  </xpath>

  <xpath expr="//div[@id='wrapwrap']/header/div" position="after">

        Welcome to our website!

  </xpath>

</template>

Here's a screenshot of what I get:


text:
Q: Mouse Drawing Application: Nothing shows up This is a word-for-word example straight out of the book Java How to Program by Paul and Harvey Deitel.
PaintPanel.java
// Using class MouseMotionAdapter
import java.awt.Point;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JPanel;

public class PaintPanel extends JPanel {
    private int pointCount = 0;
    // array of 10,000 java.awt.Point references
    private Point[] points = new Point[10000];
    // set up gui and register mouse event handler
    public PaintPanel() {
        addMouseMotionListener(new MouseMotionAdapter() {
            // store drag coordinates and repaint

            public void MouseDragged(MouseEvent e) {
                if (pointCount < points.length) {
                    points[pointCount] = e.getPoint();
                    pointCount++;
                    repaint();
                } // end if
            }
        }
        );
    }

    // draw ovals in a 4 x 4 bounding box at specified location on the window
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);  // clear drawing area
        g.setColor(Color.BLUE);
        // draw all points in the array
        for(int i = 0; i < pointCount; i++)
            g.fillOval(points[i].x, points[i].y, 4, 4);
    }
}

Driver program Painter.java
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Painter {
    public static void main(String[] args) {
        JFrame app = new JFrame("A Simple Paint Program");
        PaintPanel pp = new PaintPanel();
        app.add(pp, BorderLayout.CENTER);
        app.add(new JLabel("Drag the rat to draw"), BorderLayout.SOUTH);
        app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        app.setSize(400, 200);
        app.setVisible(true);
    }
}

When I run it, it shows the drawing panel but nothing happens when I try to draw on it with the mouse.  All code is copied verbatim from the book.  What gives?

A: Java is case sensitive.  It's mouseDragged, not MouseDragged.  This is why you should always use @Override on methods you "think" you're overriding, this way you get compile time protection.
Runnable example...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new PaintPanel());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class PaintPanel extends JPanel {
        private int pointCount = 0;
        // array of 10,000 java.awt.Point references
        private Point[] points = new Point[10000];
        // set up gui and register mouse event handler

        public PaintPanel() {
            addMouseMotionListener(new MouseMotionAdapter() {
                // store drag coordinates and repaint

                @Override
                public void mouseDragged(MouseEvent e) {
                    if (pointCount < points.length) {
                        points[pointCount] = e.getPoint();
                        pointCount++;
                        repaint();
                    } // end if
                }
            });
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 200);
        }

        // draw ovals in a 4 x 4 bounding box at specified location on the window
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);  // clear drawing area
            g.setColor(Color.BLUE);
            // draw all points in the array
            for (int i = 0; i < pointCount; i++) {
                g.fillOval(points[i].x, points[i].y, 4, 4);
            }
        }
    }
}


text:
Q: SQL Server Nested Select (with JOIN) issue I am attempting to understand how nesting works in SQL server, and have produced the following code...
SELECT(*)
FROM
(
    SELECT (*)
    FROM MPOG_Institutions JOIN AIMS_Patients
    ON MPOG_Institutions.MPOG_Institution_ID = AIMS_Patients.MPOG_Institution_ID
) AS a

My current understanding is that the inner SELECT, FROM, and JOIN statement produces a result set that is then used in the FROM statement of the outer SELECT statement.  However, when this code is run I get the following syntax error:
Msg 8156, Level 16, State 1, Line 1
The column 'MPOG_Institution_ID' was specified multiple times for 'a'.

I have read that these nested result sets need aliases, hence the "AS a", but then this error occurs.  Can anyone help me understand what is going on here?
Thank you!

A: That's because MPOG_Institution_ID is in both tables, and by doing SELECT * in the outermost query, you have selected the column twice.  Since you haven't an alias to any of the columns in the subquery, SQL doesn't know what to do with two columns named the same, hence the error.
Instead of doing SELECT *, you should specifically call out each column, and in the case of MPOG_Institution_ID, select it only once.


text:
Q: Peewee how select every n+ row? Hy!
How can I select every second or sixtieth row with peewee? For example (1st, 31st, 61st, 91st, ...)
I try with loop but it's very disgusting. Every loop I increase the offset.
I try the peewee.expression but unfortunately notworking:
TypeError: not all arguments converted during string formatting
data = GreDatasDev3.select().order_by(GreDatasDev3.idGreDatasDev.desc()).where(Expression(GreDatasDev3.idGreDatasDev, '%', 60) == 0).limit(168)
deviceDatasList = []
for i in data:
   deviceDatasList.append(
            {
            "idGreDatasDev" : i.idGreDatasDev,
            "time" : str(i.time),
            "panelNumber" : i.panelNumber,
            "battmV" : i.battmV,
            "battmA" : i.battmA,
            "battW" : i.battW,
            "panemV" : i.panemV,
            "panemA" : i.panemA,
            "paneW" : i.paneW,
            "loadmV" : i.loadmV,
            "loadmA" : i.loadmA,
            "loadW" : i.loadW,
            "battStatus" : i.battStatus,
            "paneStatus" : i.paneStatus,
            "loadStatus" : i.loadStatus,
            "percent" : round(100-((13800-i.battmV)/27), 1),
            "windStatus" : i.windStatus,
            "windMax" : i.windMax,
            "windDirection" : i.windDirection,
            "rainFall" : i.rainFall,
            "humidity" : i.humidity,
            "airPressure" : i.airPressure,
            "temperature" : i.temperature
            }
            )

But without .where tag it is working. Just with the last 168 row.
data = GreDatasDev3.select().order_by(GreDatasDev3.idGreDatasDev.desc()).limit(168)
        deviceDatasList = []
        for i in data:
            deviceDatasList.append(
            {
            "idGreDatasDev" : i.idGreDatasDev,
            "time" : str(i.time),
            ...
            }
            )

A: You can use the ROW_NUMBER window function. Details here.
For example:
# Subquery to fetch all users and their rownum (sorted by username)
subq = User.select(
    User,
    fn.ROW_NUMBER().over(order_by=[User.username]).alias('rownum'))

# Get every 6th user:
query = (User
         .select(subq.c.id, subq.c.username)
         .from_(subq)
         .where(Expression(subq.c.rownum, '%', 6) == 0))

for user in query:
    # ...

For this code to work, you need to:
# Manually import Expression to construct the modulo expression,
# since modulo is not supported out-of-the-box in peewee.
from peewee import Expression


text:
Q: Why do docker CLI commands default to controlling containers? I'm new to Docker, and one of the things I'm interested in WRT to it is what are the majority use-cases. For example, These commands seem to do the same thing:
docker container rm

and
docker rm

i.e. the CLI provides a shorthand means of controlling containers rather than images (the command docker image ls is also valid).
Why does docker choose to provide a short-hand means of working with containers rather than with images?

A: From my experience I work more with containers than with images. You create the image once but may create a container from this image multiple times.
I think this is similar to classes and objects. A image is just a blueprint for a container, same as a class is a blueprint for an object. You create multiple objects from a class but you write the class just once so in the end you will also execute more commands for containers than for images.
I think this is the reason why the commands are focused on the containers.


text:
Q: Change column width in SharePoint 2013 Content is disabled! I want to change column width, and I use this script like in answer:
Adjust column width in sharepoint 2013
It helps, but every time I click this site or refresh it, I've got attention message:

How can I do it more clever? Is there any other simply script?
I need to change width of this column:

Thank you

A: That alert is coming from http protocol and your site is being loaded securely using https protocol. That is why the browser is blocking the content loading of that jQuery library file. You need to always click on that alert button or else you can place that jQuery library in your Style Library folder and then change the absolute reference in your code.
As an alternative you can load jQuery library securely with following URL:
https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js

A: Try using local reference for JS instead of cdn reference in following line:
src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"

A: Since your are using OOB list page which is app part in SP2013 and whatever the script you added is in different web or app part, all calls are over cross domain calls for the respective page. So if you want to get rid of this situtaion you have to change all link address from http protocal to https protocal.
$(function () {
if (window.location.protocol == "https:") {
    $("a[href*='http']").each(function (i) {
        var nLink = $(this).attr('href').replace('http:', 'https:');
        $(this).attr('href', nLink);
    });
}
});

or simple make your src as "https"
use src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"

A: Best way to fix it is delete http or https this way:
src="//ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js


text:
Q: How I can delete python 3.4 if i use just anaconda python I have a specific problem with python. I have on my ubuntu  two versions python3.4 and python3.6(from anaconda). I want use just anaconda pythoncurrent version
But when i run script i have some problems with another python version
another version
How i can safe delete useless python 3.4.6?

A: sudo apt-get remove python3.4

anaconda should have set python3 as default python3.6 version

A: You should probably not delete Python3 from your system, even if you have Anaconda installed, since there might be system software that:

*

*was not tested with subsequent versions of Python;

*might struggle finding Python from Anaconda.

What you should do instead is configure your IDE / environment to run Python script with Anaconda, e.g. by setting your PATH variable to point to your anaconda/bin directory or similar.
If you are using PyCharm, as it seems from the screenshot, you could set up your project to run the Anaconda Python without modifying your other command-line settings.


text:
Q: Appium client can't connect to Appium server locally I'm using mac, version 10.14.6, Appium v 1.15 and Java 8.
I launch Appium as application and then trying to launch my autotests, but there is a fail when Java tries to create instance of AndroidDriver
driver = new AndroidDriver(url, desiredCapabilities);

look at the screenshot with capabilities

The stacktrace
Caused by: org.openqa.selenium.WebDriverException: Connection refused (Connection refused)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'build-mac', ip: 'fe80:0:0:0:182d:c3ec:3e3:65fd%en0', os.name: 'Mac OS X',         os.arch: 'x86_64', os.version: '10.14.6', java.version: '1.8.0_231'
Driver info: driver.version: SelenideDriver
at io.appium.java_client.remote.AppiumCommandExecutor.lambda$5(AppiumCommandExecutor.java:251)
at java.util.Optional.orElseGet(Optional.java:267)
at io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:250)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:41)
at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.execute(AndroidDriver.java:1)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:213)
at io.appium.java_client.AppiumDriver.startSession(AppiumDriver.java:323)
at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:131)
at io.appium.java_client.DefaultGenericMobileDriver.(DefaultGenericMobileDriver.java:37)
at io.appium.java_client.AppiumDriver.(AppiumDriver.java:86)
at io.appium.java_client.AppiumDriver.(AppiumDriver.java:96)
at io.appium.java_client.android.AndroidDriver.(AndroidDriver.java:94)
at com.whimstay.automation.core.drivers.DriverManager.createDriver(DriverManager.java:45)

I guess it's probably due to Mac security policy, because on Windows everything is okay.
What should I do to fix the issue?

A: Had to specify the URL like this http://localhost:4723


text:
Q: Glassfish Security Realms base on URL I'm working on an RESTFul API that need to authenticate users on different realms based on the URL called. For example, if you call /service1 you need to be authenticated on a JDBCRealm, but if you call /service2, you need to be authenticated on a LDAPRealm.
Furthermore, I'd like to be able to configure (database or config file) which url uses which realm. This configuration wouldn't require a redeployment of my war if possible.
Do you have any idea how I can achieve this?
I'm using Glassfish 3.1.2 with Jersey and Spring 3.0.5

Thank you, have a nice day!

--
Samuel Dionne

A: You can add a separate layer for it so that it forwards the request to the proper device per authentication.  Actually this is a good use case for the IBM DataPower device if you are a big enterprise, if not a simple proxy server can do the job for you.


text:
Q: OpenERP RML report with the fixed size table I have used default python tag for repeatRows and repatln.
But I want to add empty rows at the bottom to make my table big.
this is the code.

  <para style="terp_default_8">[[repeatIn(o.order_line,'line')]][["" for l in range(10), 'line']]</para>
  <blockTable colWidths="20.0,100.0,150.0,80.0,50.0,20.0,60.0,50.0" style="Table_Order_Pur_line_Content">

        <para style="terp_default_9"> </para>

        <para style="terp_default_9">[[ ', '.join(map(lambda x: x.name, line.taxes_id)) ]]</para>

        <para style="terp_default_9">[[line.name]]</para>

        <para style="terp_default_Right_9">[[ formatLang(line.product_qty ) ]]</para>

        <para style="terp_default_Right_9">[[ formatLang(line.price_unit,digits=get_digits(dp='Product Price') ) ]]</para>

        <para style="terp_default_Right_9"> </para>

        <para style="terp_default_Right_9"> </para>

        <para style="terp_default_Right_9">[[ formatLang(line.price_subtotal,digits=get_digits(dp='Account'), currency_obj=o.pricelist_id.currency_id ) ]] </para>

  </blockTable>

##


text:
Q: Registering More than one Custom Metric API in Kubernetes TL;DR Can I register multiple APIs to provide custom metrics in k8s?
We have a multi-tenanted cluster - with different deployments in different namespaces, and they each have their own monitoring solution (using Prometheus)
We want each namespace to be able to use the HPA to scale off of custom metrics from the Prometheus instance in their own namespace.
We have custom metrics configured using the Prometheus adapter (https://github.com/DirectXMan12/k8s-prometheus-adapter) in our dev environment and that works with the following deployed:

*

*Roles + Bindings

*Prometheus Adapter + Config + Service (in namespace)

*A apiservice.apiregistration.k8s.io that is named v1beta1.custom.metrics.k8s.io and points to the service in the namespace

The APIService doesn't get put in a namespace and is global - and the naming has to be v1beta1.custom.metrics.k8s.io which means we can only use a single prometheus for custom metrics - which breaks our usecase.
Any idea how to register more than one service as an API for custom_metrics? or another way to do this?

A: So I'm not sure this is the best answer - waiting for the community to respond before I say that - but it is definitely an answer.
You can't seem to register multiple services for a single API - so the answer is to aggregate the data into a single API.
Options for this include:

*

*Federated Prometheus = scraping the /federated endpoint of each Prometheus and using that to server the custom scaling metrics. (https://prometheus.io/docs/prometheus/latest/federation/)

*Thanos - (https://github.com/improbable-eng/thanos) Bit early days for production use maybe - so the squeamish may want to go for options one -but Thanos is giving me a unified querying layer over the top of every Prometheus, that I can attach the Adapter to. Pretty neat - nice project - worth checking out;


text:
Q: How would a test case test for an exception? For my code I have:
public void addContact(Contact contact) {
  if (contact == null) {
    throw new IllegalArgumentException("contact must not be null");
  }
  this.contacts.add(contact);
}

And for my test case I have:
@Test

public void testForAddEmptyContact() {
  Contact nullContact = null;
  assertThrows(IllegalArgumentException.class, () -> {
    testContactList.addContact(nullContact);
  });
}

When I run the code in program, the code after "assertThrows" is red.


text:
Q: angular, how to stop tracking on service objects I have a service where I store all my DTOs classes i map back to api calls.
When I use those service objects they are getting tracking all the way back to the service, so i cant renew them if i want to make another transaction.
here is the service
(function () {
    "use strict";

    var app = angular.module("app.bms");

    app.service("dtoObjects", function () {

        var state = {
            Id: "",
            Value: ""
        }

        var companyDto = {
            Id: "",
            Name: "",
            Address: "",
            Address2: "",
            City: "",
            State: state,
            Zip: "",
            Phone: "",
            contactName: ""
        }

        var departmentDto = {
            DepartmentID: "",
            DepartmentName: "",
            CompanyDto: companyDto,
            IsActive: false,
            States: [state]
        }

        var userDto = {
            UserId: "",
            FistName: "",
            LastName: "",
            Email: "",
            Phone: "",
            LoginName: "",
            Password: "",
            IsActive: "",
            Client: companyDto,
            Department: departmentDto
        }

        return {
            departmentDto: departmentDto,
            companyDto: companyDto,
            userDto: userDto
        }

    });
})();

Here is how I inject it.
function userInfoController($scope, userService, dtoObjects, ngTableParams, popUpService, modalService)

This is How I use it
var userDto = dtoObjects.userDto;
            popUpService.raisePopUp(addEditTplt, addEditCtrl, userDto, reloadTable);

            console.log(dtoObjects.userDto)

;
everything that i assigned to that object is now mapped it back to service.
Is it possible for angular to stop this deep watch on service?
Thank you!

A: You could wrap the DTO service in a function and use new to instantiate a new copy every time you need to reset. So your service would look like this:
(function() {
"use strict";
var app = angular.module("app.bms");
app.service("dtoObjects", function() {
    function dto() {
        return {
            companyDto: companyDto
            //...
        }
        var companyDto = {
            //...
        }
    }
    return dto;
});})();

And then you would use it like so:
var newDTO = new dtoObjects();
console.log(newDTO.companyDTO);

A: In general, part of the power of Angular is the fact that services are singletons, and therefore a single reference can be bound everywhere in your app.  Using DTOs in Angular tend to add large amounts of unnecessary complexity, since Angular shouldn't be concerned about transaction states on the server.
However, if you absolutely need this feature, you can use angular.copy() to make a copy of your DTO for use in your view.
//example with 1 argument
var userDto = angular.copy(dtoObjects.userDto);

//example update, using two arguments
angular.copy(userDto, dtoObjects.userDto);


text:
Q: How to set inline CSS of element to default using javascript? I have simple function in which I change the default styling of text when a checkbox is checked, and change the styling back to default when checkbox gets unchecked.
The terms.style = ""; should reset the style back to default, but for some reasons it doesn't, and I have absolutely no idea why. I know that the else scope is performed when checkbox gets unchecked, as I have tested it with manually entering different style.
const form = document.getElementById('form');
const checkBox = form.querySelector('input[name=termsCheckBox]');

checkBox.addEventListener('click', function(){
    const terms = document.getElementById('termsText');
    if (checkBox.checked){
        terms.style = "color: black; font-weight: normal";
    } else {
        terms.style = "";
    }
});//end of function

A: You can get inline CSS in style attribute of element using getAttribute() and store it in variable and on check/uncheck of checkbox insert and remove it from style attribute

var checkBox = document.querySelector('#form input[name=termsCheckBox]'),
    terms = document.getElementById('termsText'),
    style = terms.getAttribute('style');

checkBox.addEventListener('click', function(){
  if (checkBox.checked)
    terms.style.cssText = "color:black; font-weight:normal";
  else
    terms.style.cssText = style;
});
<form id="form">
  <input type="checkbox" name="termsCheckBox">
  <textarea id="termsText" style="color:red; font-weight:bold">termsText</textarea>
</form>

A: According to MDN:

Styles should not be set by assigning a string directly to the style
  property (as in elt.style = "color: blue;")

Correct way would be:
checkBox.addEventListener('click', function(){
    const terms = document.getElementById('termsText');

    if(checkBox.checked){
        terms.style.color = "black";
        terms.style.fontWeight = "normal";
    }else{
        terms.style.color = "";
        terms.style.fontWeight = "";
    }
});


text:
Q: Azure NSG rule to allow VM to access MS 365 Defender I have a VNET which restricts all access outbound using an NSG except for 1 specific port which is used for an app it hosts.
However I need a way to allow Defender to communicate with the MS 365 Defender portal so it can report in. I tried using a couple of the service tags (MS Cloud App security and ATP) but don't seem to work.
Is there an IP or set of IPs I need to allow out for it to communicate?

A: If it is the end point of the application you are protecting then:
MicrosoftDefenderForEndpoint
A full list of service tags is available here:
https://learn.microsoft.com/en-us/azure/virtual-network/service-tags-overview


text:
Q: How does an on hold question affect reputation? If I asked a question and someone vote for on hold, how does this affect my reputation? I have searched for quit a while. But I still cannot find a clear answer.

A: Putting a question on hold, or a question eventually becoming closed, doesn't directly affect your reputation.
The only things that will affect your reputation are direct interactions with the user; a part listing would be:

*

*Voting, up or down

*Bounties, either awarded or offered

*Serial voting

*Too many spam flags

It might seem like a question on hold is affecting reputation, but that may be the side effect of other users downvoting the question, in which case, it's strictly the downvotes causing the person to lose reputation.


text:
Q: Jquery Draggable + Bring to Front I have a window with a number of chat DIV's where a user to chat to different people.
Currently the chat DIV's can be open and moved around but I can't see to get the currently select DIV to set at the front. eg: when you mousedown on a DIV it comes into the foreground.
HTML:

CSS:
div.chatMessenger {
    position: absolute;
    top: 50px;
    left: 50px;
    width: 250px;
    height: 300px;
    background-color: white;
    z-index: 100;
    border: 1px solid black;
}

JQUERY:
    // JQUERY UI Draggable - Initialize
    $('div#'+memberID).draggable({
        containment: $('div#chatWrapper')
    });

    // JQUERY UI Draggable - Setting the Stack
    $(document).on('mousedown','div.chatMessenger', function() {
        alert('chat mouse down...');
        //var stack = $( ".selector" ).draggable( "option", "stack" );
        $(this).draggable( "option", "stack", ".products" );
    });

The alert triggers in the mousedown so this is finding the correct element.
I have looked at Draggable z-index and stack but I was unable to get either working.
There will be many chat DIV's open at the same time to the selected one needs to sit at the front.
thankyou.

A: This should help
$('div.chatMessenger').not(this).css('z-index', '100');
$(this).css('z-index', '1000');

inside on('mousedown') function.

A: For several draggables where you want to bring one to front and reset others to back:
$('.container').on('mousedown', function(event) {
    $('.container').css('z-index','1');
    $( this ).css('z-index','1000');
});

A: I figured out that the easiest implementation is to move the div in the dom to the last position. so if you dont have to care about the position in the dom this is the easiest way without using z-index.
i use this for positioning some sticky notes.
$("#chatWrapper").on('mousedown', '.chatMessenger', function() {
    $(this).appendTo("#chatWrapper");
});

A: Though there is an option - 'stack' existing while initiating draggables
like this -
$('.draggable').draggable({
    stack: ".draggable"
});

But it is not working properly, So I have wrote a small library dragToFront playing with z-index. Following is the plunkr link
https://embed.plnkr.co/mJqkxSJhf1Umg7r2oLQN/


text:
Q: Simple example of "Spike-and-Slab Prior" for Bayesian Inference I would really like to understand how Spike-and-Slab Priors work in relation to Linearized Models. Can somebody provide a toy example of a Spike-and-Slab Prior with a Bernoulli spike and a Gaussian slab?
Here's my generic Linear Model:
$$ y = \mathbf{\beta*x} + \epsilon $$ or written as
$$ y = \sum_{j=1}^{k}\beta_j*x_j + \epsilon $$
I understand in Bayesian Inference, one has a posterior distribution that
$$\mathbf{\theta} = [\beta_1, \beta_2, ..., \beta_j]$$
$$P(\theta|x) = \frac{P(x|\theta)*P(\theta)}{P(x)}$$
which is essentially Likelihood * Prior / Normalizer.
In this, each parameter (i.e. each $\beta_j$) has it's own distribution and I would like to fit the parameters ($\theta$) to the data ($x$) while the data is fixed and the parameters are random variables of their own distributions (btw, is that the same as $P(\theta_j)=P(x|\theta_j)*P(\theta_j)/P(x)$ with indicies?).
If any of this is incorrect, please correct me :) It would be greatly appreciated
My reference:
The paper I am reading uses Bayesian Model Averaging with a Spike-and-Slab Prior.  The Spike-and-Slab Prior uses "consists of a Bernoulli distribution that specifies whether or not a variable is selected as influential. The slab prior is a Gaussian distribution that models the effect sizes of the variables, conditional on their being chosen as influential" Shankar et al. BMC Bioinformatics (2015) 16:31 DOI 10.1186/s12859-015-0467-6.  To figure out what a Spike-and-Slab Prior was, so I can use this w/o any black-box R package, I checked out: https://www2.stat.duke.edu/courses/Fall05/sta395/joelucas1.pdf where the description of the algorithm is below.
My confusion:
I don't understand how this is related to Bernoulli and Gaussian distributions.  Is the $h_{0j}$ a random variable following Bernoulli distribution and $h_{1j}$ following Gaussian ? If $f$ has to be extremely large, does the value of it matter and why does their need to be a separate value for every index $f_j$?  I found this resource on the stats stackexchange (https://stats.stackexchange.com/questions/142818/is-a-spike-and-slab-prior-a-proper-prior) but I'm not sure what $F(x)$ is in the figure; it's definitely not a p.d.f. since it doesn't integrate to 1.
My apologies if this is long, but I've been looking up resources for over a week and it's explained a little differently everywhere I've looked; it's difficult to piece together the pieces w/o a toy example.


text:
Q: Retrieving first less than value in a joined table in MySQL I have the 3 following tables:

I want to get a table that consist of three columns which are:
order_id
last order status before contact time
status_description
So the desired output is highlighted in red in the order_status table
I managed to get all the order status before contact time but the required is only 1 for each order_id (I added  the column Timestamp for illustration):
SELECT o.order_id, o.order_status_id, m.status_description, o.Timestamp
FROM
    contact c
        JOIN
    order_status o ON o.order_id = c.order_id
        JOIN
    meta_status m ON o.order_status_id = m.order_status_id
    WHERE o.Timestamp < c.Contact_time
ORDER BY o.order_id;

A: You can use row_number()
select * from
(
SELECT o.order_id, o.order_status_id, m.status_description, o.Timestamp,row_number() over(partition by o.order_id order by o.Timestamp desc) as rn
FROM
    contact c
        JOIN
    order_status o ON o.order_id = c.order_id
       left JOIN
    meta_status m ON o.order_status_id = m.order_status_id
    where o.Timestamp < c.Contact_time
)A where rn=1


text:
Q: How does the HUD prioritize commands? Every now and then I want to reach the "Edit > Preferences" menu item in Firefox, and the HUD makes this very convenient.
ALT + "Edi" will suggest exactly that to me. Something that I find annoying however is that if I complete the work "Edit" instead, the HUD will switch to suggest "Network > Edit preferences" instead. While this is a perfectly valid match as well, it seems like an inconsistent behaviour to me.
Could someone explain in more detail how the matching works, so that I can make better use of the HUD?

A: HUD is capable of Fuzzy Matching and can learn what you usually do so it can prioritise the things you use often. It covers the focused app as well as system functionality.Source
So,in your case if you type alt and "Edi" and select the Firefox Preferences two or more times,then next time you type alt and "Edit" you should get Firefox Preferences as first option.
Also if you want to experiment with HUD,you can install command line tools for it.Command line tools are available through the package indicator-appmenu-tools
Source


text:
Q: How to convert a column from string to array in PySpark I have a dataframe converted from an inherited dataset which looks like the following:
data = [("[]","2000","M",False),
            ("[{'username':'aabb','points':'200','active':'true'}, {'username':'bbaa22','points':'0','active':'false'}]","1999","F",True),
            ("[{'username':'topuser','points':'855','active':'false'}]","1974","M",True),
            ("[]","2005","F",False),
            ("[{'username':'myprimary','points':'1050','active':'true'}, {'username':'mylurk','points':'100','active':'true'}, {'username':'closedlurk','points':'50','active':'false'}]","1992","M",True)
            ]

columns=["user","dob_year","gender","member"]
df=spark.createDataFrame(data,columns)

+--------------------+--------+------+------+
|                user|dob_year|gender|member|
+--------------------+--------+------+------+
|                  []|    2000|     M| false|
|[{'username':'aab...|    1999|     F|  true|
|[{'username':'top...|    1974|     M|  true|
|                  []|    2005|     F| false|
|[{'username':'myp...|    1992|     M|  true|
+--------------------+--------+------+------+

I need to extract some of the elements from the user column and I attempt to use the pyspark explode function.
from pyspark.sql.functions import explode

df2 = df.select(explode(df.user), df.dob_year)

When I attempt this, I'm met with the following error:

AnalysisException: cannot resolve 'explode(user)' due to data type mismatch: input to function explode should be array or map type, not string;

When I run df.printSchema(), I realize that the user column is string, rather than list as desired.
I also attempted to cast the strings in the column to arrays by creating a UDF
import pyspark.sql.functions as f

df2 = df.withColumn("user", str2list_udf(f.col("user"))).withColumn("user",df.user.cast(ArrayType(StringType())))

When I do that, I'm met with the following error:

AnalysisException: cannot resolve 'user' due to data type mismatch: cannot cast string to array;

How can the data in this column be cast or converted into an array so that the explode function can be leveraged and individual keys parsed out into their own columns (example: having individual columns for username, points and active)? If explode isn't the best method, is there another route I should follow?
If it's helpful, here is the UDF that I created:
def str2list(x):
  if x == '[]':
    return list()
  else:
    return list(x)

str2list_udf = udf(lambda x: str2list(x))

Thank you

A: Convert the stringified arrays into array of structs using from_json the explode the resulting array:
from pyspark.sql import functions as F
from pyspark.sql.types import StructField, ArrayType, StringType, StructType

user_schema = ArrayType(
    StructType([
        StructField("username", StringType(), True),
        StructField("points", StringType(), True),
        StructField("active", StringType(), True)
    ])
)

df1 = (df.withColumn("user", F.from_json("user", user_schema))
       .selectExpr("inline(user)", "dob_year", "gender", "member")
       )

df1.show()
#+----------+------+------+--------+------+------+
#|  username|points|active|dob_year|gender|member|
#+----------+------+------+--------+------+------+
#|      aabb|   200|  true|    1999|     F|  true|
#|    bbaa22|     0| false|    1999|     F|  true|
#|   topuser|   855| false|    1974|     M|  true|
#| myprimary|  1050|  true|    1992|     M|  true|
#|    mylurk|   100|  true|    1992|     M|  true|
#|closedlurk|    50| false|    1992|     M|  true|
#+----------+------+------+--------+------+------+


text: Q: Convolutions of Path Integrals of Gaussian Functions I was looking at a question on a physics forum (https://physics.stackexchange.com/questions/45955/splitting-light-into-colors-mathematical-expression-fourier-transforms) and I wanted a more mathematical perspective on it. How would such a convolution of a gaussian path integral as defined in arxiv.org/pdf/1110.2346 with a fourier transform be defined? Is such a thing even mathematically (or physically) meaningful? Please give me your opinions. Thanks in advance!


text:
Q: Unity3d C# - How to check if a button has been pressed, and then instantiate an object So for the past two days (no joke) I have been trying to figure out how to check if a button is pressed, and then if so, make it instantiate an object. I have tried multiple methods so far and maybe one of those methods were closer to getting where I wanted but for now I will just show what I have currently. Right now, the problem is me detecting if the button has even been clicked in the first place.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class Master : MonoBehaviour
{
    public Button storeButton;
    public Transform hands;
    public GameObject gun1;

    void OnEnable()
    {
        gun1 = GameObject.FindGameObjectWithTag("Weapon1");
        hands = GameObject.FindGameObjectWithTag("Player").transform;
        // storeButton.onClick.AddListener(MyFunction);//adds a listener for when you click the button
        storeButton.onClick.AddListener(() => MyFunction());
    }

    void MyFunction()
    {
        Debug.Log("YOUR PRESSED THE DAMN BUTTON");
        // Instantiate(gun1, hands.position, hands.rotation);
        GameObject.Instantiate(gun1, hands.position, hands.rotation);
    }
}

A: Add an EventSystem to your Scene.
Otherwise you cant click Buttons an other Stuff.
http://docs.unity3d.com/Manual/EventSystem.html


text:
Q: PHP Bcrypt move to Python3 I need to move original php auth verification to python3. I have code like this:
// hash from db
$hash = "$2y$14$00sMXcXPyTthEv9m5dszwuT8VUU6KK1HtCunemfutphrbCHZoIz0e";

// the hash is used as salt
$result = crypt($password, $hash);

//result should match the hash if pasword is correct
$result = "$2y$14$00sMXcXPyTthEv9m5dszwuT8VUU6KK1HtCunemfutphrbCHZoIz0e";

It is done with parameter cost = 14
What is the best lib to implement it in python3?
EDITED:
I used lib py-bcrypt.
>>> import bcrypt
>>> password = "ahoj"
>>> db_hash = "$2y$14$00sMXcXPyTthEv9m5dszwuT8VUU6KK1HtCunemfutphrbCHZoIz0e"
>>> computed_hash = bcrypt.hashpw(password, db_hash)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Invalid salt

Why is salt invalid?
In PHP it works:
password=ahoj
hash=$2y$14$00sMXcXPyTthEv9m5dszwuT8VUU6KK1HtCunemfutphrbCHZoIz0e
result=$2y$14$00sMXcXPyTthEv9m5dszwuT8VUU6KK1HtCunemfutphrbCHZoIz0e

What is different in python?

A: If you want to compare passwords, use the checkpw function instead of hashpw:
if bcrypt.checkpw(passsword, db_hash):
    print "It matches"
else:
    print "It does not match"

Salt is needed only when you generate a new hash:
hashed = bcrypt.hashpw(password, bcrypt.gensalt())

You can find more details in the README file.


text:
Q: Trouble scanning a Data Lake Gen 2 source in Purview I am using Azure Purview. I created an Azure Data Lake resource. I am trying to scan the source. When I try to scan the source the connection fails as can be seen from the image below:

I did try to use this link to figure out how to solve this:
https://learn.microsoft.com/en-gb/azure/purview/manage-credentials?wt.mc_id=mspurview_inproduct_scan_msiauth_csadai
But I haven't been able to. Any help would be greatly appreciated.

A: I needed to copy the 'Managed Identity Name' for the Purview account and add it a role assignment of 'Storage Blob Data Reader' for the ADLS Gen 2 Account. Here is a more detailed breakdown.
https://learn.microsoft.com/en-us/answers/questions/565738/error-3835-purview-failed-to-access-the-adls-gen2.html


text:
Q: Unable to connect to OpenShift from external Jenkins I followed the steps given here to connect from external Jenkins instance to openshift online broker. However when I give the OpenShift credentials, the login doesn't go through even though I seem to have the right credentials. A message "Could not request https://openshift.redhat.com/broker/rest/domains: The OpenShift Online (Next Gen) Developer Preview is here! We will not be accepting new users onto the OpenShift Online (v2) platform." is thrown. I was not able to find any relevant documentation to eliminate this error. Any help is appreciated. BTW I use version 2.46.1 of Jenkins in Windows 10. Any lead is appreciated.

A: are you using openshift v3 or v2?   v2 is taken down AFAIK


text:
Q: How to mock static methods with more than one argument I'm writing a test case to test a component that invokes a static method accepting 5 arguments. I want to know how I can do that.
Earlier I have been successful in mocking static method with 0 and 1 arguments. However when I mock a static method with more than 1 argument, it returns null. Following is a simplified version of what I'm trying to do. The static method has 2 arguments.
public interface VO {

}

public class A implements VO {
    private int value = 5;

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }
}

public class Factory {
    public static VO getObj(String a, String b) {
        return new A();
    }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest({com.csc.fsg.nba.vo.Factory.class})
public class APITest {

    @BeforeClass
    public static void runOnceBeforeClass() throws Exception {
        System.out.println("Executing runOnceBeforeClass()");
        A a = new A();
        a.setValue(3);
        PowerMockito.mockStatic(Factory.class);
        Mockito.when(Factory.getObj(Mockito.any(String.class), Mockito.any(String.class))).thenReturn(a);
    }

    @Test
    public void testA() throws Exception {
        VO vo = Factory.getObj("a", null);
        System.out.println(((A)vo).getValue());
    }

}

I'm expecting that sysout should print 3, however vo is null.

A: In this particular case the any(String.class) fails to match the null passed when exercising the test
//...

VO vo = Factory.getObj("a", null);

//...

Use anyString()
//...

when(Factory.getObj(anyString(), anyString())).thenReturn(a);