text:
Q: SubGit: Git hook to lock a svn file if non locked, or reject commit if locked by another user Context:
I'm working on a big UE4 project. Currently we're using SVN as our VCS, but I've always been a git developer and having a local repo, local branches, and stashes are things I'm not willing to loose.
So, I've started using SubGit to work on a git version of the repo, while subgit does the git to svn conversion. So far I love it, aside from the fact that I'm forced to use rebase instead of merge, everything else is like normal git.
EDIT 1: My subgit repo is bare local one, as I don't have access to the remote SVN repo. This means tools like svnadmin or svnlook don't work for me.
Question:
Now, my team works by locking the binary files they work on in SVN. I want an automatic way to join that workflow. So I thought about a pre-commit hook to check if the files I'm about to commit are locked. If not, then lock them immediately. If they are though, check if I'm the lock owner. If I'm not, abort the commit.
Does anyone have any clues of how to achieve something like this?

A: After a lot of research, trial and error finally got something that WORKS!!  I added all these comments so ppl can understand my logic, as I still believe it can be improved.
EDIT 1: created a gist to host the file, to keep track of any improvements made to it pre-commit gist
For instance, I'm accessing the remote repo once per file. When the round-trip is long that's quite inefficient if the commit contains several .uasset files. Instead, it would be cool to batch all files info request on a single svn info request. I don't know if that's possible.
Also, the way I'm grabbing the Lock owner username is too hacky, but at least it does the trick for my case. Couldn't succeed to grab a string from between two single quotes on the second grep. Instead, I'm matching the username pattern which of course only works in my scenario where all svn usernames used in my company are of the form name.lastname
### Parameters

# Change SVN_USER to the SVN username you configured in subgit
SVN_USER="Firstname.Lastname"
# Remote url. Should end with trunk/ or branches/ . Assumes same folder name on svn and git
SVN_REPO="https://url/path/to/remote/trunk/"
# Currently only checks locks for files with .uasset extension
GREP_FILE_PATTERN_TO_INSPECT="\.uasset$"
# Pattern to match usernames other than your own on the lock error msg
GREP_USERNAME_PATTERN="[[:alpha:]]\+\.[[:alpha:]]\+"

### Start of the hook

# Only to be used for the lock msg. Not necessary...
CURRENT_BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)
# leave as 0, used for aborting the commit if a non-owned lock is found
COMMIT_SHOULD_FAIL=0
# Array of relative file paths (to git project) from staged files that should be locked
FILES_TO_LOCK=$(git diff --cached --name-only | grep $GREP_FILE_PATTERN_TO_INSPECT)

for FILE in $FILES_TO_LOCK
do
    PATH_TO_FILE_IN_SVN=$SVN_REPO$FILE
    # Try to apply a lock. If the file is already locked, grab the lock owner's username
    # 2>&1 redirects stderr to stdout, to pipe the error msg into grep for parsing it
    # 1st grep would grab part of the error msg printed if the file is already locked
    # 2nd grep would grab the lock owner's username with format GREP_USERNAME_PATTERN
    LOCK_OWNER=$(svn lock $PATH_TO_FILE_IN_SVN -m "working on ${CURRENT_BRANCH_NAME}" 2>&1 \
        | grep -o "already locked by user .\+'" \
        | grep -o $GREP_USERNAME_PATTERN)
    if [ $LOCK_OWNER ] && [ $LOCK_OWNER != $SVN_USER ] # If someone else locked it
    then
      echo "Error: File ${FILE} locked by ${LOCK_OWNER}"
        COMMIT_SHOULD_FAIL=1
    fi
done

if [ $COMMIT_SHOULD_FAIL -eq 1 ] # If at least 1 file was locked by another user
then
  echo '--Commit ABORTED--'
  exit 1 # Exiting with exit-code 1 makes the entire commit process abort
fi

Super open to improvements! Please suggest them in the comments

A: Regarding locking, you can use "What is the best way to see what files are locked in Subversion?", meaning svnadmin lslocks which does list locked files and their owner. (also, locally, svn status --show-updates)
Compare it, in your pre-commit hook, to the list given by git diff --cached --name-status.
For any file not locked, a svn proplist -v would display its owner.


text:
Q: C++ "Too many initializers" Error while making an array of chars I'm new to C++. I know a lot of python but I'm extremely new to C++. I was creating an array of chars but I got this error- "Too many Initializers" in VSCode.
Please let me know how to fix it.
Here's the code
1 | class Board {
2 |     public:
3 |     char pos_list[9];
4 |
5 |     void reset_pos() {
6 |        pos_list[9] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '};
7 |     };
8 | };

I am getting this error in line 6.
Please help me :(

A: EDIT: My initial answer was not correct, please find the modified correct way to do what you are looking for:
You will not be able to use {'','',''} in order to assign empty values to all elements in the array in C++, you can only do that while initializing the array when you declare it. Also, it wouldn't be ideal because it would use hardcoding of ' ' across the entire length of the array. The better way to do this is to loop over the array and then set each element to empty like below:
void reset_pos() {
           int len = sizeof(pos_list)/sizeof(pos_list[0]);
           for(int i=0; i<len; i++){
               pos_list[i] = ' ';
           }
        };

redpajama_set_name: RedPajamaStackExchange


text:
Q: Saving current route in bottom navigation - Compose I have a NavigationBar and each of the items have their own separate navGraphs. One of the NavGraphs has a following scheme:
sealed class ShopDestination(val name: String) {
object Shop : ShopDestination("shop") {
    object Category: ShopDestination("${super.name}/category")
    class Listing(listingId: Long? = null) : ShopDestination("${super.name}/listing/${listingId ?: ("{" + ShopArguments.ListingId.name + "}")}")
    class Product(productId: Long? = null) : ShopDestination("${super.name}/${productId ?: ("{" + RouteArguments.ProductId.name + "}")}")
}

and here's the graph:
.shopNavGraph(navController: NavController) {
navigation(
    route = ShopDestination.Shop.name,
    startDestination = ShopDestination.Shop.Category.name
) {
    composable(ShopDestination.Shop.Category.name) {
        ShopScreen({ navController.navigate(ShopDestination.Shop.Listing(it).name) })
    }
    composable(
        route = ShopDestination.Shop.Listing().name,
        arguments = listOf(
            navArgument(ShopArguments.ListingId.name) {
                type = NavType.LongType
            }
        ),
    ) {
        ListingComposable(
            contract = hiltViewModel<ListingViewModel>(),
            goBack = { navController.popBackStack() },
            goToProduct = { navController.navigate(ShopDestination.Shop.Product(it).name) },
        )
    }

    composable(
        route = ShopDestination.Shop.Product().name, arguments = listOf(navArgument(
            RouteArguments.ProductId.name
        ) {
            type = NavType.LongType
        })
    ) {
        ProductScreen(
            { navController.popBackStack() },
            { navController.navigate(ShopDestination.Shop.Product(it).name) })
    }
}

When a user click on a different NavigationBarItem and then goes back the shopNavGraph starts from the startDestination. I would like the NavigationBar to save the backstack and once the user clicks back on it, start from where it left of (for example Product). How do I achieve that? Here's also the NavigationBar if it helps in any way:
 NavigationBar(containerColor = MaterialTheme.colorScheme.primary) {
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    val currentRoute = navBackStackEntry?.destination?.route ?: ""

    items.forEach {
        NavigationBarItem(
            colors = NavigationBarItemDefaults.colors(indicatorColor = Color.Transparent),
            icon = {
                Row(verticalAlignment = CenterVertically) {
                    Icon(
                        imageVector = it.icon,
                        contentDescription = it.name,
                        tint = MaterialTheme.colorScheme.onPrimary
                    )
                    Text(
                        text = stringResource(id = it.titleResId).uppercase(),
                        modifier = Modifier.padding(start = dimensionResource(id = R.dimen.margin_normal)),
                        color = MaterialTheme.colorScheme.onPrimary,
                        style = MaterialTheme.typography.labelMedium
                    )
                }
            },
            alwaysShowLabel = true,
            selected = currentRoute.contains(it.name),
            onClick = {
                navController.navigate(it.name)
            }


text:
Q: Rails 3 / Ruby: ActiveRecord Find method IN condition Array to Parameters single quote issue I created a method on a micropost model which takes an array of user_ids. In this method I use the following 'find' method to pull all posts for all of the users within the array.
find(:all, :conditions => ["user_id IN (?)", args.join(',')])

But when ActiveRecord generates the SQL for this query it surrounds the coma delimited list of Ids in single quotes. This causes the query to only pull posts for the first number within the single quotes instead of all the numbers.
SELECT `microposts`.* FROM `microposts` WHERE (user_id IN ('3,4,5')) ORDER BY microposts.created_at DESC

The query should look like this to work correctly but I can't figure out how to get Ruby to convert the Array to a coma delimited list without the quotes, I know it has to be something simple and I am just missing it and can't find anything on Google that fixes this. All the posts I have found use the same .join(',') method to concert the Array.
SELECT `microposts`.* FROM `microposts` WHERE (user_id IN (3,4,5)) ORDER BY microposts.created_at DESC

One more fact which migh assist you in figuring out my issue is the Array of ids which I am passing into the method is being built in the following manner. Not sure if this would affect things.
ids = Array.new
ids.push(current_user.id)
ids = ids + current_user.friends.map(&:id)
ids = ids + current_user.reverse_friends.map(&:id)

Thanks in advance to the one who can help me get back to work ;)

A: Answer updated (twice) to reflect Rails 3+ ActiveRecord syntax
Rails 3+
You can use the following syntax:
Post.where(user_id: [1,2,3])

And thus:
Post.where(user_id: args)

Rails 3 or Rails 4 (Original)
For completeness, the Rails 3 syntax would be:
Post.where("user_id IN (?)", [1,2,3]).to_a

If args is an Array, then:
Post.where("user_id IN (?)", args).to_a

Or, if args is an array of strings:
Post.where("user_id IN (?)", args.map(&:to_i)).to_a

The to_a is optional, but will return the results as an array.  Hope this helps.
Rails 2
You should be able to simply pass in an array as the parameter, as follows:
find(:all, :conditions => ["user_id IN (?)", [1,2,3] ] )

Thus, if args is an array of ids, you should simply call:
find(:all, :conditions => ["user_id IN (?)", args ] )

In case you have an issues with types, you can do:
find(:all, :conditions => ["user_id IN (?)", args.map { |v| v.to_i } ] )

and this will ensure each item in the array is an Integer.

A: In rails 3 and 4, you could also simply pass the array as an argument like so:
Post.where(:user_id => [1,2,3])

And that will give you the same result as
Post.where("user_id IN (?)", [1,2,3])


text:
Q: How to take a word after word in JavaScript? I have an input and I need to take the word after a word in JavaScript. I am trying to think how create a regexp to do this, but I'm not getting on the logic.
One example of user input:
input reg a,
input b,
input int p, f, g,
output logic c,
output k;

So, I have a word (input, output), that will be followed for a type (or suppressed) then a name of variable until get a ;. So I need to do a regexp where after the user finish to write the code, it returns to me the name of inputs and outputs. In the example, it should return something like a,b,p,f,g,c,k.
Please any ideas how to do this?

A: It does not need regex, you can solve it with javascript
var string = userInput.split(' ');
var inputOutput = string[0];
var wordAfter = string[1];

That's slightly verbose and will still work if you leave out the second line.

A: use this:
 var value_ = document.querySelector("textarea").value;
 var varArr = [];
 for(var i=0; i<value_.length; i++){
    if(value_.charAt(i)=="," || value_.charAt(i)==";" ){
      varArr.push(value_.charAt(i-1));
    }
 }

see this link : https://plnkr.co/edit/QOiakDJg4dR3BMTmGCRQ?p=preview


text:
Q: RO domain access I want to open RO access to specific group of domain users on linux server. Solution has to be universal i.e. work for new files, no necessity to constantly add/remove users etc
So far the best I can come up with is a script which checks the rights+S setgid.
Any other ideas?

A: You could use ACLs:
setfacl -R -m d:g:thegroup:rwx /your/dir
setfacl -R -m g:thegroup:rwx /your/dir

The first command sets the default ACLs (for new files) to rwx for thegroup recursively in /your/dir. The second command does the same for the currently existing files.


text:
Q: Flatten Array of Objects based on nested Array I have this Array of Objects that I would need to transform into a flat Array of Objects. It looks as follows.
const points = [
    {
        highlights: [
            {
                title: 'Title 1',
                description: 'Description 1',
                x: 111,
                y: 222,
            },
            {
                title: 'Title 2',
                description: 'Description 2',
                x: 111,
                y: 222,
            },
        ],
        width: 1108,
        height: 1528,
        relativePath: '/image_01.jpg',
    },
    {
        highlights: [
            {
                title: 'Title 3',
                description: 'Description 3',
                x: 199,
                y: 411,
            },
            {
                title: 'Title 4',
                description: 'Description 4',
                x: 213,
                y: 1132,
            },
        ],
        width: 1108,
        height: 1528,
        relativePath: '/image_02.jpg',
    },
];

I would like each points.highlights[x] to have its own index so the Array would look as such:
[
    {
        title: 'Title 1',
        description: 'Description 1',
        x: 111,
        y: 222,
        width: 1108,
        height: 1528,
        relativePath: '/image_01.jpg',
    },
    {
        title: 'Title 2',
        description: 'Description 2',
        x: 111,
        y: 222,
        width: 1108,
        height: 1528,
        relativePath: '/image_01.jpg',
    },
    {
        title: 'Title 3',
        description: 'Description 3',
        x: 111,
        y: 222,
        width: 1108,
        height: 1528,
        relativePath: '/image_02.jpg',
    },
    {
        title: 'Title 4',
        description: 'Description 4',
        x: 111,
        y: 222,
        width: 1108,
        height: 1528,
        relativePath: '/image_02.jpg',
    },
];

I believe flatMap is part of the solution but then I am unsure how exactly I would be able to retain the other properties (width, height, relativePath).
I appreciate the help!

A: Here's a solution using flatMap:
points.flatMap(point =>
    point.highlights.flatMap(obj => {
        let temp = { ... point, ... obj };
        delete temp["highlights"];
        return temp;
    })
);

A: simply:

const points =
  [ { highlights:
      [ { title: 'Title 1', description: 'Description 1', x: 111, y: 222 }
      , { title: 'Title 2', description: 'Description 2', x: 111, y: 222 }
      ]
    , width        : 1108
    , height       : 1528
    , relativePath : '/image_01.jpg'
    }
  , { highlights:
      [ { title: 'Title 3', description: 'Description 3', x: 199, y: 411  }
      , { title: 'Title 4', description: 'Description 4', x: 213, y: 1132 }
      ]
    , width        : 1108
    , height       : 1528
    , relativePath : '/image_02.jpg'
    }
  ]

const result = points.reduce((res,{highlights,...plus})=>
  {
  highlights.forEach(hl=> res.push({...hl,...plus}))
  return res
  }
  ,[])

console.log(result)


text:
Q: s3cmd - sync command and remote_copy copies different files? I used the s3cmd sync command to sync a directory from a server to a s3 bucket. However, after s3cmd has uploaded all the files, it now does a "remote copy" - why is that the case? Additionally I do see logs like this:
remote copy: 'media/image/0e/f8/67/hof_570_1920x1920@2x.jpg' -> 'media/image/32/75/e6/hof_570_1280x1280@2x.jpg'
remote copy: 'media/image/10/95/db/Suesslupinen_1100x1100@2x.jpg' -> 'media/image/25/8f/e2/Suesslupinen_550x550@2x.jpg'

So it copies a file to another location and renames the file? This should not be the case, should it?


text:
Q: google maps api marker zoom I enter the coordinates of antwerp in my JavaScript code to place a marker on the map , but when I test it in my browser it places a marker in the middle of the map and if I zoom in it becomes more accurate until the marker is at the right place ... what am I doing wrong ??
The marker is not at the right place when zoomed out but it is when I zoom in. thanks in advance!
function initialize() {
    var mapOptions = {
      center: new google.maps.LatLng(51.2239721,4.413785),
      zoom: 8
    };
    var map = new google.maps.Map(document.getElementById("map-canvas"),
        mapOptions);

        var myLatlng = new google.maps.LatLng(51.2239721,4.413785);
        var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title:"ap hogeschool"
});
  }

  google.maps.event.addDomListener(window, 'load', initialize);

A: You can use google map latlngBounds as the code below will do that. u may need to read this
here
var locBounds = new google.maps.LatLngBounds();
        locBounds.extend(LatLng1);
        locBounds.extend(latlng2);

        map.fitBounds(locBounds);


text:
Q: SQL - Select distinct record in one column based on criteria in another I understand there are similar questions but I haven't found one that discusses this yet...
Example Sales table. Need to return Name of individual who did not sell product type 'A' on 21-Feb-16
Name        Date            Product Type
John        21-Feb-16       A
John        21-Feb-16       B
Joe         21-Feb-16       D
Joe         21-Feb-16       B
Jane        21-Feb-16       A
Jane        21-Feb-16       D

Desired return:
Name
Joe

Need something more than just...
select
distinct Name
from Sales
where Name = 'Joe'

A: just read about Not in
select *
from Sales
where Name not in
(select name
from Sales
where Date='21-Feb-16'
and product_type='A')

A: If you have a table like SalesPerson; using not exists():
select Name
from SalesPerson sp
where not exists (
  select 1
  from Sales s
  where s.SalesPersonId = sp.SalesPersonId
    and s.ProductType = 'A'
    and s.date = '20160221'
  )

otherwise:
select distinct Name
from Sales s
where not exists (
  select 1
  from Sales i
  where s.Name = i.Name
    and i.ProductType = 'A'
    and i.date = '20160221'
  )

A: You could use the EXCEPT operator for this.
SELECT DISTINCT Name
FROM Sales
EXCEPT
SELECT Name
FROM Sales
WHERE ProductType = 'A' AND Date = '21-Feb-16'

A: You can use the NOT in and a subselect like the following. In practical way you retrieve all the sellers excluding the sellers who sold at least one product of type A
select distinct
    Name
from
    Sales
where
    Name not in (select distinct Name
                 from Sales
                 where Product_type = 'A' and date '21-feb-2016')

A: How about using:
select
Name
from Sales
where Name = 'Joe'
group by Name


text:
Q: CSS - Minus top value how to get rid of the gap below it
The three 'Spares Solutions' columns are in a container called relative. I have given it the properties below:
.relative {
    top: -10rem;
    position: relative;
}

I know that this is expected behaviour which is what you see in the screenshot.
You can also see that there is content below the three columns. This is where I get my problem.
I would like to know if there is a way to give something a minus value and get rid of the space where it expects to see the three columns.
one solution would be to give the content a minus 10 value. But I would like to avoid this due to the space then being under the content.
This is my current HTML:

SPARES SOLUTIONS

                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit amet ultrices lorem, eget malesuada nulla. Pellentesque vel mattis nunc. Fusce quis ultricies quam,
                    ut molestie ex. Nulla facilisi. Praesent id magna consequat, pulvinar ligula sit amet, maximus tellus.

                LEARN MORE

SPARES SOLUTIONS

                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit amet ultrices lorem, eget malesuada nulla. Pellentesque vel mattis nunc. Fusce quis ultricies quam,
                    ut molestie ex. Nulla facilisi. Praesent id magna consequat, pulvinar ligula sit amet, maximus tellus.

                LEARN MORE

SPARES SOLUTIONS

                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit amet ultrices lorem, eget malesuada nulla. Pellentesque vel mattis nunc. Fusce quis ultricies quam,
                    ut molestie ex. Nulla facilisi. Praesent id magna consequat, pulvinar ligula sit amet, maximus tellus.

                LEARN MORE

                    "Click Spares have saved us
                    thousands since we joined!!!",
                    really great service and they
                    know exactly how to deal with
                    tricky customers"

                    Product Retail Manager

WHY CLICK SPARES

                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit amet ultrices lorem, eget malesuada nulla. Pellentesque vel mattis nunc. Fusce quis ultricies quam,
                ut molestie ex. Nulla facilisi. Praesent id magna consequat, pulvinar ligula sit amet, maximus tellus.

            LEARN MORE

A: use margin-top:-10rem instead of top:-10rem and use z-index:999 or something bigger than the div on the top ( the div before .relative )  has ( in this example top has z-index:2 ) . if it doesn't have a z-index give one manually
.top{z-index:2} , .relative{z-index:3}
let me know if it works ( in the snippet example it works )

.relative {
    margin-top: -10rem;
    position: relative;
    z-index:999;

}
.top {
  height:200px;
  background:blue;
  position:relative;
  z-index:2;
}
.bottom {
  height:200px;
  background:blue;
}
<link href="https://maxcdn.bootstrapcdn.com/bootswatch/latest/journal/bootstrap.min.css" rel="stylesheet"/>

SPARES SOLUTIONS

                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit amet ultrices lorem, eget malesuada nulla. Pellentesque vel mattis nunc. Fusce quis ultricies quam,
                    ut molestie ex. Nulla facilisi. Praesent id magna consequat, pulvinar ligula sit amet, maximus tellus.

                LEARN MORE

SPARES SOLUTIONS

                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit amet ultrices lorem, eget malesuada nulla. Pellentesque vel mattis nunc. Fusce quis ultricies quam,
                    ut molestie ex. Nulla facilisi. Praesent id magna consequat, pulvinar ligula sit amet, maximus tellus.

                LEARN MORE

SPARES SOLUTIONS

                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit amet ultrices lorem, eget malesuada nulla. Pellentesque vel mattis nunc. Fusce quis ultricies quam,
                    ut molestie ex. Nulla facilisi. Praesent id magna consequat, pulvinar ligula sit amet, maximus tellus.

                LEARN MORE

                    "Click Spares have saved us
                    thousands since we joined!!!",
                    really great service and they
                    know exactly how to deal with
                    tricky customers"

                    Product Retail Manager

WHY CLICK SPARES

                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit amet ultrices lorem, eget malesuada nulla. Pellentesque vel mattis nunc. Fusce quis ultricies quam,
                ut molestie ex. Nulla facilisi. Praesent id magna consequat, pulvinar ligula sit amet, maximus tellus.

            LEARN MORE

A: Just use margin-top: -10rem; instead of top: -10rem;


text:
Q: Converting SQL Query to Databricks SQL I have a query that I need to convert to Databricks SQL or run against a table in a Databrick environment but failing even though it works very well against tables SQL Server. The tables and query can be found here
The query to convert or run in Databricks environment is:
;WITH CTE AS (
    SELECT EventID
         , EventName
         , EventStartDateTime
         , IIF(EventEndDateTime = '',GETUTCDATE(),EventEndDateTime)
           AS EventEndDateTime
     FROM EventLog

     UNION ALL

     SELECT EventID
          , EventName
          , DATEADD(month, DATEDIFF(month, 0, DATEADD(month , 1 ,
             EventStartDateTime)), 0) AS EventStartDateTime
          , EventEndDateTime
     FROM CTE
     WHERE  DATEADD(month, DATEDIFF(month, 0, DATEADD(month , 1 ,
     EventStartDateTime)), 0)  <= EventEndDateTime
  )

And then selecting from the CTE like so:
SELECT EventID
     , EventName
     , YEAR(EventStartDateTime)
     , DATENAME(MONTH,EventStartDateTime)
     , DATEDIFF(SECOND, EventStartDateTime, n_EventStartDateTime) /
         3600.0
 FROM (
   SELECT EventID
        , EventName
        , EventStartDateTime
        , LEAD(EventStartDateTime,1,EventEndDateTime)
          OVER(PARTITION BY EventID,EventName ORDER BY
           EventStartDateTime) n_EventStartDateTime
   FROM CTE
  ) t1
      OPTION (maxrecursion 0)

I equally noticed that
DATEADD(month, DATEDIFF(month, 0, DATEADD(month , 1 ,
          EventStartDateTime)), 0) AS EventStartDateTime

and
DATEDIFF(SECOND, EventStartDateTime, n_EventStartDateTime) / 3600.0

are not working in databricks environment.
I sincerely appreciate your help on this

A: According to the error you found, the particular codes should be modified as follows:
SQL Server Version:
DATEADD(month, DATEDIFF(month, 0, DATEADD(month , 1 ,
          EventStartDateTime)), 0) AS EventStartDateTime

Databricks Version:
add_months('1900-01-01', months_between(add_months(EventStartDateTime, 1), '1900-01-01'))

SQL Server Version:
DATEDIFF(SECOND, EventStartDateTime, n_EventStartDateTime) / 3600.0

Databricks Version:
datediff(EventStartDateTime, n_EventStartDateTime) * 24

Read more about Databricks date function. Note that some functions are just released after particular Databricks SQL endpoint versions which may not be available yet.


text:
Q: How can i use this library on API 16 in Android I want use this library for searchBar in my application : See Link
This library minSDK has 16 and when run this library on SDK 16 and 17 and click on EditText (for write worlds) not show my any text and just show white screen (in editText) but when run on device with SDK 18 and above it ok and not bug!
SearchBar codes:
public class MaterialSearchBar extends RelativeLayout implements View.OnClickListener,
        Animation.AnimationListener, SuggestionsAdapter.OnItemViewClickListener,
        View.OnFocusChangeListener, TextView.OnEditorActionListener {
    public static final int BUTTON_SPEECH = 1;
    public static final int BUTTON_NAVIGATION = 2;

    private LinearLayout inputContainer;
    private ImageView searchIcon;
    private ImageView arrowIcon;
    private AppCompatEditText searchEdit;
    private ImageView navIcon;
    private OnSearchActionListener onSearchActionListener;
    private boolean searchEnabled;
    private boolean suggestionsVisible;
    public static final int VIEW_VISIBLE = 1;
    public static final int VIEW_INVISIBLE = 0;
    private SuggestionsAdapter adapter;
    private float destiny;

    private int searchIconRes;
    private int navIconResId;
    private CharSequence hint;
    private int maxSuggestionCount;
    private boolean speechMode;

    private int menuResource;
    private PopupMenu popupMenu;

    private int textColor;
    private int hintColor;

    private boolean navButtonEnabled;

    public MaterialSearchBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public MaterialSearchBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public MaterialSearchBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        inflate(getContext(), R.layout.searchbar, this);

        TypedArray array = getContext().obtainStyledAttributes(attrs, R.styleable.MaterialSearchBar);
        searchIconRes = array.getResourceId(R.styleable.MaterialSearchBar_searchIconDrawable, -1);
        navIconResId = array.getResourceId(R.styleable.MaterialSearchBar_navIconDrawable, -1);
        hint = array.getString(R.styleable.MaterialSearchBar_hint);
        maxSuggestionCount = array.getInt(R.styleable.MaterialSearchBar_maxSuggestionsCount, 3);
        speechMode = array.getBoolean(R.styleable.MaterialSearchBar_speechMode, false);

        hintColor = array.getColor(R.styleable.MaterialSearchBar_hintColor, -1);
        textColor = array.getColor(R.styleable.MaterialSearchBar_textColor, -1);
        navButtonEnabled = array.getBoolean(R.styleable.MaterialSearchBar_navIconEnabled, false);

        destiny = getResources().getDisplayMetrics().density;
        adapter = new SuggestionsAdapter(LayoutInflater.from(getContext()));
        adapter.setListener(this);
        adapter.maxSuggestionsCount = maxSuggestionCount;
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.mt_recycler);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        array.recycle();

        searchIcon = (ImageView) findViewById(R.id.mt_search);
        arrowIcon = (ImageView) findViewById(R.id.mt_arrow);
        searchEdit = (AppCompatEditText) findViewById(R.id.mt_editText);
        inputContainer = (LinearLayout) findViewById(R.id.inputContainer);
        navIcon = (ImageView) findViewById(R.id.mt_nav);
        findViewById(R.id.mt_clear).setOnClickListener(this);

        setOnClickListener(this);
        arrowIcon.setOnClickListener(this);
        searchIcon.setOnClickListener(this);
        searchEdit.setOnFocusChangeListener(this);
        searchEdit.setOnEditorActionListener(this);
        navIcon.setOnClickListener(this);
        postSetup();
    }

    /**
     * Inflate menu for searchBar
     *
     * @param menuResource - menu resource
     */
    public void inflateMenu(int menuResource) {
        this.menuResource = menuResource;
        if (menuResource > 0) {
            ImageView menuIcon = (ImageView) findViewById(R.id.mt_menu);
            RelativeLayout.LayoutParams params = (LayoutParams) searchIcon.getLayoutParams();
            params.rightMargin = (int) (36 * destiny);
            searchIcon.setLayoutParams(params);
            menuIcon.setVisibility(GONE);
            menuIcon.setOnClickListener(this);
            popupMenu = new PopupMenu(getContext(), menuIcon);
            popupMenu.inflate(menuResource);
            popupMenu.setGravity(Gravity.RIGHT);
        }
    }

    /**
     * Get popup menu
     *
     * @return PopupMenu
     */
    public PopupMenu getMenu() {
        return this.popupMenu;
    }

    private void postSetup() {
        if (searchIconRes < 0)
            searchIconRes = R.drawable.ic_magnify_black_48dp;
        setSpeechMode(speechMode);
        if (navIconResId < 0)
            navIconResId = R.drawable.ic_menu_black_24dp;
        setNavigationIcon(navIconResId);
        if (hint != null)
            searchEdit.setHint(hint);
        setupTextColors();
        setNavButtonEnabled(navButtonEnabled);
        if (popupMenu == null)
            findViewById(R.id.mt_menu).setVisibility(GONE);
    }

    private void setupTextColors() {
        if (hintColor != -1)
            searchEdit.setHintTextColor(ContextCompat.getColor(getContext(), hintColor));
        if (textColor != -1)
            searchEdit.setTextColor(ContextCompat.getColor(getContext(), textColor));
    }

    /**
     * Register listener for search bar callbacks.
     *
     * @param onSearchActionListener the callback listener
     */
    public void setOnSearchActionListener(OnSearchActionListener onSearchActionListener) {
        this.onSearchActionListener = onSearchActionListener;
    }

    /**
     * Hides search input and close arrow
     */
    public void disableSearch() {
        searchEnabled = false;
        Animation out = AnimationUtils.loadAnimation(getContext(), R.anim.fade_out);
        Animation in = AnimationUtils.loadAnimation(getContext(), R.anim.fade_in_right);
        out.setAnimationListener(this);
        searchIcon.setVisibility(VISIBLE);
        inputContainer.startAnimation(out);
        //inputContainer.animate().alpha(0).start();
        searchIcon.startAnimation(in);

        if (listenerExists())
            onSearchActionListener.onSearchStateChanged(false);
        if (suggestionsVisible) animateLastRequests(getListHeight(false), 0);
    }

    /**
     * Shows search input and close arrow
     */
    public void enableSearch() {
        adapter.notifyDataSetChanged();
        searchEnabled = true;
        Animation left_in = AnimationUtils.loadAnimation(getContext(), R.anim.fade_in_left);
        Animation left_out = AnimationUtils.loadAnimation(getContext(), R.anim.fade_out_left);
        left_in.setAnimationListener(this);
        inputContainer.setVisibility(VISIBLE);
        inputContainer.startAnimation(left_in);
        //inputContainer.animate().alpha(1).x(0).start();
        if (listenerExists()) {
            onSearchActionListener.onSearchStateChanged(true);
        }
        searchIcon.startAnimation(left_out);
    }

    private void animateLastRequests(int from, int to) {
        suggestionsVisible = to > 0;
        final RelativeLayout last = (RelativeLayout) findViewById(R.id.last);
        final ViewGroup.LayoutParams lp = last.getLayoutParams();
        if (to == 0 && lp.height == 0)
            return;
        ValueAnimator animator = ValueAnimator.ofInt(from, to);
        animator.setDuration(200);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                lp.height = (int) animation.getAnimatedValue();
                last.setLayoutParams(lp);
            }
        });
        if (adapter.getItemCount() > 0)
            animator.start();
    }

    /**
     * Set search icon drawable resource
     *
     * @param searchIconResId icon resource id
     */
    public void setSearchIcon(int searchIconResId) {
        this.searchIconRes = searchIconResId;
        this.searchIcon.setImageResource(searchIconResId);
    }

    /**
     * Set navigation icon drawable resource
     *
     * @param navigationIconResId icon resource id
     */
    public void setNavigationIcon(int navigationIconResId) {
        this.navIconResId = navigationIconResId;
        this.navIcon.setImageResource(navigationIconResId);
    }

    /**
     * Sets search bar hint
     *
     * @param hint
     */
    public void setHint(CharSequence hint) {
        this.hint = hint;
        searchEdit.setHint(hint);
    }

    /**
     * sets the speechMode for the search bar.
     * If set to true, microphone icon will display instead of the search icon.
     * Also clicking on this icon will trigger the callback method onButtonClicked()
     *
     * @param speechMode
     * @see #BUTTON_SPEECH
     * @see OnSearchActionListener#onButtonClicked(int)
     */
    public void setSpeechMode(boolean speechMode) {
        this.speechMode = speechMode;
        if (speechMode) {
            searchIcon.setImageResource(R.drawable.mn_v_sv_mic4);
            searchIcon.setColorFilter(ContextCompat.getColor(getContext(), R.color.colorAccent));
            searchIcon.setClickable(true);
        } else {
            searchIcon.setImageResource(searchIconRes);
            searchIcon.setClickable(false);
        }
    }

    /**
     * True if MaterialSearchBar is in speech mode
     *
     * @return speech mode
     */
    public boolean isSpeechModeEnabled() {
        return speechMode;
    }

    /**
     * Check if search bar is in edit mode
     *
     * @return true if search bar is in edit mode
     */
    public boolean isSearchEnabled() {
        return searchEnabled;
    }

    /**
     * Specifies the maximum number of search queries stored until the activity is destroyed
     *
     * @param maxQuery maximum queries
     */
    public void setMaxSuggestionCount(int maxQuery) {
        this.maxSuggestionCount = maxQuery;
        adapter.maxSuggestionsCount = maxQuery;
    }

    /**
     * Returns the last search queries.
     * The queries are stored only for the duration of one activity session.
     * When the activity is destroyed, the queries will be deleted.
     * To save queries, use the method getLastSuggestions().
     * To recover the queries use the method setLastSuggestions().
     *
     * @return array with the latest search queries
     * @see #setLastSuggestions(List)
     * @see #setMaxSuggestionCount(int)
     */
    public List<String> getLastSuggestions() {
        return adapter.getSuggestions();
    }

    /**
     * Sets the array of recent search queries.
     * It is advisable to save the queries when the activity is destroyed
     * and call this method when creating the activity.
     *
     * @param suggestions an array of queries
     * @see #getLastSuggestions()
     * @see #setMaxSuggestionCount(int)
     */
    public void setLastSuggestions(List<String> suggestions) {
        adapter.setSuggestions(suggestions);
    }

    /**
     * Set search input text color
     *
     * @param textColor text color
     */
    public void setTextColor(int textColor) {
        this.textColor = textColor;
        setupTextColors();
    }

    /**
     * Set text input hint color
     *
     * @param hintColor text hint color
     */
    public void setTextHintColor(int hintColor) {
        this.hintColor = hintColor;
        setupTextColors();
    }

    /**
     * Set navigation drawer menu icon enabled
     *
     * @param navButtonEnabled icon enabled
     */
    public void setNavButtonEnabled(boolean navButtonEnabled) {
        this.navButtonEnabled = navButtonEnabled;
        if (navButtonEnabled) {
            navIcon.setVisibility(VISIBLE);
            navIcon.setClickable(true);
            LayoutParams lp = (LayoutParams) inputContainer.getLayoutParams();
            lp.leftMargin = (int) (50 * destiny);
            inputContainer.setLayoutParams(lp);
            arrowIcon.setVisibility(GONE);
        } else {
            navIcon.setVisibility(GONE);
            navIcon.setClickable(false);
        }
    }

    public void setText(String text) {
        searchEdit.setText(text);
    }

    public String getText() {
        return searchEdit.getText().toString();
    }

    /**
     * Set CardView elevation
     *
     * @param elevation
     */
    public void setCardViewElevation(int elevation) {
        CardView cardView = (CardView) findViewById(R.id.mt_container);
        cardView.setCardElevation(elevation);
    }

    /**
     * Add text watcher to searchbar's EditText
     *
     * @param textWatcher
     */
    public void addTextChangeListener(TextWatcher textWatcher) {
        searchEdit.addTextChangedListener(textWatcher);
    }

    private boolean listenerExists() {
        return onSearchActionListener != null;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == getId()) {
            if (!searchEnabled) {
                enableSearch();
            }
        } else if (id == R.id.mt_arrow) {
            disableSearch();
        } else if (id == R.id.mt_search) {
            if (listenerExists())
                onSearchActionListener.onButtonClicked(BUTTON_SPEECH);
        } else if (id == R.id.mt_clear) {
            searchEdit.setText("");
            disableSearch();
        } else if (id == R.id.mt_menu) {
            popupMenu.show();
        } else if (id == R.id.mt_nav)
            if (listenerExists())
                onSearchActionListener.onButtonClicked(BUTTON_NAVIGATION);
    }

    @Override
    public void onAnimationStart(Animation animation) {

    }

    @Override
    public void onAnimationEnd(Animation animation) {
        if (!searchEnabled) {
            inputContainer.setVisibility(GONE);
            searchEdit.setText("");
        } else {
            searchIcon.setVisibility(GONE);
            searchEdit.requestFocus();
            animateLastRequests(0, getListHeight(false));
        }
    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (hasFocus) {
            imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
        } else {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (listenerExists())
            onSearchActionListener.onSearchConfirmed(searchEdit.getText());
        if (suggestionsVisible)
            animateLastRequests(getListHeight(false), 0);
        adapter.addSuggestion(searchEdit.getText().toString());
        return true;
    }

    private int getListHeight(boolean isSubtraction) {
        if (!isSubtraction)
            return (int) ((adapter.getItemCount() * 50) * destiny);
        return (int) (((adapter.getItemCount() - 1) * 50) * destiny);
    }

    @Override
    public void OnItemClickListener(int position, View v) {
        if (v.getTag() instanceof String) {
            searchEdit.setText((String) v.getTag());
        }
    }

    @Override
    public void OnItemDeleteListener(int position, View v) {
        if (v.getTag() instanceof String) {
            /*Order of two line should't be change,
            because sholud calculate the height of item first*/
            animateLastRequests(getListHeight(false), getListHeight(true));
            adapter.deleteSuggestion(position, (String) v.getTag());
        }
    }

        void onButtonClicked(int buttonCode);
    }

    @Override
    protected Parcelable onSaveInstanceState() {
        SavedState savedState = new SavedState(super.onSaveInstanceState());
        savedState.isSearchBarVisible = searchEnabled ? VIEW_VISIBLE : VIEW_INVISIBLE;
        savedState.suggestionsVisible = suggestionsVisible ? VIEW_VISIBLE : VIEW_INVISIBLE;
        savedState.speechMode = speechMode ? VIEW_VISIBLE : VIEW_INVISIBLE;
        savedState.navIconResId = navIconResId;
        savedState.searchIconRes = searchIconRes;
        savedState.suggestions = getLastSuggestions();
        savedState.maxSuggestions = maxSuggestionCount;
        if (hint != null) savedState.hint = hint.toString();
        return savedState;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        SavedState savedState = (SavedState) state;
        super.onRestoreInstanceState(savedState.getSuperState());
        searchEnabled = savedState.isSearchBarVisible == VIEW_VISIBLE;
        suggestionsVisible = savedState.suggestionsVisible == VIEW_VISIBLE;
        setLastSuggestions(savedState.suggestions);
        if (suggestionsVisible)
            animateLastRequests(0, getListHeight(false));
        if (searchEnabled) {
            inputContainer.setVisibility(VISIBLE);
            searchIcon.setVisibility(GONE);
        }
    }

    private static class SavedState extends BaseSavedState {
        private int isSearchBarVisible;
        private int suggestionsVisible;
        private int speechMode;
        private int searchIconRes;
        private int navIconResId;
        private String hint;
        private List<String> suggestions;
        private int maxSuggestions;

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeInt(isSearchBarVisible);
            out.writeInt(suggestionsVisible);
            out.writeInt(speechMode);

            out.writeInt(searchIconRes);
            out.writeInt(navIconResId);
            out.writeString(hint);
            out.writeList(suggestions);
            out.writeInt(maxSuggestions);
        }

        public SavedState(Parcel source) {
            super(source);
            isSearchBarVisible = source.readInt();
            suggestionsVisible = source.readInt();
            speechMode = source.readInt();

            navIconResId = source.readInt();
            searchIconRes = source.readInt();
            hint = source.readString();
            suggestions = source.readArrayList(null);
            maxSuggestions = source.readInt();
        }

        public SavedState(Parcelable superState) {
            super(superState);
        }

        public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
            @Override
            public SavedState createFromParcel(Parcel source) {
                return new SavedState(source);
            }

            @Override
            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && searchEnabled) {
            animateLastRequests(getListHeight(false), 0);
            disableSearch();
            return true;
        }
        return super.dispatchKeyEvent(event);
    }
}

searchBar xml codes:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <android.support.v7.widget.CardView
        android:id="@+id/mt_container"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_margin="8dp"
        app:cardBackgroundColor="@android:color/white"
        app:cardElevation="4dp">

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/root"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <android.support.v7.widget.AppCompatImageView
                android:id="@+id/mt_menu"
                android:layout_width="36dp"
                android:layout_height="50dp"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true"
                android:background="?attr/selectableItemBackgroundBorderless"
                android:clickable="true"
                android:padding="13dp"
                android:scaleType="centerCrop"
                android:src="@drawable/ic_dots_vertical_black_48dp"
                android:tint="@color/material_grey_600"
                android:visibility="gone" />

            <android.support.v7.widget.AppCompatImageView
                android:id="@+id/mt_nav"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_weight="1"
                android:clickable="true"
                android:scaleType="center"
                android:tint="@color/colorAccent"
                app:srcCompat="@drawable/ic_menu_black_24dp" />

            <LinearLayout
                android:id="@+id/inputContainer"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:layout_toLeftOf="@+id/mt_menu"
                android:layout_toRightOf="@+id/mt_nav"
                android:layout_toStartOf="@+id/mt_menu"
                android:gravity="center_vertical"
                android:orientation="horizontal"
                android:visibility="gone">

                <android.support.v7.widget.AppCompatImageView
                    android:id="@+id/mt_arrow"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:background="?attr/selectableItemBackground"
                    android:clickable="true"
                    android:padding="13dp"
                    android:src="@drawable/ic_arrow_left_black_48dp"
                    android:tint="@color/material_grey_600"
                    android:visibility="visible" />

                <android.support.v7.widget.AppCompatEditText
                    android:id="@+id/mt_editText"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="8dp"
                    android:layout_weight="1"
                    android:background="@android:color/transparent"
                    android:hint="@string/action_search"
                    android:imeOptions="flagNoExtractUi|actionSearch"
                    android:gravity="right|center_vertical"
                    android:textColor="@color/colorAccent"
                    android:singleLine="true"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:visibility="visible" />

                <android.support.v7.widget.AppCompatImageView
                    android:id="@+id/mt_clear"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_marginRight="50dp"
                    android:background="?attr/selectableItemBackground"
                    android:padding="14dp"
                    android:src="@drawable/ic_close_black_48dp"
                    android:tint="@color/colorAccent" />

            </LinearLayout>

            <RelativeLayout
                android:id="@+id/last"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_marginTop="50dp">

                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:background="@color/material_grey_300" />

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/mt_recycler"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </RelativeLayout>

            <android.support.v7.widget.AppCompatImageView
                android:id="@+id/mt_search"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:clickable="false"
                android:padding="13dp"
                android:src="@drawable/ic_magnify_black_48dp"
                android:tint="@color/colorAccent"
                android:visibility="visible" />

        </RelativeLayout>

    </android.support.v7.widget.CardView>

</merge>

Style code:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

</resources>

How can i fix bug and run successfully in sdk 16 and 17 ?
Please help me, Thanks all <3


text:
Q: Time complexity of prefix to postfix conversion? I think it should be quadratic i.e O(n^2). I am reading from this source prefix to postfix . I assume that appending two string takes linear time (O(sum of size of the two strings which we are appending)) and maximum number of times we need to append can go upto O(n) and thus overall complexity is O(n^2).
Can some one tell if i am wrong and can some one provide better proof of this ?

A: Yes, you're right that it's O(n2), and I think your proof is OK, but that depends who you have to prove it to.  Maybe show explicitly how to construct a string that would result in O(n) appends of O(n) size.
Here's a simple recursive version that does the job in O(n):
static String preToPost(String src)
{
    StringBuilder dest = new StringBuilder(src.length());
    for(int pos=0; pos < src.length(); pos = preToPost(dest, src, pos));
    return dest.toString();
}
// Convert one prefix expression to postfix.  Returns
// end position
static int preToPost(StringBuilder dest, String src, int pos)
{
    if (pos >= src.length())
    {
        //no expression
        return pos;
    }
    char c = src.charAt(pos++);
    if ("+-/*".indexOf(c)>=0)
    {
        //operator. Convert both operands first
        pos = preToPost(dest, src, pos);
        pos = preToPost(dest, src, pos);
    }
    dest.append(c);
    return pos;
}

The iterative version is not much more complicated:
static String preToPost2(String src)
{
    StringBuilder dest = new StringBuilder(src.length());
    int pos=0;

    Stack<Character> stk = new Stack<>();
    while(pos < src.length())
    {
        char c = src.charAt(pos++);
        if ("+-/*".indexOf(c)>=0)
        {
            //operator.  After the next 2 expressions, put c
            stk.push(c);
            //after the next expression, just do another one
            stk.push('\0');
            continue;
        }
        dest.append(c);
        // done expression.  check the todo stack
        while(!stk.empty())
        {
            c = stk.pop();
            if (c=='\0')
            {
                break;
            }
            dest.append(c);
            // the append completed another expression, so loop
            // to check the todo stack again
        }
    }
    return dest.toString();
}

This is a direct conversion of the recursive one.


text:
Q: Why is list() necessary in aggregate() When using aggregate() by columns you specify which columns you want to e.g summarise over in a list.
For instance:
aggregate(mtcars$qsec, by = list(as.factor(mtcars$cyl),
                                      as.factor(mtcars$carb)), FUN = sum)

 Group.1 Group.2      x
1       4       1  96.89
2       6       1  39.66
3       4       2 113.62
4       8       2  68.24
5       8       3  53.00
6       6       4  70.68
7       8       4  98.97
8       6       6  15.50
9       8       8  14.60

Why is a list() necessary here, why not a vector?


text:
Q: Looping over Joined query I've got a query which outputs the following data:
Treatment ID --------- Treatment_Name ---------- Customer_type
1                      Treatment 1               Ladies
1                      Treatment 1               Mens
3                      Treatment 2               Ladies
4                      Treatment 3               Mens

I need to loop over this and output a similar structure to this:

Treatment 1

So basically grouping by the Treatment name (or ID) and then outputting all of the customers related to this treatment.
Coming from a ColdFusion background I assumed this would be easy with a Query of Queries etc. however I've struggled with coming up with a PHP solution.
I've tried to do a while loop and only show data if the treatment_name has changed which seems to work fine but I'm not sure how to display the customer_types related to this.
Any ideas? Thanks.
Edit
Here is a copy of the query returned from the db using a mysqli_fetch_all:
array (size=22)
  0 =>
    array (size=3)
      0 => string 'Mens' (length=4)
      1 => string '1' (length=1)
      2 => string 'treatment 1' (length=11)
  1 =>
    array (size=3)
      0 => string 'Ladies' (length=6)
      1 => string '1' (length=1)
      2 => string 'treatment 1' (length=11)
  2 =>
    array (size=3)
      0 => string 'Kids' (length=4)
      1 => string '2' (length=1)
      2 => string 'treatment 2' (length=11)
  3 =>
    array (size=3)
      0 => string 'Ladies' (length=6)
      1 => string '2' (length=1)
      2 => string 'treatment 2' (length=11)
  4 =>
    array (size=3)
      0 => string 'Mens' (length=4)
      1 => string '2' (length=1)
      2 => string 'treatment 2' (length=11)
  5 =>
    array (size=3)
      0 => string 'Mens' (length=4)
      1 => string '3' (length=1)
      2 => string 'treatment 3' (length=11)
  6 =>
    array (size=3)
      0 => string 'Kids' (length=4)
      1 => string '3' (length=1)
      2 => string 'treatment 3' (length=11)
  7 =>
    array (size=3)
      0 => string 'Ladies' (length=6)
      1 => string '3' (length=1)
      2 => string 'treatment 3' (length=11)
  8 =>
    array (size=3)
      0 => string 'Ladies' (length=6)
      1 => string '4' (length=1)
      2 => string 'treatment 4' (length=11)

It continues in the same format...

A: Hope this answers your question:
<?php
    $link = mysqli_connect("hostname","username","password","database","port") or die("Error " . mysqli_error($link));
    $query = "SELECT treatment_name,Customer_type from Treatments" or die("Error at.." . mysqli_error($link));
    $result = $link->query($query);

    while($row = mysqli_fetch_assoc($result)) {
        $data[] = $row;
    }
//I have used this sample array: Try and make your result set this way
    $data = array(
                array('treatment_name'=>'Treatment1','Customer_type'=>'Mens'),
                array('treatment_name'=>'Treatment1','Customer_type'=>'Ladies'),
                array('treatment_name'=>'Treatment2','Customer_type'=>'Mens')
            );
    foreach ($data as $key => &$value) {
        $temp[$value['treatment_name']][$key] = $value['Customer_type'];
    }

    //echo "
";
    //print_r($data);
    //print_r($temp);
    //die;

    foreach($temp as $key => $value){
        echo "
 $value2)
            echo " ". $value2. " ";
        echo "\">
".$key."

";
    }
?>
//Output

Treatment1

Treatment2

You can use the commented lines for checking the data and adjusting accordingly.
By the way, this code directly prints the output as html, so your browser will render it. Right click the page and view source  if you want the content!


text:
Q: How to style a react Link component? When I try to style the Link component, it does not work:
Link {
  padding: 0 30px;
}

But it does work when I use inline styling
<Link style={{padding: '0 30px'}} to="/invoices">Invoices</Link>

I use import './App.css' and styling normal elements like div does work.

A: Provide className as a prop to Link
.link-styles {
  padding: 0 30px;
}

<Link className={"link-styles"} to="/invoices">
  Invoices
</Link>

A: Link is a react component, which by default isn't directly read/defined in native css styling.
Saying that means only one thing, Links are just anchor tags, and thus you can style/modify them in the css styling sheet using a.
To style all links available on the page (general styling) just add a { general styles..} on top of your sheet.
And then to style each one on their own, make sure its wrapped in a div with a className, and in your styles do it this way:
.divClassNameYouChose a {   custom styles...  }

A: There are many ways you can do this:

*

*Using id in the component

    <Link id="link_Styles" to="/invoices">
          Invoices
    </Link>

And css is like
#link_Styles {
   padding: 0 30px;
}

*Using bootstrap inbuilt classes like

    <Link className="px-4" to="/invoices"> //px-4 means 24px (1.5rem)
          Invoices
    </Link>

*Using tailwindCSS classes

    <Link className="px-7" to="/invoices">  //px-7 means 28px (1.75rem)
          Invoices
    </Link>

But for approach 2 & 3, you have to embed their CDN links respectively.

*Using className like done by @Amila in first answer


text:
Q: How to transfer a notebook with imported data to another computer? I've been working on a notebook at home with imported data from some Excel files and plan on working on it on another computer. I have the .nb file and the .xls files, and my imported data is a suppressed output.
Sorry is this is an obvious question, I can't get the key words right in my searches for an answer.
What is the best way to transfer my notebook, all the stored variables and .xls files as one package to another computer?
Am I going to have to transfer all the files to the new computer, go into my notebook and fix the file directory for each individual time that I imported data (as the file directory will not be the same on the new computer)? Then will I have to re-evaluate every single command?
I've never actually had to transfer my notebook from one computer to another, I am always used to working on the same machine so I'm unsure as to the mechanics of moving large notebooks with imported data and lots of set variables to a new machine.

A: You can use
DumpSave["state.mx", "Global`"]

to put all the defined variables/symbols in a given instance into a file. Then you can afterwards reload that with Get["state.mx"]. This is probably the most 'portable state' form you can get for moving a notebook's loaded data to another computer, without moving the source data.


text:
Q: Can you do this with Hudson? I want to create a hudson job, that takes an id as a parameter. And use that id to calculate the svn-repo path.
Where I work you have a svn path for every issue that you resolve. And then all the issues are joined into a single svn-path.
What I want to do is to run static code analysis on the partial issues.
So I think maybe having an Ant build.xml that I use for every issue, then, parametrize the job with the issue id.
I have tried to achieve that but the svn path doesn't replace the parameter.
I have tried with #issueId, %issueId%, ${issueId} and ${env.issueId} without success.
Jump error like:
Location 'http://svn-path:8181/svn/devSet/issues/${env.chuid}' does not exist
Checking out a fresh workspace because C:\Documents and Settings\dnoseda\.hudson\jobs\test\workspace\${env.chuid} doesn't exist
Checking out http://svn-path:8181/svn/devSet/issues/${env.chuid}
ERROR: Failed to check out http://svn-path:8181/svn/devSet/issues/${env.chuid}
org.tmatesoft.svn.core.SVNException: svn: '/svn/!svn/bc/46190/devSet/issues/$%7Benv.chuid%7D' path not found: 404 Not Found (http://svn-path:8181)
    at org.tmatesoft.svn.core.internal.wc.SVNErrorManager.error(SVNErrorManager.java:64)
    at org.tmatesoft.svn.core.internal.wc.SVNErrorManager.error(SVNErrorManager.java:51)
    at

I am think that I can not do what I want.
Do you know how I can setup the correct configuration to achieve this matter?
Thanks for any help.
Edit
The section of the configurate job that I want to put this parameter is this:
<scm class="hudson.scm.SubversionSCM">
<locations>
      <hudson.scm.SubversionSCM_-ModuleLocation>
        <remote>http://svn-path:8181/svn/devSet/issues/${env.issueid}</remote>
      </hudson.scm.SubversionSCM_-ModuleLocation>
    </locations>

New Edit: Solved
My version of hudson it was the last (1.349), but the version of svn plugin it was 1.11, being the last the 1.13, and it work with ${issueId}
Thank for the anwsers

A: From the hudson wiki:
"The parameter are available as environment parameters. So e.g. a shell ($FOO, %FOO%) or Ant ( ${env.FOO} ) can access these values."
Your syntax doesn't match the one in the wiki.

A: I've setup a svn project that does the parameter substitution successfully.   The syntax is indeed ${issueId} so I assume you are doing something wrong, or are using a very old version of Hudson.   Could you update the question with the versions of Hudson and the subversion plugin that you are using?
<project>
  <actions/>
  <description></description>
  <keepDependencies>false</keepDependencies>
  <properties>
    <hudson.model.ParametersDefinitionProperty>
      <parameterDefinitions>
        <hudson.model.StringParameterDefinition>
          <name>issueId</name>
          <description></description>
          <defaultValue>none</defaultValue>
        </hudson.model.StringParameterDefinition>
      </parameterDefinitions>
    </hudson.model.ParametersDefinitionProperty>
  </properties>
  <scm class="hudson.scm.SubversionSCM">
    <locations>
      <hudson.scm.SubversionSCM_-ModuleLocation>
        <remote>https://svn.dev.java.net/svn/hudson/trunk/${issueId}</remote>
      </hudson.scm.SubversionSCM_-ModuleLocation>
    </locations>
    <useUpdate>true</useUpdate>
    <excludedRegions></excludedRegions>
    <excludedUsers></excludedUsers>
    <excludedRevprop></excludedRevprop>
  </scm>
  <canRoam>true</canRoam>
  <disabled>false</disabled>
  <triggers class="vector"/>
  <concurrentBuild>false</concurrentBuild>
  <builders/>
  <publishers/>
  <buildWrappers/>
</project>

Here is the build output.  The checkout fails due to an authentication issue, but the parameter is successfully replaced:
Started by user anonymous
Building on master
Checking out a fresh workspace because C:\hudson\jobs\test-svn\workspace\${issueId} doesn't exist
Checking out https://svn.dev.java.net/svn/hudson/trunk/www
ERROR: Failed to check out https://svn.dev.java.net/svn/hudson/trunk/www
org.tmatesoft.svn.core.SVNCancelException: svn: No credential to try. Authentication failed
    at org.tmatesoft.svn.core.internal.wc.SVNErrorManager.cancel(SVNErrorManager.java:37)
    at org.tmatesoft.svn.core.internal.wc.SVNErrorManager.cancel(SVNErrorManager.java:32)
    at org.tmatesoft.svn.core.internal.wc.DefaultSVNAuthenticationManager.getFirstAuthentication(DefaultSVNAuthenticationManager.java:168)
    at org.tmatesoft.svn.core.internal.io.dav.http.HTTPConnection.request(HTTPConnection.java:534)
    at org.tmatesoft.svn.core.internal.io.dav.http.HTTPConnection.request(HTTPConnection.java:273)
    at org.tmatesoft.svn.core.internal.io.dav.http.HTTPConnection.request(HTTPConnection.java:261)
    at org.tmatesoft.svn.core.internal.io.dav.DAVConnection.exchangeCapabilities(DAVConnection.java:516)
    at org.tmatesoft.svn.core.internal.io.dav.DAVConnection.open(DAVConnection.java:98)
    at org.tmatesoft.svn.core.internal.io.dav.DAVRepository.openConnection(DAVRepository.java:1001)
    at org.tmatesoft.svn.core.internal.io.dav.DAVRepository.getLatestRevision(DAVRepository.java:178)
    at org.tmatesoft.svn.core.wc.SVNBasicClient.getRevisionNumber(SVNBasicClient.java:482)
    at org.tmatesoft.svn.core.wc.SVNBasicClient.getLocations(SVNBasicClient.java:851)
    at org.tmatesoft.svn.core.wc.SVNBasicClient.createRepository(SVNBasicClient.java:534)
    at org.tmatesoft.svn.core.wc.SVNUpdateClient.doCheckout(SVNUpdateClient.java:893)
    at org.tmatesoft.svn.core.wc.SVNUpdateClient.doCheckout(SVNUpdateClient.java:791)
    at hudson.scm.SubversionSCM$CheckOutTask.invoke(SubversionSCM.java:615)
    at hudson.scm.SubversionSCM$CheckOutTask.invoke(SubversionSCM.java:541)
    at hudson.FilePath.act(FilePath.java:676)
    at hudson.FilePath.act(FilePath.java:660)
    at hudson.scm.SubversionSCM.checkout(SubversionSCM.java:534)
    at hudson.scm.SubversionSCM.checkout(SubversionSCM.java:482)
    at hudson.model.AbstractProject.checkout(AbstractProject.java:898)
    at hudson.model.AbstractBuild$AbstractRunner.checkout(AbstractBuild.java:400)
    at hudson.model.AbstractBuild$AbstractRunner.run(AbstractBuild.java:349)
    at hudson.model.Run.run(Run.java:1106)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:46)
    at hudson.model.ResourceController.execute(ResourceController.java:93)
    at hudson.model.Executor.run(Executor.java:122)
Notifying upstream projects of job completion
Finished: FAILURE

A: In this comment, it is mentioned that they use the ${ISSUEID}, which is why I suggested it, but all other signs I see say this doesn't actually work.
Otherwise I would recommend not using the SCM plugin and doing the SVN operation in a build script step. This would allow you to use the parameters as env variables like $ISSUEID


text:
Q: Search for an Array or List in a List Have
List<byte> lbyte

Have
byte[] searchBytes

How can I search lbyte for not just a single byte but for the index of the searchBytes?
E.G.
Int32 index = lbyte.FirstIndexOf(searchBytes);

Here is the brute force I came up with.
Not the performance I am looking for.
public static Int32 ListIndexOfArray(List<byte> lb, byte[] sbs)
{
    if (sbs == null) return -1;
    if (sbs.Length == 0) return -1;
    if (sbs.Length > 8) return -1;
    if (sbs.Length == 1) return lb.FirstOrDefault(x => x == sbs[0]);
    Int32 sbsLen = sbs.Length;
    Int32 sbsCurMatch = 0;
    for (int i = 0; i < lb.Count; i++)
    {
        if (lb[i] == sbs[sbsCurMatch])
        {
            sbsCurMatch++;
            if (sbsCurMatch == sbsLen)
            {
                //int index = lb.FindIndex(e => sbs.All(f => f.Equals(e)));  // fails to find a match
                IndexOfArray = i - sbsLen + 1;
                return;
            }
        }
        else
        {
            sbsCurMatch = 0;
        }
    }
    return -1;
}

A: Brute force is always an option. Although slow in comparison to some other methods, in practice it's usually not too bad. It's easy to implement and quite acceptable if lbyte isn't huge and doesn't have pathological data.
It's the same concept as brute force string searching.

A: You may find Boyer-Moore algorithm useful here. Convert your list to an array and search. The algorithm code is taken from this post.
static int SimpleBoyerMooreSearch(byte[] haystack, byte[] needle)
{
    int[] lookup = new int[256];
    for (int i = 0; i < lookup.Length; i++) { lookup[i] = needle.Length; }

    for (int i = 0; i < needle.Length; i++)
    {
        lookup[needle[i]] = needle.Length - i - 1;
    }

    int index = needle.Length - 1;
    var lastByte = needle.Last();
    while (index < haystack.Length)
    {
        var checkByte = haystack[index];
        if (haystack[index] == lastByte)
        {
            bool found = true;
            for (int j = needle.Length - 2; j >= 0; j--)
            {
                if (haystack[index - needle.Length + j + 1] != needle[j])
                {
                    found = false;
                    break;
                }
            }

            if (found)
                return index - needle.Length + 1;
            else
                index++;
        }
        else
        {
            index += lookup[checkByte];
        }
    }
    return -1;
}

You can then search like this. If lbyte will remain constant after a certain time, you can just convert it to an array once and pass that.
//index is returned, or -1 if 'searchBytes' is not found
int startIndex = SimpleBoyerMooreSearch(lbyte.ToArray(), searchBytes);

Update based on comment. Here's the IList implementation which means that arrays and lists (and anything else that implements IList can be passed)
 static int SimpleBoyerMooreSearch(IList<byte> haystack, IList<byte> needle)
 {
    int[] lookup = new int[256];
    for (int i = 0; i < lookup.Length; i++) { lookup[i] = needle.Count; }

    for (int i = 0; i < needle.Count; i++)
    {
        lookup[needle[i]] = needle.Count - i - 1;
    }

    int index = needle.Count - 1;
    var lastByte = needle[index];
    while (index < haystack.Count)
    {
        var checkByte = haystack[index];
        if (haystack[index] == lastByte)
        {
            bool found = true;
            for (int j = needle.Count - 2; j >= 0; j--)
            {
                if (haystack[index - needle.Count + j + 1] != needle[j])
                {
                    found = false;
                    break;
                }
            }

            if (found)
                return index - needle.Count + 1;
            else
                index++;
        }
        else
        {
            index += lookup[checkByte];
        }
    }
    return -1;
}

Since arrays and lists implement IList, there's no conversion necessary when calling it in your case.
int startIndex = SimpleBoyerMooreSearch(lbyte, searchBytes);

A: Another way you could do with lambda expression
int index = lbyte.FindIndex(e => searchBytes.All(i => i.Equals(e));


text:
Q: How do I use CMake to build the ECCODES package using MinGW? I'm trying to build some software from ECMWF called ECCODES.

*

*It builds fine on GNU/Linux.

*It builds fine on Mac OS X.

*It builds fine on Windows/Cygwin.

*Unfortunately (Ugh!!), I must use Windows and I can't use Cygwin.

*I have to use something like MinGW.

The build instructions use CMake.  I am no expert at CMake.  The Windows system I am on has:

*

*cygwin64

*mingw64

*a bare-bones Visual Studio 14

I've tried every incantation and override of the CMake variables/options:
-DCMAKE_C_COMPILER=... \
-DCMAKE_CXX_COMPILER=... \
-DCMAKE_Fortran_COMPILER=... \
-DCMAKE_MAKE_PROGRAM=... \
-G ...

to get ECCODES to build using MinGW, with no luck.  I know some will ask, "Why not contact ECMWF?"  The short answer is, the response time is very long (months/years).  The FAQ page is empty, and you can't post questions on their Jira site (it's locked).
Would it be possible for someone who knows CMake and MinGW well to download the .tar.gz, build ECCODES using MinGW, and tell us how you did it?
http://www.ecmwf.int/
https://software.ecmwf.int/wiki/display/ECC/ecCodes+Home
https://software.ecmwf.int/wiki/download/attachments/45757960/eccodes-0.13.0-Source.tar.gz?api=v2


text:
Q: Error: invalid arch independent ELF magic, while loading a VirtualBox machine with Ubuntu Tinyos I've created a virtual machine with Ubuntu (having TinyOS). The problem arises when I start the machine. I immediately get a black screen with written:
GRUB loading.
error: invalid arch independent ELF magic
grub rescue>

What kind of a problem is it, and more importantly how can I solve it?
I tried it on my laptop which has Windows 7 64 bit, and so I also tried it on my Ubuntu partition and also with Ubuntu, once I launch the virtual machine I get the same error!

A: This happens when the GRUB core image (the boot loader's first stage) is built for a different CPU architecture than the modules that it tries to load from /boot/grub.  (Here's the check you're running into, modulo slight typographical changes that have been made since then; it's called from here.)  This suggests a serious error when installing the OS.  It doesn't directly relate to 64-bit support in the VM or anything like that, although it's of course possible that that kind of thing might have confused the OS installer into doing the wrong thing somehow.
Since you asked this several years ago, it's possible that you've solved it by now, that you've given up, or that simply reinstalling with a newer version of Ubuntu will help.  But if none of those things are true:

*

*Ensure that the disk image was clean before you installed the virtual machine guest.  This sort of thing might happen if you have bits of GRUB left over from a previous installation.

*Make sure you aren't doing anything funny like trying to boot the guest using a boot loader that wasn't installed by the guest OS installation.

*Make sure the process of installing the guest was as simple as possible.  There usually isn't much reason to have something like a complicated partitioning setup in a VM guest, and that sort of thing just introduces ways that things can go wrong.


text:
Q: lsnrctl start rane when i fireing this command this error comeing [oracle@myserver ~]$ lsnrctl start rane

LSNRCTL for Linux: Version 11.2.0.1.0 - Production on 27-SEP-2016 23:04:58

Copyright (c) 1991, 2009, Oracle.  All rights reserved.

Starting /oraeng/app/oracle/product/11.2.0/bin/tnslsnr: please wait...

TNSLSNR for Linux: Version 11.2.0.1.0 - Production
System parameter file is /home/oracle/listener.ora
Log messages written to /oraeng/app/oracle/product/11.2.0/log/diag/tnslsnr/myserver/rane/alert/log.xml
TNS-01150: The address of the specified listener name is incorrect

Listener failed to start. See the error message(s) above...

This is my listener configuration:
LISTENER =
 (DESCRIPTION_LIST =
  (DESCRIPTION =
   (ADDRESS_LIST =
    (ADDRESS = (PROTOCOL = TCP)(HOST =192.168.246.128)(PORT =152101 ))
   )
  )
 )
 SID_LIST_LISTENER=
  (SID_LIST=
   (SID_DESC= (SID_NAME = raneesh)
   (ORACLE_HOME =/oraeng/app/oracle/product/11.2.0 )
  )
 )

A: The port number you have specified is not valid. The usual port number for a listener is 1521, but if you want to use a different value it still has to be in the valid range, with a maximum of 65535, and avoiding the well-known ports up to 1024. The number you have tried to use, 152101, is well outisde the allowed range.
Read more about port numbers.


text:
Q: Primefaces CommandLink only works the first time it's clicked I have a datatable, and have links that allow the user to insert a row directly below the current row.  This should then update the numbering.
It works perfectly once, creating a new row, populating the number and adding one to the numbering for all rows below.
If I click anything else though, it seems as though the ajax request completes but nothing happens.
You will see that I am using the #{table} variable to get the row index of the UIData element.  I have tried using process="@form" and process="@this" in the commandLink, but to no avail sadly.  Likewise, my method was returning void so I set it to return a null String, but the same result occurred.
XHTML
<h:form id="feForm">
   <p:dataTable value="#{fichaExpandidaBean.feFlujoNormalList}" binding="#{table}" var="fn">
      <p:column headerText="Paso:">
         <h:outputText value="#{fn.orden}-"/>
      </p:column>
      <p:column headerText="Descripcion:">
         <h:inputText value="#{fn.descripcion}" style="width:98%;"/>
      </p:column>
      <p:column headerText="Acciones">
         <p:commandLink style="margin: 5px;" action="#{fichaExpandidaBean.agregarFilaFlujoNormal(table.rowIndex)}" update="@form">
            <h:graphicImage title="Agregar fila abajo." value="/resources/imagenes/agregarFila.png" alt="AgregarFila"/>
         </p:commandLink>
      </p:column>
   </p:dataTable>
</h:form>

Bean:
@Named(value = "fichaExpandidaBean")
@ConversationScoped
public class FichaExpandidaBean implements Serializable {

@Inject
    private Conversation conversation;
...etc...

public String agregarFilaFlujoNormal(int row){

        FeFlujonormal fn = new FeFlujonormal();
        fn.setOrden(row + 2);
        feFlujoNormalList.add(row + 1, fn);

        for(int i = row + 2; i < feFlujoNormalList.size(); i++){

            FeFlujonormal feTemp = feFlujoNormalList.get(i);
            feTemp.setOrden(feTemp.getOrden()+1);
        }

        return null;
    }

EDIT:  I don't think it's a Primefaces issue, I get the same result with the following code:
<h:dataTable value="#{fichaExpandidaBean.feFlujoNormalList}" binding="#{table}" var="fn">
     <h:column>
        <f:facet name="header">Paso</f:facet>
        <h:outputText value="#{fn.orden}-"/>
     </h:column>
     <h:column>
        <f:facet name="header">Descripcion</f:facet>
        <h:inputText value="#{fn.descripcion}" style="width:98%;"/>
     </h:column>
     <h:column>
        <f:facet name="header">Acciones</f:facet>
        <h:commandLink style="margin: 5px;" action="#{fichaExpandidaBean.agregarFilaFlujoNormal(table.rowIndex)}">
           <f:ajax render="@form"/>
           <h:graphicImage title="Agregar fila abajo." value="/resources/imagenes/agregarFila.png" alt="AgregarFila"/>
        </h:commandLink>
     </h:column>
 </h:dataTable>


text:
Q: Replicate distribution image kurtosis I am trying to replicate one of the images from this post.
In particular I want to plot something similar to this image in matlab:

I.e. I  want these three differently peaked distributions, where the tails are very clear. Can someone help me with such a plot?
Code as of now:
y = normpdf(x,0,1);
plot(x,y)
y1 = tpdf(x,5);
hold on
plot(x,y1)
hold on
y2 = tpdf(x,1000)

A: The referenced post and graphic are misleading because they suggest that kurtosis somehow measures height and/or pointiness/flatness of the distribution, notions which have been thoroughly debunked. Rather, kurtosis is a measure of tailweight (or more specifically tail leverage), see https://stats.stackexchange.com/a/481022/102879 for a good place to start.
It is important to visualize the heaviness of the tails, but the standard histogram/density plot is inadequate for this purpose: The tails, even when heavy, are too close to zero to distinguish "light" from "heavy" in such graphs.  Instead, you can use the normal quantile-quantile plot. Tail heaviness is very easy to see in this plot, and there is a direct mathematical connection between the appearance of this plot and the kurtosis statistic.  See here: https://stats.stackexchange.com/a/354076/102879


text:
Q: Nested if statement not working correctly So I am making a project that allows a user to change their password in a database, one of the latter stages of the code which is that they must re-enter the correct password again in order for it to change is not working here it is:
if tblusers.locate('StudentID', sStudentID,[]) then
begin
  if soldpass = tblusers['Password'] then
  else
  begin
    showmessage('Incorrect Current Password');
    exit;
  end;
  tblusers.edit;
  tblusers['Password'] := snewpass;
  if snewpass <> sreenter then
  begin
    showmessage('Re-Enter your Password correctly');
    edtreenter.clear;
    exit;
  end
  else
    tblusers.post;
  showmessage('Password Successfully Changed');
end;

The problem is that last if statement is not working properly because they can re enter a totaly different password and it will still change it

A: you have to use small and capital letters. your text message is difficult to understand, don't use same words for different messages type.
var
  ...
  s_Msg : string;
begin
  if sOldPass <> tblUsers['Password'] then
    s_Msg := 'wrong password' // 'login failed', 'incorrect password' ...
  else
  begin
    ShowMessage('login successful'); // 'password is correct', 'login done' ...
    tblUsers.edit;

    if sNewPass <> sReenter then
    begin
      edtreEnter.clear;
      s_Msg := 're-enter password is incorrect'; // 'new password is wrong', 'please confirm your password' ...
    end
    else
    begin
      tblUsers['Password'] := sNewPass;
      tblUsers.post;
      s_Msg := 'password successfully changed';
    end;
  end;
  ShowMessage(s_Msg);
end;

A: So I have fixed the issue after consulting with my dad and him helping me better my code
This the the new code which works:
begin
  if soldpass = tblusers['Password'] then
  begin
    showmessage('Correct Current Password');
    tblusers.edit;
    if snewpass = sreenter then
    begin
      tblusers['Password'] := snewpass;
      tblusers.post;
      showmessage('Password Successfully Changed');
    end
    else
    begin
      showmessage('Re-Enter your Password correctly');
      edtreenter.clear;
      exit;
    end;
  end
  else
  begin
    showmessage('Incorrect Current Password');
    exit;
  end;
end


text:
Q: Change password in cakephp 2x I'm trying to make a simple password reset function that allows an administrator to change a users password and email them the new password. Everything works except the password never actually gets changed in the database. I found a lot of information about this topic but nothing has worked. Why is the password not being changed? I'm using Cakephp 2.1
I tried this:
public function auto_reset_password($id = null){
    $this->User->id = $id;
    $randomPass= $this->User->generatePassword();
    $randomPassHashed= $this->Auth->password($randomPass);
    $this->User->set('password', $randomPassHashed);
    $this->User->save();
    //email code....
}

and substituting this:
$u = $this->User->find('first', array(
    'conditions' => array('User.id' => $id)
));
//.....
$u['User']['password'] = $randomPassHashed;

My user modal has this beforeSave:
public function beforeSave() {
    if (isset($this->data[$this->alias]['password'])) {
        $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
    }
    return true;
}

A: A few things to look out for:

*

*in the database the "password" field should be named the same, otherwise it will not be saved

*$this->User->save() will try to validate your data before saving. Validation may fail if you have defined rules for not empty email or not empty username and so on. You really need to look at the result that save returns! (or you can disable validation like this $this->User->save( null, false ))

*use saveField() instead: $this->User->saveField( 'password', $randomPassHashed );

*make sure you're not double hashing as you do in the original question.


text:
Q: Как сделать "Вы уверены, что хотите закрыть приложение?" C#, .NET
Ну, как создать MessageBox и все такое, я знаю. Но как сделать так, чтобы по нажатию "Нет" форма не закрылась? И чтобы это все работало при нажатии на "красный крестик", то есть стандартную кнопку управления окном.
A: Нужно обрабатывать событие "FormClosing". При нажатии на красный крестик система посылает сообщение, что окно хотят закрыть. Если в обработчике сего события не отменят оное действие, окно закроется, посылая следующее сообщение "FormClosed", где уже ничего отменить нельзя.
Отменяется закрытие примерно так:
private void fMain_FormClosing(object sender, FormClosingEventArgs e)
{
    e.Cancel = true;
}

Ну а сообщение с вопросом встроить сюда - пара строк =)
A: private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (MessageBox.Show("Закрыть?", "Message", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
        e.Cancel = true;
    else
        e.Cancel = false;
}

A: В VB6 нужно обрабатывать событие Form_Terminate:
Private Sub Form_Terminate()
.
.
.
End Sub


text:
Q: How to be a MDM Vendor for iOS Did a lot of research on this. Saw several opinions, few say I need a Apple Enterprise account, few say I don't.
Having a MAC server would help? Do I need to have an enterprise account to be a MDM vendor. Any pointers would be great.
I saw the technical business document provided by MDM, but it was not explaining anything about the internal implementation of the server.
Any help would be great!

A: You do need an enterprise account, but I'm not sure whether you need to specifically request to be a vendor also. You don't need a Mac server.
As for the details of your request - are you talking about signing your 'customers' certificate signing request which is a required step now in order to be a vendor or actually setting up and running an MDM service?

A: After research, we need to have a Enterprise Developer account from Apple, and we need to send MDM payload, from the web server, using Apple's push notification server.

A: To become an MDM vendor, you need:
1) An Apple Enterprise account
2) Contact Apple (https://developer.apple.com/contact/submit.php) and ask to be an MDM vendor.
They should enable you as an MDM vendor and you will have a "Other" tab in your "Certificates" section to send a Cert. Signing Request for MDM purposes.


text:
Q: Aptana not copying files to external server I just set up Aptana and have configured the Apache testing server in the folder C:\Apache\htdocs. When I try to test a simple HTML file I am directed to localhost/myproject/myfile.html but I get a 404 error. Upon inspecting the folder I find it empty. If I put a file in that folder the external server displays it just fine, but Aptana is not loading the files on the testing server when I attempt to run them. Any ideas? I know it's something simple, but I can't seem to figure out the problem.
Thanks,
Rob

A: The solution I discovered for this seems like a workaround but may be the only way to perform the task. I simply set up the localhost server just as if I was publishing the site to a remote location. Of course, the files don't update automatically when viewed like Dreamweaver does, but it works.

A: I discovered the best solution to this problem. I discovered I needed to install an FTP server on the local machine. I installed and configured Filezilla server and voila - problem solved. The only tip I'd add is to make sure to set the permissions properly for the folder or you'll run into errors.


text:
Q: Faithful Group Actions and Normal Subgroups Let $G\curvearrowright X$. Show that $K=\{g\in G:g\cdot x=x,\text{ for all }x\in X \}\trianglelefteq
G$. If $\phi\colon G\to Sym(X)$ is the homomorphism given by the
action, show that $K=\ker(\phi)$.
Let $G\curvearrowright X$ and let $K$ be as above. Show that
$\frac{G}{K}$ acts faithfully on $X$.
Attempt at solution: We want to show that $K = ker(\phi)$ The $ker(\phi)$ has already been show to be a normal subgroup. Also, by definition above we can see that $K$ is not faithful as it has more than one element that acts as the identity.
Take any element $g \in G$ and $x \in X$ Then by definition $g \cdot x = x$ but if we choose different elements $g_1 \in G$ and $x_1 \in X$ then we also get $g \cdot x_1 = x_1$ This is where I am stuck with writing the proof.
In part B when we kill the kernel of $G$ this makes only the identity map to the identity, as this group action now becomes faithful.

A: First of all, $G$ may act faithfully on $X$. It was not stated that $K$
had more than one element. Next $g\in K\iff gx=x,\forall\,x\in X\iff \phi(g)=\text{id}_X\iff g\in\ker(\phi)$.

A: Hints:
For any $\;k\in K\,,\,g\in G\;$ :
$$k\in K\implies k(gx)=gx\;,\;\;\forall\,g\in G\,,\,x\in X\implies $$
$$\implies g^{-1}kg(x)=g^{-1}(kg(x))=g^{-1}gx=1\cdot x= x\implies g^{-1}kg\in K\implies K\lhd G$$
As for (b):
$$(gK)x:=g(x)=x\iff g\in K\iff gK=\overline 1\iff\;\text{the induced action's faithful}$$


text:
Q: Running C# Interop Control ActiveX on Client Side from ASP.NET I am trying to make a simple web application using ASP.NET and Interop COM.
The main question is: How to make Interop COM works in client side?
I am Using:
IIS Windows Server 2008
C# Interop COM - Visual Studio 2010
Asp .NET - Visual Studio 2010
After looking at these articles http://msdn.microsoft.com/en-us/library/aa479302.aspx and http://msdn.microsoft.com/en-us/magazine/cc301832.aspx. I tried to use the component on the client side in two ways:
First:
<object id="Obj" codebase="MyApp.dll#version=1,0,0,0" classid="clsid:C6659361-1625-4746-931C-36014B146679" VIEWASTEXT></object>
    <script type="text/javascript" >
        function test() {
            alert('TEst');
            Obj.PrintHi();
            alert('and');
        }
    </script>

Second:
in .aspx
<object id="Obj" codebase="MyApp.dll#version=1,0,0,0" classid="clsid:C6659361-1625-4746-931C-36014B146679" VIEWASTEXT></object>

and in .cs file:
RegisterClientScriptBlock("showSaveMessage", "<script language=\"JavaScript\"> Obj.PrintHi();  </script>");

In server side I open Internet Explorer and works like a charm. But in client side appears: Object doesn't support this property or method.
I also tried:
<%
    set Obj = CreateObject("MyApp.MyClass")

    Obj.PrintHi
%>

Works for both side, but only call MyApp.dll installed on the server side.
Using 'object tag' is the correct way? Is there another way to use COM in client side? How to configure IIS to avoid Object doesn't support this property or method in client side?
Thanks in Advance
1# Update
I create ASP.NET C# in Visual Studio 2010 on Windows XP 32bits that uses a C# Interop COM.
On my machine "Windows XP" I do Start Debugging and IE page opens with my application. This works.So I copied the project to Windows Server 2008 and added the project in IIS. When I run IIS opens IE and this works.After this I tried to make the final test, So I open the IE on Windows XP and type the address that Windows Server generated, fine, I can see the page, but when I click to run the function, Appears: "Object does not support this property or method".
Server:
Windows 2008 R2 64bits
IE version 9
Client:
Windows XP 32bits
IE version 8
2# Update
I tried another test
I made a new Component COM
IClassTest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace MyCOM
{
    [ComVisible(true)]
    [Guid("8F388924-7743-4166-993F-CBF897D08A8B")]
    public interface IClassTest
    {
        string getString(string str);
    }
}

ClassTest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace MyCOM
{
    [ComVisible(true)]
    [Guid("1AE4AD64-A951-4E6C-8600-AA1F08810DDD")]
    public class ClassTest : IClassTest
    {
        public string getString(string str)
        {
            return str + "1";
        }
    }
}

In AssemblyInf.cs has [assembly: ComVisible(true)]
I made another asp application:
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="asp_test._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<object id="Obj" codebase="MyCOM.dll#version=1,0,0,0" classid="clsid:1AE4AD64-A951-4E6C-8600-AA1F08810DDD" VIEWASTEXT></object>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

<script type="text/javascript" >
    function test() {
        var test = Obj.getString('2');
        alert(test);
    }
    </script>
    <input name="btnTest" value="Call COM" onclick="test()" style=" width: 400px;" type="button">
</asp:Content>

I change IE settings to display ActiveX not trust and run the program.
In windows XP works, In Windows Server works. But when try to call the page from windows XP "Windows XP call Windows 2008 page" appears: "Object doesn't support this property or method"
If on client side I do regasm /u MyCOM.dll the IE prompted to install the component.
The dll is stored in the C:\WINDOWS\Downloaded Program Files, if I try to install more than once, creates a folder called CONFLICT.1.. C:\WINDOWS\Downloaded Program Files\CONFLICT.1 very strange. I also tried to register this downloaded component with regasm MyCOM.dll /codebase.
Server .NET: C:\Windows\Microsoft.NET\Framework\v4.0.30319
Client .NET: C:\Windows\Microsoft.NET\Framework\v4.0.30319
Why not work? It makes no sense.
3# Update
I ran on another machine "Client". I change IE settings to run not safe ActiveX. And Works, After this I tried on Windows XP Client I reseted the settings and set up again to run ActiveX not safe. This Works.
Now the problem is related to Install Interop COM from ASP. I tried to install but appears: Object doesn't support this property or method. I think it is related to Safe Inicialization. I found this link: http://msdn.microsoft.com/en-us/library/aa751977.aspx#iobjsafe but is for C++, Is there C# examples?
4# Update
I tried to use:
public class ClassTest : System.Windows.Forms.UserControl, IClassTest
I also tried to do a .cab file but does not work.
Have I to make wpf project? Why this does not work?

A: I found the solution: Deploy C# ActiveX in a CAB for Internet Explorer use
I did the following:
Strong-named the assembly.
Created an INF file
Created an MSI using the Visual Studio 2010 "Setup Project" template.
Created a CAB file using "Makecab.exe"
See this link for details to mark as safe for scripting
http://www.olavaukan.com/2010/08/creating-an-activex-control-in-net-using-c/
I was searching wrong, not is Component COM C# and yes C# ActiveX Control. I confuse with ATL COM C++.
Thank you

A: To get something working like this on the client side, provided it can be done with the security settings on the client machine, you have to have the DLL registered. Considering this requirement to make your website work, I would think a windows application of some type (winForms, WPF, even newer Silverlight) might be a better option as you can make sure the COM bits (or native bits, in cases where using native) are installed.
One issue with COM is the identifier has to be registered (i.e. in the registry) to work, as that is the only pointer Windows has to find the bits.