Q: Problems with itemRollOver and itemRollOut events on List component I have set the itemRollOver and itemRollOut event listeners on a List component, but whenever I roll the mouse over a list item, both the over and out events of the same list item fire in succession right after each other. My list uses a custom itemRenderer.
Any ideas why this might be? The Adobe documentation doesn't provide much insight into this (not surprisingly...).

A: In my opinion this is a bug. The ListBase.mouseOverHandler now sets a variable called lastHighlightItemRendererAtIndices when it dispatches an ITEM_ROLL_OVER event, which is then used (together with lastHighlightItemIndices) when dispatching an ITEM_ROLL_OUT event in ListBase.clearHighlight (called by the mouseOutHandler).
The problem is that when you mouse from row-to-row the mouseOverHandler is called first, setting the lastHightlight... variables, and then when the mouseOutHandler gets called subsequently, it uses the lastHighlight... values that were just set with the result that you get consecutive 'roll over' and 'roll out' events for the same renderer.
Frankly I don't know why ListBase.clearHighlight just doesn't use the passed in renderer when dispatching the ITEM_ROLL_OUT event (which is how it used to work in SDK 2) as this is the actual renderer that is being 'rolled out of'.

A: Are they coming from the same object?
If not you will it is likely so that you will get an itemRollOut from the "item" you just left and a itemRollOver from the new one you entered, depending on their spacing and such these may fire very close to each other.

A: Make sure you are setting super.data in your item renderer if you are overriding set data().
ListBase listens for MOUSE_OVER and then figures out the item underneath it based on coordinates of mouse and the position of the item renderer. You could check ListEvent.itemRenderer to see which renderer's roll over and roll out are firing and in what order.
Worst case, you could listen for rollOver and rollOut inside your item renderer.

A: Had the same problem. super.data was already being set, and the item is the same for the rollOut and rollOver event. I ended up opting for anirudhsasikumar's worst case scenario, and listened for rollOver and rollOut inside the item renderer. Seems to work fine.

A: I was having this same issue. I ended up subclassing the mx.controls.List class and overriding the clearHighlight function. As far as I can tell, the lastHighlightItemIndices variable is only ever read in that function. So doing something like the following fixed this issue:
import mx.core.mx_internal;

use namespace mx_internal;

public class List extends mx.controls.List
{
    public function List()
    {
        super();
    }

    override mx_internal function clearHighlight( item:IListItemRenderer ):void
    {
        var uid:String = itemToUID( item.data );

        drawItem( UIDToItemRenderer( uid ), isItemSelected( item.data ), false, uid == caretUID );

        var pt:Point = itemRendererToIndices( item );

        if( pt )
        {
            var listEvent:ListEvent = new ListEvent( ListEvent.ITEM_ROLL_OUT );

            listEvent.columnIndex = item.x;
            listEvent.rowIndex = item.y;
            listEvent.itemRenderer = item;

            dispatchEvent( listEvent );
        }
    }
}

Then just use this List class instead of the Adobe one and you'll have the behavior you expect. I tested this against Flex SDK 3.2 and it works.
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:controls="com.example.controls.*">

    [ other code ... ]

    <controls:List itemRollOver="onItemRollOver( event )" itemRollOut="onItemRollOut( event )" />

</mx:Canvas>

Thanks to Gino Basso for the idea in the post above. Hope that helps.

A: Thanks for the solution. That really solved the problem! Small correction, though:
listEvent.columnIndex = item.x;
listEvent.rowIndex = item.y;

should be
listEvent.columnIndex = pt.x;
listEvent.rowIndex = pt.y;

item.x and y hold the coordinate of the renderer in pixels.


Q: Get metadata column value in SPD Workflow How to get metadata column value in SharePoint Designer Workflow 2010 or 2013 ?

A: For getting metadata column in SPD, create one calculated column for metadata and then get calculated column in workflow.

A: This is a related question also asked around the same topic.
Here is a good resource around Parsing managed metadata value for sharepoint designer workflows
A typical structure would be something like “TX | c61d9028-824f-446e-9389-eb9515813a42”
Basically, you have to

*

*Pick the value from the column

*Split the value based on |

*Copy the zeroth index element to the destination variable and trim it.

To get the field in SPD wf -

*

*Choose action  - set variable to value

*In the value section (popup when you click value)- choose the data source as the list which you are fetching the column from -

*In the field from source - choose the managed metadata column internal name

*In the find in the list item section - choose the field tp be ID and value to be CurrentItem -> ID (should look like CurrentItem.ID)

*Click on OK. This should get you value of the managed metadata column.

*If you want, you can use the action Log item to the history list to check the value.

Note -
You need to search on the basis of the internal name of the column. In order to find out the internal name of the column - Go to - List -> List Settings -> Scroll Down to Columns Section -> Click on the Managed Metadata Column The url should look something like this -

http://.sharepoint.com/_layouts/FldEditEx.aspx?List=%7B5G5AD447-B908-4023-B622-52D04E9583F0%7D&Field=Managed Column

The Field's value is the internal name of the column


Q: Issue validating App using Sphero SDK in Xcode 7.1 beta (7B75) I'm having an issue validating an iOS 9 app (via the Organizer window) in Xcode 7.1 beta (7B75) that links to the latest RobotKit and RobotUIKit frameworks available from the Sphero Developer site.
The validation fails with a message, and here's contents of the IDEDistribution.critical.log:
2015-10-06 21:55:03 +0000 [MT] Failed to generate distribution items with error: Error Domain=DVTMachOErrorDomain Code=0 "Found an unexpected Mach-O header code: 0x72613c21" UserInfo=0x7fb9a236fb40 {NSLocalizedDescription=Found an unexpected Mach-O header code: 0x72613c21, NSLocalizedRecoverySuggestion=}
2015-10-06 21:55:03 +0000 [MT] Presenting: Error Domain=DVTMachOErrorDomain Code=0 "Found an unexpected Mach-O header code: 0x72613c21" UserInfo=0x7fb9a236fb40 {NSLocalizedDescription=Found an unexpected Mach-O header code: 0x72613c21, NSLocalizedRecoverySuggestion=}
As a test, I deleted both Sphero embedded frameworks from the .xcarchive file that is being validated, so the issue points to something in those underlying frameworks. Does anyone have any pointers?

A: I have an update. The issue turned out to be simple in hindsight. I added both the RobotUIKit and RobotKit frameworks to the "Embedded Binaries" section of the General tab for my target app in Xcode. They should ONLY be added to the "Linked Frameworks and Libraries" section. The Sphero framework is a pre-iOS 8 framework and thus appears to be statically linked.


Q: Is "looked at me funny" correct grammar? The following phrases:

Looked at me funny
Looking at me funny

Don't sound grammatically correct, but I hear them as turns of phrase relatively frequently. It should be something like:

Looked at me funnily
Looking at me funnily

Right?
But then the original sentiment of the phrase seems lost, as it's so seldom used. Is it valid for the adjective "funny" to implicitly modify the noun "the look" that is being received, or is this just another case of standardised bad grammar?

A: Yes, it is correct, though it is arguably restricted to informal speech and writing.
Funny is here an adverb, with the meaning 'in an odd or peculiar way'. This usage is recorded e.g. in the Merriam-Webster dictionary (you'll need to scroll down to the meaning of the word as an adverb). It is also recorded in the OED, with the note regional and colloq.


Q: Families of ordinary Siegel Modular Forms I'm looking for references to constructions and treatments of Hida Families/Eigenvarieties for ordinary Siegel modular forms (In particular: genus 2).
So far I've been reading Richard Taylor's thesis and would like to find more.
Thanks in advance.

A: This is a very rich and active subject. There are lots of different approaches to the problem, giving more or less strong results -- you can try to interpolate any or all of { Hecke eigenvalues, Fourier coefficients, L-values, Galois representations }, for forms satisfying various different flavours of finite-slope condition, while the weight varies in families having different numbers of parameters. Here are a selection of the important works on this:

*

*For ordinary families appearing in Betti cohomology, see Tilouine--Urban, "Several-variable $p$-adic families of Siegel-Hilbert cusp eigensystems and their Galois representations", Ann Sci ENS, 1999.

*For non-ordinary families appearing in functions on a compact form of $Sp(4)$, try the PhD thesis of Daniel Snaith (aka "Caribou"), (Imperial College, early 2000's).

*For a coherent-cohomology approach, more in the style of Coleman's work for $GL(2)$, try Andrei Jorza's thesis (Princeton, 2010), or for rather stronger results Andreatta--Iovita--Pilloni (Annals, this year).

These are just the references I know that treat Siegel modular forms specifically; there are other references that treat general reductive groups from which one can extract something for $Sp(4)$.


Q: Create lists of nodes from rows of matching pairs Not sure if this can be done with pandas or if I need to write a loop with some logic.
I have some data representing chains of pairs of nodes:
pairs = [
    # A1 -> B1 -> C1
    {'source': 'A1', 'target': 'B1'},
    {'source': 'B1', 'target': 'C1'},
    # A1 -> D1
    {'source': 'A1', 'target': 'D1'},
    # C2 -> A2 -> B2
    {'source': 'C2', 'target': 'A2'},
    {'source': 'A2', 'target': 'B2'},
]

And I want to resolve those chains to create the list of nodes they contain:
results = [
    ['A1', 'B1', 'C1', 'D1'],
    ['C2', 'A2', 'B2'],
]

So far I have this code which does allow me to match some of those nodes together:
def pair_nodes(df, src, tgt):
    df = df.groupby([src]).agg({tgt: 'unique'}).reset_index()
    df['nodes'] = df.apply(lambda r: np.append(r[src], r[tgt]), axis=1)
    return df

df1 = pair_nodes(df, 'source', 'target')
df2 = pair_nodes(df, 'target', 'source')
print(df1)
print(df2)

Which gives me:
  source    target         nodes
0     A1  [B1, D1]  [A1, B1, D1]
1     A2      [B2]      [A2, B2]
2     B1      [C1]      [B1, C1]
3     C2      [A2]      [C2, A2]
  target source     nodes
0     A2   [C2]  [A2, C2]
1     B1   [A1]  [B1, A1]
2     B2   [A2]  [B2, A2]
3     C1   [B1]  [C1, B1]
4     D1   [A1]  [D1, A1]

And I'm a stuck there. What I guess I'm missing is to merge rows from df1 and df2 whenever source or target is found in nodes
I had a look at df.merge but it only seems to work for exact key match.
Can this be achieved with pandas or do I need to write a custom loop/logic to do this?

A: Creating the desired result with merging dataframes can be a complicated process.
The above used login of merging will not be able to satisfy all types of graphs. Have a look at the below method.
# Create graph
graph = {}
for pair in pairs:
    if pair['source'] in graph.keys():
        graph[pair['source']].append(pair['target'])
    else:
        graph[pair['source']] = [pair['target']]

# Graph
print(graph)
{
    'A1': ['B1', 'D1'],
    'B1': ['C1'],
    'C2': ['A2'],
    'A2': ['B2']
}

# Generating list of nodes
start = 'A1' # Starting node parameter
result = [start]
for each in result:
    if each in graph.keys():
        result.extend(graph[each])
    result = list(set(result))

# Output
print(result)
['A1', 'B1', 'C1', 'D1']


Q: iTunes connect update limited to some countries? I have an app available for multiple countries; and now I need to release an update only to some of this countries.
Example
An app available for the whole world, is going to get an update, but it should only be available for USA users for instance.
Is it possible to release this update only to the USA store, or somehow limit it?
Thanks in advance.

A: If you limit the app to any geographical extent, then current users will be able to use it, but it won't appear to anyone on iTunes.
So, if you wanted an update for some region while having the previous version available, the answer is no, there's no way to do that.
@skorulis I find many reasons why you could want to do so, e.g. incremental release of the app update amongst many others.


Q: UIImageView.image not loading I have a strange issue with loading an imageview into a UITableViewCell during:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

here is my code:
    UIImageView *title = [[[UIImageView alloc] initWithFrame:CGRectMake(0,10,300,150)] autorelease];

    title.image = [UIImage imageNamed:@"featured_graphic.png" ];
    title.contentMode = UIViewContentModeScaleAspectFill;
    title.alpha = 1.0;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

its inside this:
 if( [indexPath isEqual:[NSIndexPath indexPathForRow:0 inSection:0]] )
 {
 }

I verified that featured_graphic.png is in my application.

A: You make the title but you don't actually add it to the view.
[cell.contentView addSubview:title];


Q: How to update column name after finding the table names from information schema I have run a script to find the table names with a specific column name from a database using the information schema
here is the query
  use IMS_SCMS_DIGITAL_POWER
  select * from information_schema.columns
  where column_name like 'COMPANY_ID%'

after finding the table names now i would like to update the specific column values of all the database. Need solutions.

A: Run following query to get all tablenames with specific column name
SELECT t.name AS TableName
FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%COMPANY_ID%'

just use in forward only cursor with tablenames to update the specific table.


Q: Angular PWA implementation on a specific component of angular Successfully converted my app into PWA but what I wanted to achieve is, I wanted that install option start visible from localhost/employee/dashboard not from localhost/.
What I tried so far is:
I put the URL (employee/dashboard/) in the starting URL of menifest.json, but what I achieve by this is it still showing the install option from the localhost/ but on installing it start PWA screen from localhost/employee/dashboard which is not what I wanted.
What I wanted:
I know to achieve this what I have to do is to put  in the index.html of that component, but my project is not in simple html,css,js where every component have a  tag where I put  and it starts giving install option from there. It is angular, can I somehow achieve this.


Q: np.transpose behavior different for different array constructions I came across this weird behavior with np.transpose wherein it works differently when used on an numpy array and array constructed from a list. As an MWE following code is presented.
import numpy as np

a = np.random.randint(0, 5, (1, 2, 3))
print(a.shape)
# prints (1, 2, 3)
b = np.transpose(a, (0, 2, 1))
print(b.shape)
# prints (1, 3, 2), which is expected

# Constructing array from list of arrays
c = np.array([np.random.randint(0, 5, (2, 3)), np.random.randint(0, 5, (2, 3)), np.random.randint(0, 5, (2, 3)), np.random.randint(0, 5, (2, 3))])
print(c.shape)
# prints (4, 2, 3)
d = np.transpose(c, (2, 0, 1))
print(d.shape)
# prints (3, 4, 2), whereas I expect it to be (2, 3, 4)

I do not understand this behavior. Why is it that the array constructed from the list has the dimensions mixed up? Any help is appreciated.

A: np.transpose() picks the dimensions you specify in the order you specify.
In your first case, your array shape is (1,2,3) i.e. in dimension->value format, it is 0 -> 1, 1 -> 2 and 2 -> 3. In np.transpose(), you're requesting for the order 0,2,1 which is 1,3,2.
In the second case, your array shape is (4,2,3) i.e. in dimension->value format, it is 0 -> 4, 1 -> 2 and 2 -> 3. In np.transpose(), you're requesting for the order 2,0,1 which is 3,4,2.


Q: How can Apache Camel be used to monitor file changes? I would like to monitor all of the files in a given directory for changes, ie an updated timestamp. This use case seems natural for Camel using the file component, but I can't seem to find a way to configure this behavior.
A uri like:
file:/some/directory

will consume the files in the provided directory but will delete them.
A uri like:
file:/some/directory?noop=true

consumes each file once when it is added or when the route is started.
It's surprising that there isn't an option along the lines of
consumeOnChange=true

Is there a straightforward way to monitor file changes and not delete the file after consuming?

A: You can do this by setting up the idempotentKey to tell Camel how a file is considered changed. For example if the file size changes, or its timestamp changes etc.
See more details at the Camel file documentation at: https://camel.apache.org/components/latest/file-component.html
See the section Avoiding reading the same file more than once (idempotent consumer). And read about idempotent and idempotentKey.
So something alike
from("file:/somedir?noop=true&idempotentKey=${file:name}-${file:size}")

Or
from("file:/somedir?noop=true&idempotentKey=${file:name}-${file:modified}")

You can read here about the various ${file:xxx} tokens you can use: http://camel.apache.org/file-language.html

A: Setting noop to true will result in Camel setting idempotent=true as well, despite the fact that idempotent is false by default.
Simplest solution to monitor files would be:
.from("file:path?noop=true&idempotent=false&delay=60s")

This will monitor changes to all files in the given directory every one minute.
This can be found in the Camel documentation at: http://camel.apache.org/file2.html.

A: I don't think Camel supports that specific feature but with the existent options you can come up with a similar solution of monitoring a directory.
What you need to do is set a small delay value to check the directory and maintain a repository of the already read files. Depending on how you configure the repository (by size, by filename, by a mix of them...) this solution would be able to provide you information about news files and modified files. As a caveat it would be consuming the files in the directory very often.
Maybe you could use other solutions different from Camel like Apache Commons VFS2 (I wrote a explanation about how to use it for this scenario: WatchService locks some files?

A: I faced the same problem i.e. wanted to copy updated files also (along with new files). Below is my configuration,
public static void main(String[] a) throws Exception {

    CamelContext cc = new DefaultCamelContext();

    cc.addRoutes(createRouteBuilder());

    cc.start();

    Thread.sleep(10 * 60 * 1000);

    cc.stop();
}

protected static RouteBuilder createRouteBuilder() {
    return new RouteBuilder() {
        public void configure() {
            from("file://D:/Production"
                    + "?idempotent=true"
                    + "&idempotentKey=${file:name}-${file:size}"
                    + "&include=.*.log"
                    + "&noop=true"
                    + "&readLock=changed")

            .to("file://D:/LogRepository");
        }
    };
}

My testing steps:

*

*Run the program and it copies few .log files from D:/Production to D:/LogRepository and then continues to poll D:/Production directory

*I opened a already copied log say A.log from D:/Production (since noop=true nothing is moved) and edited it with some editor tool. This doubled the file size and save it.

At this point I think Camel is supposed to copy that particular file again since its size is modified and in my route definition I used "idempotent=true&idempotentKey=${file:name}-${file:size}&readLock=changed". But camel ignores the file.
When I use TRACE for logging it says "Skipping as file is already in progress...", but I did not find any lock file in D:/Production directory when I editted and saved the file.
I also checked that camel still ignores the file if I replace A.log (with same name but bigger size) in D:/Production directory from outside.
But I found, everything is working as expected if I remove noop=true option.
Am I missing something?

A: If you want monitor file changes in camel, use file-watch component.
Example -> RECURSIVE WATCH ALL EVENTS (FILE CREATION, FILE DELETION, FILE MODIFICATION):
from("file-watch://some-directory")
.log("File event: ${header.CamelFileEventType} occurred on file ${header.CamelFileName} at ${header.CamelFileLastModified}");

You can see the complete documentation here:
Camel file-watch component


Q: How to reduce size of all PPT/PPTX files in folder? I have 1000+ PPT/PPTX files, how to reduce size of them all? It's OK if resolution of images goes down or history is gone. As long as current on slides text is preserved and images are recognizable, everthing is fine.


Q: What purpose does the Fortune Teller serve? So I'm assuming the Fortune Tellers predictions about chance impact some RNG in the game, but I'm really not sure what RNG it impacts, since there is quite a few things I can think of (chance for rare crops, chance for minerals to appear in the mines, chance for fish to bite, et cetera).
So what do the Fortune Tellers predictions impact?

A: *

*Geodes - there were threads all over claiming their contents was impacted by luck.  However Tallian linked this thread on reddit in the comments that suggested otherwise.  The OP could be better worded, so I'll restate.  What you get out of Geode's appears to be deterministic.  I did a very small test last night and opened a couple of geodes, force closed the game, and then opened them again.  I got the same set of things in the same order both times. So it appears Geode content is set in some manner.  It also might be true that it's deterministic by type, as per this comment in the thread (essentially, that the type of geode + the "nth Geode opened" is what determines the drop).  Unfortunately I only had basic Geodes on hand for my test.  There have been arguments that what a Geode contains is set when the Geode drops.  However nobody has found evidence in the save files, which contain lots of information about the things your character possess.  So I would say Geode contents are not affected, but Geode drop rate probably is.

*Drops in the Journey of the Prairie King arcade game in the Saloon.  I haven't played the other game but if it has drops then it affects those as well.

*What you find in the mines.  A good fortune means you are more likely to find a stair under a rock.  I believe it impacts the spawn rate of rocks with ore/minerals in them as well.

*Fishing.
Obviously a bad fortune works against you while a good fortune works for you.
Crops @JohnDubya says he has read that fortune impacts crops.  I can't offer much in the way of evidence on this one, but here goes.  I've put something like 14+ seasons of crop growing into this game (less a couple of winters without the greenhouse) and as I tend to harvest as soon as possible and use quality fertilizers I can't speak much to whether luck might be impacting harvesting.  In my current game's green house, I only use speed growth fertilizers (I'm increasing my base for star, ancient, and rare seeds).  I pulled two ancient fruit the other day and got a silver and a gold despite it being a worst-luck day.  I almost always get some quality out of the crops there and I know I have harvested on a series of bad luck days over the past in-game month (as I'm just building up a seed base I don't have any steady crop rotations; most times I harvest in batches of 2-6 plants).  In my very humble opinion, waiting for a "good luck" day to harvest is a bad idea even if it impacts the quality of what you harvest unless one is well into the game and has a terrific economic base.  Plant with Quality Fertilizer instead and there will be plenty of gold starred crops.

A: I find it much easier to find stair down in the mine on my fortunate day, and the opposite when not. The monster spawning is affected too. I can descend some 5 floors in a few hours when my luck is high, while it can take entire day and got killed on my non-lucky day.
I think the fishing is also affected, but I haven't been keeping track much in this case.

A: Just a small update about the mines and the staircase. The staircase in a mine is not random. It will always be the same for that one floor. The luck value doesn't affect it.


Q: For which $\alpha$ do limits for $F(a,b)= \int_A||x||_2^\alpha dx$ exist? I have a function $$F(a,b)= \int_A||x||_2^\alpha dx$$ where $||x||_2$ denotes the euclidean norm and $A = \{x\in \mathbb R^2: a\leq ||x||_2 \le b\}$ and I would like to find all $\alpha$, for which the limits $\lim_{a \to 0} F(a,1)$, $\lim_{b\to \infty} F(1,b)$ and $\lim_{a\to 0}\lim_{b\to \infty} F(a,b)$ exist.
I have already solved a similar excercise for the one dimensional case, but I do not know how to proceed with this one. Since this is two dimensional, I am having troubles knowing what to do. So far, all I have learned about multidimensional integration is Fubini's theorem. The main problem I am having here is that I do not know how I would even integrate the above term, for a given $\alpha$. I know that I can use double integration for "square" intervals, but in this case $A$ is a circle, which confuses me even further. What can I do here? Any help is greatly appreciated!

A: To start this problem, you want to change your basis. As you said, you're integrating over an annulus (a flat donut, like a circle with an inner circle cut out). In this case treating the plane with $x$ and $y$ is messy, the natural system to use is polar coordinates. If $u$ is some point in the plane expressed with polar coordinates, $\Vert u \Vert_2$ is simply equal to the radial component of $u$. The integral becomes:
$$\int_{0}^{2\pi}\int_{a}^{b}||x||_2^\alpha r\mathrm{d}r\mathrm{d}\phi = \int_{0}^{2\pi}\int_{a}^{b}r^{1+\alpha}\mathrm{d}r\mathrm{d}\phi$$
This is because you first want to integrate over the set of radial values for each $x$, and then the set of angular values. (Just like you would integrate over $x$ and then $y$.) You'll also see an extra $r$ that seems to have appeared out of nowhere. This is a factor that always appears in an integral when you convert from cartesian to polar, and intuitively occurs because if you integrate over a ring with $k$ times the radius of another ring, you expect there to be $k$ times as many "points" you're summing.
Now you'll realise you can integrate this: Assuming everything is well defined in this case, you get
\begin{align*}
\int_{0}^{2\pi}\int_{a}^{b}r^{1+\alpha}\mathrm{d}r\mathrm{d}\phi &= \frac{1}{2+\alpha}\int_{0}^{2\pi}\Big[r^{2+\alpha}\Big]_{a}^{b}\mathrm{d}\phi\\
&= \frac{1}{2+\alpha}\int_{0}^{2\pi}b^{2+\alpha}-a^{2+\alpha}\mathrm{d}\phi\\
&= \frac{2\pi}{2+\alpha}\big(b^{2+\alpha}-a^{2+\alpha}\big)
\end{align*}
Now that you know how to integrate it, I'm sure you'll be fine with the actual questions! Usually the best way to first learn calculus of this nature is through physics (especially electromagnetism).


Q: How to find a canonical member of an equivalence class of matrices under row and column swaps? Call two matrices "swap-equivalent" if one matrix can be transformed into the other via some sequence of row swaps and column swaps.
I'd like a computationally efficient algorithm that can transform a matrix into a canonical swap-equivalent matrix (so that all members of an equivalence class give the same result).
I've been first sorting the rows and then sorting the columns, using the following comparison function:
A list (row or column) $a$ is considered greater than a list $b$ if when sorted, $a$ comes before $b$ lexicographically, with ties broken by the lexicographic order of (unsorted) $a$ and $b$.
For example:
$\begin{matrix} 1 & 0 & 3 \\ 0 & 4 & 2 \\ 2 & 0 & 4 \end{matrix}$
becomes
$\begin{matrix} 2 & 0 & 4 \\ 0 & 4 & 2 \\ 1 & 0 & 3 \end{matrix}$
after sorting the rows, and then
$\begin{matrix} 4 & 0 & 2 \\ 2 & 4 & 0 \\ 3 & 0 & 1 \end{matrix}$
after sorting the columns.
This is efficient enough, but I haven't been able to figure out if it's right.
EDIT: Turns out this doesn't work.
$\begin{matrix} 2 & 1 & 0 \\ 1 & 0 & 2 \end{matrix}$
gets transformed to
$\begin{matrix} 2 & 0 & 1 \\ 1 & 2 & 0 \end{matrix}$
but
$\begin{matrix} 2 & 1 & 0 \\ 0 & 2 & 1 \end{matrix}$
gets transformed to
$\begin{matrix} 1 & 2 & 0 \\ 2 & 0 & 1 \end{matrix}$
even though they're equivalent.
Sorting the rows again fixes it though.  Is that enough?  Maybe iterate until a stable state is reached?

A: The question linked to by David Speyer in a comment has an answer that points out that this is equivalent to finding a canonical representation of a bipartite graph, since the matrices can be viewed as biadjacency matrices.  This problem is not known to be in P.  However, the nauty program can usually find such a form quickly.

A: Determining whether two matrices are swap-equivalent is the graph isomorphism problem for bipartite graphs -- which is asymptotically as hard as the graph isomorphism problem for general graphs (it is GI-complete).  There is no known algorithm with a worst-case polynomial running time, but there are algorithms that empirically seem to be efficient on most graphs you're likely to run into in practice.
You are asking for something a bit more: an algorithm to compute a representative for the equivalence class, i.e., a canonical form for the graph.  This is at least as hard as the graph isomorphism problem, and potentially harder.  However, the existing tools for graph isomorphism also tend to provide a way to do this as well.


Q: How do filters and hooks really work in PHP How does filters and hooks actually work in WordPress?
I'm asking about something advanced. How is it implemented in PHP? E.g how does it collect all the hooks from the different plugins and "attach" them to the core hooks etc.

A: Hooks are included in both the WordPress core files and some parent themes files. They enable you to hook in content in a specific location in the file.
An example is the wp_head hook in WordPress. You can use this hook in your child theme to add content in that location'
Example:
add_action('wp_head', 'add_content_to_head');
function add_content_to_head() {
echo 'Your Content';
}

Some premium themes also include action hooks which you can use in a child theme to do the same thing. Here's a visual map which includes all the the action hooks and the position they output your content in the Genesis theme framework.
Example:
add_action('genesis_header', 'add_content_to_header');
function add_content_to_header() {
echo 'Your Content';
}

Here's what the hook looks like if you opened the header.php file in the Genesis theme framework:
do_action( 'genesis_header' );

Here's a list of WordPress hooks you can use in many ways.
Filters enable you to modify the output of an existing function and is included in both the WordPress core files and some parent theme frameworks like Genesis.
Here's a list of the filters you can use with the Genesis Design Framework
Here's a list of the filters included in WordPress
Here's an example of how you can use a filter in a theme framework like Genesis:
add_filter( 'comment_author_says_text', 'custom_comment_author_says_text' );
function custom_comment_author_says_text() {
return 'author says';
}

The above code can be used in a child theme to modify the author says text in your comments. It works in any theme.
Here's another example which customizes the length of excerpts to 50 words:
add_filter( 'excerpt_length', 'change_excerpt_length' );
function change_excerpt_length($length) {
return 50;
}

You'll find the the_excerpt() function in the wp-includes/post-template.php file.
Here's what it looks like:
  function the_excerpt() {
        echo apply_filters('the_excerpt', get_the_excerpt());
}

You can also use hooks and filters in plugins to do exactly the same thing and the code won't be lost when you update the parent theme or WordPress.
Basically, hooks and filters enable you to customize and modify both WordPress and your parent theme without editing the core WordPress files or your parent theme files.
Its significantly easier to customize a child theme when the parent theme framework includes hooks and filters because you never need to edit the parent themes template files. This way you can safely change themes as well.

A: Overview
Basically the "Plugin API," which summons Filters and Hooks, consists out of the following functions:

*

*apply_filters() - execute

*do_action - execute

*apply_filters_ref_array() - execute

*do_action_ref_array() - execute

*add_filter() - add to stack

*add_action() - add to stack
Basic Internals
Overall there're a couple of globals (what else in WordPress world) involved:
global $wp_filter, $wp_actions, $wp_current_filter, $merged_filters;

The first one $wp_filter is a global Array that holds all filter names as subarrays. Each of those subarrays then holds even more subarrays that are callbacks summoned under a priority array.
Brief in-depth
So when an execute function is called, WordPress searches those globals arrays for the keys with that name. Then the attached callbacks get executed priority after priority. The only thing that happens up front are callbacks attached to the all filter.
When you add a callback using add_action or add_filter, then WordPress first calculates a "unique" ID to not overwrite already attached callbacks.
$idx = _wp_filter_build_unique_id($tag, $function_to_add, $priority);

Then it adds your callback to the global $wp_filter stack:
$wp_filter[ $tag ][ $priority ][ $idx ] = array(
    'function'      => $function_to_add,
    'accepted_args' => $accepted_args
);

As you can see the main sub array is the $tag (or action/filter name), then everything is summoned under a specific priority, and then the "unique" callback/ID string gets used as key.
Later, when a filter gets called - happening with the $tag/action-/filter-name - the array gets searched and the callbacks get called. As it is using call_user_func_array it doesn't really matter how many arguments are attached. WordPress resolves that by itself.
foreach ( (array) current( $wp_filter[ $tag ] ) as $the_ )
{
    call_user_func_array(
        $the_['function'],
        array_slice(
            $args,
            0,
            (int) $the_['accepted_args']
        )
    );
}


Q: What is helperGrowEdges function in MATLAB I was following a tutorial in matlab documentation at  http://www.mathworks.com/help/vision/examples/automatically-detect-and-recognize-text-in-natural-images.html
There they use a function helperGrowEdges but I it is not being recognized right now. I verified that I have Computer Vision System Toolbox. I am unable to figure how to implement it. It says it 'Grow the edges outward by using image gradients around edge locations', but I am unable to figure out how to implement is well.

A: As hinted out by Naveh, It works those functions are present only in MATLAB 2014 version and not in older versions.
Older versions do not have that example as well when I try to open edit TextDetectionExample

A: This example first appears in release R2014a.  helperGrowEdges is a helper function, which goes with the example.  Unfortunately it does not get published in the documentation.  The only way for you  to see it is to get access to an installation of MATLAB R2014a with the Computer Vision System Toolbox, and do edit helperGrowEdges.


Q: Lightweight pickle for basic types in python? All I want to do is serialize and unserialize tuples of strings or ints.
I looked at pickle.dumps() but the byte overhead is significant. Basically it looks like it takes up about 4x as much space as it needs to. Besides, all I need is basic types and have no need to serialize objects.
marshal is a little better in terms of space but the result is full of nasty \x00 bytes. Ideally I would like the result to be human readable.
I thought of just using repr() and eval(), but is there a simple way I could accomplish this without using eval()?
This is getting stored in a db, not a file. Byte overhead matters because it could make the difference between requiring a TEXT column versus a varchar, and generally data compactness affects all areas of db performance.

A: personally i would use yaml.  it's on par with json for encoding size, but it can represent some more complex things (e.g. classes, recursive structures) when necessary.
In [1]: import yaml
In [2]: x = [1, 2, 3, 'pants']
In [3]: print(yaml.dump(x))
[1, 2, 3, pants]

In [4]: y = yaml.load('[1, 2, 3, pants]')
In [5]: y
Out[5]: [1, 2, 3, 'pants']

A: Maybe you're not using the right protocol:
>>> import pickle
>>> a = range(1, 100)
>>> len(pickle.dumps(a))
492
>>> len(pickle.dumps(a, pickle.HIGHEST_PROTOCOL))
206

See the documentation for pickle data formats.

A: If you need a space efficient solution you can use Google Protocol buffers.
Protocol buffers - Encoding
Protocol buffers - Python Tutorial

A: Take a look at json, at least the generated dumps are readable with many other languages.

JSON (JavaScript Object Notation) http://json.org is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format.

A: There are some persistence builtins mentioned in the python documentation but I don't think any of these is remarkable smaller in the produced filesize.
You could alway use the configparser but there you only get string, int, float, bool.

A: "the byte overhead is significant"
Why does this matter?  It does the job.  If you're running low on disk space, I'd be glad to sell you a 1Tb for $500.
Have you run it?  Is performance a problem?  Can you demonstrate that the performance of serialization is the problem?
"I thought of just using repr() and eval(), but is there a simple way I could accomplish this without using eval()?"
Nothing simpler than repr and eval.
What's wrong with eval?
Is is the "someone could insert malicious code into the file where I serialized my lists" issue?
Who -- specifically -- is going to find and edit this file to put in malicious code?  Anything you do to secure this (i.e., encryption) removes "simple" from it.

A: Luckily there is solution which uses COMPRESSION, and solves
the general problem involving any arbitrary Python object
including new classes. Rather than micro-manage mere
tuples sometimes it's better to use a DRY tool.
Your code will be more crisp and readily refactored
in similar future situations.
y_serial.py module :: warehouse Python objects with SQLite
"Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Most useful "standard" module for a database to store schema-less data."
http://yserial.sourceforge.net
[If you are still concerned, why not stick those tuples in
a dictionary, then apply y_serial to the dictionary.
Probably any overhead will vanish due to the transparent
compression in the background by zlib.]
As to readability, the documentation also gives details on
why cPickle was selected over json.


Q: React get metamask latest transaction status I am using this, to make a function call in smart contract via metamask in react:
export default class EthereumForm1 extends Component {
  constructor (props) {
    super (props);
    const MyContract = window.web3.eth.contract(ContractABI);

    this.state = {
      ContractInstance: MyContract.at('ContractAddress')
    }
    this.doPause = this.doPause.bind (this);
}
  doPause() {
    const { pause } = this.state.ContractInstance;

    pause (
      {
        gas: 30000,
        gasPrice: 32000000000,
        value: window.web3.toWei (0, 'ether')
      },
      (err) => {
      if (err) console.error ('Error1::::', err);
      console.log ('Contract should be paused');
    })
  }

What I want is to run jQuery code with loading gif: $(".Loading").show();
while transaction is being processed and remove it after. Also, it would be good to add transaction status in div after, like in metamask(either passed or rejected).

A: What helped me was checking every few seconds if my transactiopn finished, and if yes hiding the loader.
if (latestTx != null) {
  window.web3.eth.getTransactionReceipt(latestTx, function (error, result) {
    if (error) {
      $(".Loading").hide();
      console.error ('Error1::::', error);
    }
    console.log(result);
    if(result != null){
      latestTx = null;
      $(".Loading").hide();
    }
  });
}

A: You don't need jquery to do this. React state can manage the status of the progress automatically. All you have to do is to call setState function.
class EthereumFrom1 extends React.Component {

    state = {
        loading: false
    };

    constructor(props) {
        super(props);

        this.doPause = this.doPause.bind(this);

    }

    doPause() {
        const {pause} = this.state.ContractInstance;

        pause(
            {
                gas: 30000,
                gasPrice: 32000000000,
                value: window.web3.toWei(0, 'ether')
            },
            (err) => {
                if (err) console.error('Error1::::', err);
                this.setState({loading: true});
            })
    }

    render() {
        return (

                {this.state.loading ?

                        Loading...

 :
done

                }

        )
    }
}


Q: my server it looking for a file, but i have a string, How would i simulate a fileupload via jquery i was curious if there was a way for me to set up an ajax call such that a string would be recognized as a file.
i essentially created a XML via javascript that is in string format, and want to upload it, but the server looks for a file.
I was thinking that i would have to post it to a webservice such that it would post to a iframe as file contents or something and then upload it that way or some other hack around it.
EDIT:  I was thinking this might be a solution?  Creating a fake file?  How to upload string as file with jQuery or other js framework

A: After looking at the same for how to upload a string as a file with Jquery and then looking at how the server processed the information.  I determined that the data saved doesnt nessicarily have to be that of a file.  When looking at responsees, all that information was in the string the next time it was pulled.  I actually just removed the data and pushed it up and it returned what i wanted.
var myData = {
   user: top.USERNAME,
   pass: top.PW_HASH,
   secure: true,
   url: top.BASE_URL,
   ext: "foo",
   data:saveXML
 };

which as you can see, the data being passed in the object to my $.ajax wrapper was just the saveXML.


Q: X Axis on graph in Power BI does not display full date range I am new at Power BI and created a column chart to display events for every month in a 13 month period. The X axis is displaying all the data, but the naming of the months is not correct as it skips every second month. Does anyone know where I can change this as I suspect it might only be a format change.
I have attached a screenshot to show the x axis.
Thank you!
enter image description here

A: Please go to X-axis in format tab in Visualizations and change type from Continuous to Categorical.
Type as Categorical
Create a calculated column as follows and sort it using Date field
MonthLabel = CONCATENATE(CONCATENATE(LEFT([Date].[Month],3)," "),Right([Date],4))
Hope this helps!
Best Regards,
Shani Noorudeen


Q: Here the class Main is throwing DERIVED without declaring Main as THROWS but it works, can anyone explain this Here the class Main is throwing DERIVED without declaring Main as THROWS but it works, can anyone explain this.
class Base extends Exception {}
    class Derived extends Base  {}
     public class Main {//main class throwing DERIVED
     public static void main(String args[]) {
       // some other stuff
       try {
           // Some monitored code
           throw new Derived();
        }
        catch(Base b)     {
           System.out.println("Caught base class exception");
        }
        catch(Derived d)  {
           System.out.println("Caught derived class exception");
        }
      }
    }


Q: How to find a substring in a cell array I am trying to use regexp in MATLAB to search for two words in strings in cell arrays. My cell array contains
strings={'1abc_2def_ghi_AB_12A','1abc_2def_ghi_BD_19A','1abc_2def_ghi_CD_16A',}

How would I go about constructing the expression to search the cell array for the string that contains both 'ghi' and '12'?
Thanks in advance for any assistance.

A: How about this?
result = find(~cellfun(@isempty, regexp(strings, 'ghi')) & ...
    ~cellfun(@isempty, regexp(strings, 'AB')));

Or, using a single regular expression,
result = find(~cellfun(@isempty, regexp(strings, '(ghi.*AB|ghi.*AB)')));


Q: addHTMLImage not working I am working on a project that sends out HTML emails to people after a forum is filled out, I have gotten the HTML portion of the code to work but for some reason cannot get the banner image to appear at the top when embedding the image into my code. I had it work before when I was working on the latest version of PHP but had to downgrade to PHP 5.3 in order for my scripts to run on our server. Since then I used the same code and it resulted in failure. I have tried many different methods and none have proven effective. Here is my code
    require_once('Mail.php');
    require_once('Mail/mime.php');

    $smtp_credentials = array('host' => 'smtp.postmarkapp.com', 'port' => 25, 'auth' =>          TRUE, 'username' => '*', 'password' => '*');

    $headers = array('From' => '*', 'To' => $email, 'Subject' => $subject);

    $mime = new Mail_mime(array('eol' => PHP_EOL));

    $file = '/*/*/*/dls.jpg';
    $mime->addHTMLImage(file_get_contents($file),'image/jpeg',basename($file),false, "blackstone");

    #I used this code to fish out the cid out of mime I tried echoing this out and
    # it returned blackstone which I defined as the 5th parameter of addHTMLImage which
    # sets the cid.
    $cid=$mime->_html_images[count($mime->_html_images)-1]['cid'];

    $banner = '

    ';

    $message_text = $banner;

    $mime->setHTMLBody($message_text);

    $mime->setTXTBody($body_text);

    $mail = Mail::factory('smtp', $smtp_credentials);

    try {
    $send = $mail->send($email, $mime->headers($headers), $mime->get());

    } catch (Exception $e) {

    echo $e->getMessage(); die;
    }

    echo 'mail sent!';

I have tried many different things, like not using cids at all which I would prefer since a lot of mail clients do not work well with cids, but on the PEAR manual it is suggested to use cid in the src attribute. I am using gmail, but I do not think this is the problem since it worked when I was running the newer version of php. whenever I open the email, the html portion of it works. Where the image should be there is a little image icon but no image is displayed.

A: The image url is supposed to be an absolute url.. not a path (relative or absolute).. it can't be a path, it must be a complete url to the image.
So you need to use a valid url such as the one below.
http://www.example.com/images/image-name.jpg
Something like the below would not work.
../path/to/images/image-name.jpg
and the same goes for below (it won't work):
/root/public/path/to/images/image-name.jpg
so make sure you are specifying a valid url to your image.


Q: How to set element invisible with animation? I have this toggle button that when it is on, calls an animation method that sets several elements visible. But when I turn it off, the elements remain visible, although the opposite instruction. How can I make them disapear with the same logic? Do I have to create another method? Thanks, here's the code:
 drum.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                key1.setVisibility(View.VISIBLE);
                key1.startAnimation(fadeInAnimation());

                key2.setVisibility(View.VISIBLE);
                key2.startAnimation(fadeInAnimation());

                key3.setVisibility(View.VISIBLE);
                key3.startAnimation(fadeInAnimation());

                rocking.setLooping(true);
                rocking.start();

                Toast.makeText(getApplicationContext(), "Rock and Rolling!", Toast.LENGTH_SHORT).show();
            } else {
                rocking.setLooping(false);
                key1.setVisibility(View.INVISIBLE);// These instrucions are ignored...
                key2.setVisibility(View.INVISIBLE);
                key3.setVisibility(View.INVISIBLE);

                Toast.makeText(getApplicationContext(), "Can't keep up? Try the tamborine!", Toast.LENGTH_SHORT).show();

            }
        }
    });

And the animation method:
private Animation fadeInAnimation() {
Animation animation = new AlphaAnimation(0f, 1.0f);
animation.setDuration(1000);
animation.setFillEnabled(true);
animation.setFillAfter(true);
return animation;
}

A: Change the fadeInAnimation and pass a boolean argument, if true do fade-In animation else fade-out animation. Code sample is given below. Usage fadeAnimation(true) for fadeIn animation and fadeAnimation(false) for fadeOut animation. Hope this helps.
private Animation fadeAnimation(boolean fadeIn) {

 Animation animation = null;
 if(fadeIn)
    animation = new AlphaAnimation(0f, 1.0f);
 else
    animation = new AlphaAnimation(1.0f, 0f);
 animation.setDuration(1000);
 animation.setFillEnabled(true);
 animation.setFillAfter(true);
 return animation;

}

A: Checkout below code
viewObject.animate()
            .alpha(0.0f)
            .setStartDelay(10000)
            .setDuration(2000)
            .setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    // do your stuff if any, after animation ends
                }
            }).start();

A: possible duplicate of View.setVisibility(View.INVISIBLE) does not work for animated view. visibility are not honoured as long as an animation is  performed even though  animation is cancelled


Q: what does allowLossyConversion mean in ios I am using the dataUsingEncoding(encoding: NSStringEncoding, allowLossyConversion: Bool = default) -> NSData? function to convert String to NSData, but I don't get what allowLossyConversion actually means.
Is it similar to Lossy compression? Can anybody help me understand this?

A: If flag is YES and the receiver can’t be converted without losing some information, some characters may be removed or altered in conversion. For example, in converting a character from NSUnicodeStringEncoding to NSASCIIStringEncoding, the character ‘Á’ becomes ‘A’, losing the accent.


Q: How can I set different session lifetime for each role? How can I set different session lifetime for each symfony role? Is there a built-in option for doing this?
We're using different roles, one for our clients and one for each department within our company. We'd like to increase session lifetime for company roles without increasing it for the clients role.

A: You would have to set the session lifetime for the role that has the highest, and then, saving dates on your database, log users out after the amount of time that you want.


Q: Angular component has click listener attribute How can I know within my-component, if the parent listens to the click event (A) or not (B).
Case A:
<my-component (click)="onClick()"></my-component>

Case B:
<my-component></my-component>

Definition:
@Component({
  selector: 'my-component',
  templateUrl: './my-component.component.html',
})
export class MyComponent {
  @???()
  hostHasClickListener: boolean;   // I want to know this within my component
}

Thank you!

A: You can achieve this by using an @Output with click as the name. This forces the consumers to bind their function to this click when they use (click)="Blah()" in the HTML.
this.click.observed return true when click is used in the HTML.
mycomponent.component.ts
@Component({
  ...
})
export MyComponent implements OnInit {

  @Output()
  public click = new EventEmitter();

  private _hasClick = false;

  public ngOnInit() {

     this._hasClick = this.click.observed;

     if(this._hasClick) {
       // do something here.
     }

  }
}


Q: Need to divide a single VF page into multiple tabs I have a query. I have single vf page which is having 15 fields. Is it possible to divide that page into 3 tabs and assign 5 fields to each of it.
If Yes, can anyone please provide me some sample.

A: You are probably looking for apex:tab (doc)
<apex:page standardController="Account" id="thePage">
    <apex:tabPanel switchType="client" selectedTab="name1" id="theTabPanel">
       <apex:tab label="One" name="name1" id="tabOne">
           <apex:outputField valie="{!Account.Name}" />
       </apex:tab>
       <apex:tab label="Two" name="name2" id="tabTwo">content for tab two</apex:tab>
       </apex:tabPanel>
       <apex:tab label="Three" name="name3" id="tabThree">content for tab three</apex:tab>
     </apex:tabPanel>
</apex:page>


Q: lxpanel volume control not visible plus no sound I installed Lubuntu on my laptop, and it is working extremely well. However, I cannot figure out how to add applets to the panel. In particular, I cannot add volume control, so I cannot figure out how to change my volume (which is currently muted).
Also, my function keys no longer work (which is not surprising). How can I make it so that I have control over the volume using the panel applet and my function keys?
Thanks for any replies.
Update: After testing this out with other applets, I found the problem is that volume control is not visible. How can I make it visible?
Update: I played with alsamixer and found I have no sound. How can I fix this?
Update: Here is the output of pulseaudio
E: [pulseaudio] module-alsa-card.c: Failed to find a working profile.
E: [pulseaudio] module.c: Failed to load module "module-alsa-card" (argument: "device_id="29" name="platform-thinkpad_acpi" card_name="alsa_card.platform-thinkpad_acpi" namereg_fail=false tsched=yes fixed_latency_range=no ignore_dB=no deferred_volume=yes use_ucm=no card_properties="module-udev-detect.discovered=1""): initialization failed.

A: I figured out how to fix the problem. For anyone else who has this problem: be sure to change the default volume card. Here is how you can do that:

*

*Type Ctrl + Alt + T to start LXTerm

*Type sudo leafpad /etc/asound.conf

*Type Enter

*Copy and paste

defaults.ctl.card 2
defaults.pcm.card 2
defaults.timer.card 2
into the file.
Change the number 2 to the sound card you want to use, then save the file and restart your computer.


Q: replace columns in hive I have created a table in hive, now I am trying to replace the columns name using REPLACE COLUMNS.
Alter query is:
**ALTER TABLE emp1 REPLACE COLUMNS (
id INT eid int,
name STRING ename string,
sal INT esal int,
city string ecity string,
country string ecountry string);**

MismatchedTokenException(26!=301)
    at org.antlr.runtime.BaseRecognizer.recoverFromMismatchedToken(BaseRecognizer.java:617)
    at org.antlr.runtime.BaseRecognizer.match(BaseRecognizer.java:115)
    at org.apache.hadoop.hive.ql.parse.HiveParser.alterStatementSuffixAddCol(HiveParser.java:9898)
    at org.apache.hadoop.hive.ql.parse.HiveParser.alterTblPartitionStatementSuffix(HiveParser.java:8524)
    at org.apache.hadoop.hive.ql.parse.HiveParser.alterTableStatementSuffix(HiveParser.java:8139)
    at org.apache.hadoop.hive.ql.parse.HiveParser.alterStatement(HiveParser.java:7190)
    at org.apache.hadoop.hive.ql.parse.HiveParser.ddlStatement(HiveParser.java:2602)
    at org.apache.hadoop.hive.ql.parse.HiveParser.execStatement(HiveParser.java:1589)
    at org.apache.hadoop.hive.ql.parse.HiveParser.statement(HiveParser.java:1065)
    at org.apache.hadoop.hive.ql.parse.ParseDriver.parse(ParseDriver.java:201)
    at org.apache.hadoop.hive.ql.parse.ParseDriver.parse(ParseDriver.java:166)
    at org.apache.hadoop.hive.ql.Driver.compile(Driver.java:462)
    at org.apache.hadoop.hive.ql.Driver.compileInternal(Driver.java:1276)
    at org.apache.hadoop.hive.ql.Driver.runInternal(Driver.java:1393)
    at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1205)
    at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1195)
    at org.apache.hadoop.hive.cli.CliDriver.processLocalCmd(CliDriver.java:220)
    at org.apache.hadoop.hive.cli.CliDriver.processCmd(CliDriver.java:172)
    at org.apache.hadoop.hive.cli.CliDriver.processLine(CliDriver.java:383)
    at org.apache.hadoop.hive.cli.CliDriver.executeDriver(CliDriver.java:775)
    at org.apache.hadoop.hive.cli.CliDriver.run(CliDriver.java:693)
    at org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:628)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
FAILED: ParseException line 2:7 mismatched input 'eid' expecting ) near 'INT' in add column statement
Please help me. I am learning hive

A: REPLACE is used when you want to have an altogether different columns to your table.If not it is better to rename the column_name with the CHANGE option in the alter statement.

A: The ALTER TABLE <TableName> REPLACE COLUMNS removes all existing columns and adds the new set of columns.
ALTER TABLE <TableName> REPLACE COLUMNS
(EID INT,
EName STRING);
REPLACE COLUMNS
For your scenario you can make use of ALTER TABLE <TableName> CHANGE <ColumnName>
ALTER TABLE <TableName> CHANGE ID EID INT;
This page will give you a lots of information ALTER COLUMNS


Q: The representation of a group Do all the homomorphisms $\phi: SL(2,\mathbb{Z})\ltimes \mathbb{Z}^2 \to GL(2,\mathbb{R})$ always have that $\phi_{|\mathbb{Z}^2}$ is trivial, i.e. $\phi(\mathbb{Z}^2)=I_2$?

A: Yes. Consider $\mathbb R^2$ as a representation of the semidirect product, hence as a representation of $\mathbb Z^2$, and write it as an extension of irreducible characters $\chi_1$, $\chi_2$. If any nontrivial character $\chi$ appears, then all conjugates of that character by automorphisms of $\mathbb Z^2$ in $SL_2(\mathbb Z)$ must appear as well. But each nontrivial character has at least three distinct conjugates (with the minimum achieved by the three nontrivial quadratic characters), so none can appear. Hence the representation of $\mathbb Z^2$ is unipotent, but this just gives a character $\mathbb Z^2 \to \mathbb R^{+}$. Again all conjugates must appear, but there is just one conjugate, so it must be trivial.
So $\mathbb Z^2$ acts trivially.


Q: Why, in Python, a dictionary does not need to be nonlocal to be seen in an inner function I am learning Python and while I was doing exercises with decorators, I found a case that I don't understand. The code bellow, inspired by the tutorial I use, is working:
>>> def maxExeTime(absMax,printMax=False):
...     def decorFun(toDo):
...         storeInfo = {"exeMax":0}
...         def modified(*p,**pp):
...             startTime = time.time()
...             returnValue = toDo(*p,**pp)
...             exeTime = time.time() - startTime
...             if exeTime > storeInfo["exeMax"]:
...                 storeInfo["exeMax"] = exeTime
...             if printMax:
...                 print("max execution time = {}".format(storeInfo["exeMax"]))
...             if exeTime > absMax:
...                 raise Exception("Max exe time reached: {}".format(exeTime))
...             return returnValue
...         return modified
...     return decorFun
...
>>> @maxExeTime(15,printMax=True)
... def mul(x,y):
...     input("Press Enter...")
...     return x*y
...
>>>
>>> mul(3,4)
Press Enter...
max execution time = 1.1439800262451172
12
>>> mul(3,5)
Press Enter...
max execution time = 2.1652064323425293
15
>>> mul(3,7)
Press Enter...
max execution time = 2.1652064323425293
21
>>> mul(3,10)
Press Enter...
max execution time = 21.074586629867554
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 13, in modified
Exception: Max exe time reached: 21.074586629867554
>>>

But I don't understand why the dictionary storeInfo is persistent and can be re-used from one call to the other. If I try to store the information directly in a variable (ie exeMax=0) and adapt the code accordingly, I get the behavior that I was expecting with an exception at run time: UnboundLocalError: local variable 'exeMax' referenced before assignment when I try to compare the current execution time with the actual max value (if exeTime > exeMax:)
Why does the dictionary persists out of the scope of the maxExeTime function execution?
Thanks to the links an the redirection to duplicate questions, I discovered closure which was a concept I never see before. Good. And I understand why it does not work in my test with the local variable exeMax since I didn't declare it as nonlocal. But I didn't do it either for the dictionary storeInfo, and it is working. Why does this type of object have a different behavior?
Edit
@kindall what you say explains why it is necessary to use nonlocal when I use and integer directly since it seems that integers have a different behavior/rules than other objects, and I want to modify the value in the inner function.
But I still don't understand why if exeTime < exeMax: fails when exeTime < storeInfo["exeMax"] does not, and then why the next code is valid.
>>> a = 12
>>> def m(x):
...     return a*x
...
>>> m(3)
36
>>> a = 15
>>> m(3)
45

For the moment, all these differences in behavior make the variable scope definition looking fuzzy for me. I need to find a clear definition of it, with, I hope, a small set of rules and no exception.


Q: TypeGuards for optional property while filtering array of objects I've got the following interfaces in typescript:
interface ComplexRating {
  ratingAttribute1?: number;
  ratingAttribute2?: number;
  ratingAttribute3?: number;
  ratingAttribute4?: number;
}

export interface Review {
  rating: ComplexRating | number;
}

I'd love to calculate an average rating for say ratingAttribute1 for sake of simplicity.
So given these reviews:
const reviews: Review[] = [
  { rating: { ratingAttribute1: 5 } },
  { rating: { ratingAttribute1: 10 } },
  { rating: { ratingAttribute2: 15 } },
  { rating: 5 }
]

I can filter down the reviews to the ones I'm interested in i.e.:
const calculateAverageRating = (reviews: Review[]): number => {
  const reviewsWithRating = reviews.filter(
    (review) =>
      typeof review.rating === 'object' &&
      typeof review.rating['ratingAttribute1'] === 'number'
  );
  return (
    reviewsWithRating.reduce((acc, review) => {
      let newValue = acc;
      if (typeof review.rating === 'object') {
        const rating = review.rating['ratingAttribute1'];
        if (rating) {
          newValue += rating;
        }
      }
      return newValue;
    }, 0.0) / reviewsWithRating.length
  );
};

Now, what's annoying is that Typescript does not know that by running the reviews.filter function I type guarded the Reviews only to a subset of the Reviews that have rating of type ComplexType and also the ones that have ratingAttribute1: number;  rather than ratingAttribute?: number.
What I'd love to end up with is not having to repeat the type checks in the calculation effectively ending up with:
const calculateAverageRating = (reviews: Review[]): number => {
  const reviewsWithRating = reviews.filter(
    (review) =>
      typeof review.rating === 'object' &&
      typeof review.rating['ratingAttribute1'] === 'number'
  );
  return (
    reviewsWithRating.reduce(
      (acc, review) => acc + review.rating['ratingAttribute1'],
      0.0
    ) / reviewsWithRating.length
  );
};

but that does not work out of the box:

Is there any way of achieving this level of type guarding? Or is there a neater of way doing this type of stuff?

A: The .filter() function will always return an array of the same type that was given as the argument. That is why reviewsWithRating is still a Review[], even after you filter it.
To change this, you can add a type guard to the callback:
const reviewsWithRating = reviews.filter(
  (review): review is { rating: Required<ComplexRating> } =>
    typeof review.rating === 'object' &&
    typeof review.rating['ratingAttribute1'] === 'number'
);

Now TypeScript will know that reviewsWithRating is of type { rating: Required<ComplexRating> }[].


Q: Connection Error in SQL Server Compact with ASP.Net I am trying to access a database, using a DataSet. I am using Visual Studio for Web Express 2013, ASP Web Forms project with SQL Server Compact 4.0. I created the database from Database Explorer, added 3 tables, now my code has getData, setData methods which will use Dataset to get data.
But the SqlConnection object is throwing exception at runtime.

[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error:
   26 - Error Locating Server/Instance Specified)]

I guess this is due to connection string since error is at line:
SLQCon.Open();

I have tried more than one method but none of them has worked yet. These are few of them,
msdn link
Connection Strings
The other things work fine (web form controls), only problem is when I do something related to database, any fixes?
My code is as follows:
void setData(string tableName) {
    string ConString = @"Data Source=" + "F:\\Github\\JournalClassifier\\WebApplication1\\WebApplication1\\App_Data\\KeywordsDB.sdf" + ";Connect Timeout=30";

    SQLCon.ConnectionString = ConString;

    SQLCon.Open();      // Exception here

    // insertion code
}

A: Make sure your database inside App_Data folder on your root application. and change the connection string to this one
<add name="ConnectionStringName"
    providerName="System.Data.SqlServerCe.4.0"
    connectionString="Data Source=\KeywordsDB.sdf;Connection Timeout=30" />

things you need to concern is you are using SQL Server Compact, so the provider name need use System.Data.SqlServerCe.4.0 otherwise it will confused with SQL Server Client


Q: How to detect corner "joints" that connect elements on images? I'm using OpenCV via Python 3.7. I have a set of monochrome images that look like this:

I'd like to find all "joint points" on these images, where a "joint point" - is a center (1 pixel) of every intersection of two planks. These "joints" are roughly represented by red cicrles on the image below:

The first idea was to skeletonize the image and then find all connected edges algorythmically, but all skeletonizations technques gave me wiggly or round corners and extra "sprouts".
import cv2
import numpy as np
from skimage.morphology import skeletonize

image = cv2.imread("SOURCE_IMAGE.jpg", cv2.IMREAD_GRAYSCALE)
binary_image = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 91, 12)
skeleton = (skeletonize(binary_image//255) * 255).astype(np.uint8)

Result:

The second idea was to find inner contours, approximate them to bounding points, find closest neighbours and then somehow calculate centers, but, again, Canny edge detection method gave me wiggly corners and extra points.
import cv2

image = cv2.imread("SOURCE_IMAGE.jpg", cv2.IMREAD_GRAYSCALE)
edged = cv2.Canny(image, 100, 200)

Result:

Are there any reliable approcahes to this problem?

A: This is my approach to solve this issue:

*

*Determine vertical lines

*Determine horizontal lines

*Find their intersections which are joints

For first step check each column and determine thin lines and make them black(0). The result will be only vertical lines. For the second step do reverse.
At the end compare vertical line image with the horizontal line image. The pixels which are white(255) in both are the intersection points.
Note: Please do not blame me because of coding in C++. I am not familiar with python I just wanted to show my approach and results.
Here is the code and results:
Source:

Vertical Lines:

Horizontal Lines:

Result:

The code:
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace std;
using namespace cv;

int main()
{
    Mat img = imread("/ur/image/directory/joints.jpg",1);

    imshow("Source",img);

    int checker = 1,checker2 = 1;
    int begin_y,finish_y2,finish_y,begin_y2;
    Mat vertical_img = img.clone();
    Mat horizontal_img = img.clone();

    cvtColor(vertical_img,vertical_img,CV_BGR2GRAY);
    cvtColor(horizontal_img,horizontal_img,CV_BGR2GRAY);

    int finish_checker = 0,finish_checker2=0;
    for(int i=0;i<horizontal_img.rows;i++)
    {
        for(int j=0;j<horizontal_img.cols;j++)
        {
            if(horizontal_img.at<uchar>(Point(j,i))>100 && checker)
            {
                begin_y = j;
                checker = 0;
            }

            if(horizontal_img.at<uchar>(Point(j,i))<20 && checker==0)
            {
                finish_y = j;
                checker = 1;
                finish_checker = 1;

            }

            if(finish_checker)
            {
                if((finish_y-begin_y)<30)
                {
                    for(int h=begin_y-2;h<=finish_y;h++)
                    {
                        horizontal_img.at<uchar>(Point(h,i)) = 0;
                    }
                }

                finish_checker = 0;
            }
        }
    }

    imshow("Horizontal",horizontal_img);

    for(int i=0;i<vertical_img.cols;i++)
    {
        for(int j=0;j<vertical_img.rows;j++)
        {
            if(vertical_img.at<uchar>(Point(i,j))>100 && checker2)
            {
                begin_y2 = j;
                checker2 = 0;
            }
            if(vertical_img.at<uchar>(Point(i,j))<50 && checker2==0)
            {
                finish_y2 = j;
                checker2 = 1;
                finish_checker2 = 1;
            }
            if(finish_checker2)
            {
                if((finish_y2-begin_y2)<30)
                {
                    for(int h=begin_y2-2;h<=finish_y2;h++)
                    {
                        vertical_img.at<uchar>(Point(i,h)) = 0;
                    }
                }
                finish_checker2 = 0;
            }
        }
    }
    imshow("Vertical",vertical_img);

    for(int y=0;y<img.cols;y++)
    {
        for(int z=0;z<img.rows;z++)
        {
            if(vertical_img.at<uchar>(Point(y,z))>200 && horizontal_img.at<uchar>(Point(y,z))>200)
            {
                img.at<cv::Vec3b>(z,y)[0]=0;
                img.at<cv::Vec3b>(z,y)[1]=0;
                img.at<cv::Vec3b>(z,y)[2]=255;
            }
        }
    }

    imshow("Result",img);
    waitKey(0);
    return 0;
}

A: Here's a slight modified version of @YunusTemurlenk's approach using Python instead of C++. The idea is:

*

*Obtain binary image. Load image, convert to grayscale, Gaussian blur, then Otsu's threshold.

*Obtain horizontal and vertical line masks. Create horizontal and vertical structuring elements with cv2.getStructuringElement then perform cv2.morphologyEx to isolate the lines.

*Find joints. We cv2.bitwise_and the two masks together to get the joints.

*Find centroid on joint mask. We find contours then calculate the centroid.

Horizontal/vertical line masks

Detected joints in green

Results

import cv2
import numpy as np

# Load image, grayscale, Gaussian blur, Otsus threshold
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Find horizonal lines
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10,1))
horizontal = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)

# Find vertical lines
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,10))
vertical = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=2)

# Find joints
joints = cv2.bitwise_and(horizontal, vertical)

# Find centroid of the joints
cnts = cv2.findContours(joints, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    # Find centroid and draw center point
    M = cv2.moments(c)
    cx = int(M['m10']/M['m00'])
    cy = int(M['m01']/M['m00'])
    cv2.circle(image, (cx, cy), 3, (36,255,12), -1)

cv2.imshow('thresh', thresh)
cv2.imshow('horizontal', horizontal)
cv2.imshow('vertical', vertical)
cv2.imshow('joints', joints)
cv2.imshow('image', image)
cv2.waitKey()


Q: Analogue of a path-connected subspace in the context of point processes Given a set of points $S$ in some metric space, a pair of points $x, x'$ will be termed $\epsilon$-connected if they are connected by a series of points $x_1, \ldots, x_m \in S$ such that $d(x, x_1)$, $d(x_1, x_2), \ldots, d(x_{m-1}, x_m)$, $d(x_m, x')$ are all at most $\epsilon$.
Suppose $n$ points are drawn from a fixed probability distribution $\mathcal{D}$ on some metric space. I would like to say that $D$ is [SOMETHING] if for any fixed pair of points $p, p'$ and any $\epsilon>0$ as $n \to \infty$ the probability that $p$ and $p'$ will be $\epsilon$-connected goes to 1.
Is there a common term for this type of thing?


Q: CALCULAR HORAS TRANSCURRIDO MÁS DE 1 DÍAS EXCEL Buen día.
Por favor me ayudarían con la formula correcta para calcular el tiempo transcurrido en horas entre varios días.
Intente con la siguiente formula pero no me da el calculo correcto: =C2-D2+A2+B2

Estamos de acuerdo que son más de 24 y 48 hrs.
¡Saludos y gracias!

A: Creo que lo que buscas puede hacerse así:
En primer lugar cambia la fórmula, que tal y como está no calcula bien, pon =(C2+D2)-(A2+B2)
Luego vete a formato de celda personalizado y busca el que pone [h]:mm:ss

A: ¿Cómo están guardadas las fechas y las horas? ¿En formato 'fecha' y 'hora' básicos, podemos asumir?
La fórmula que usas no tiene sentido, pero los números salen tan 'desviados', porque el formato 'hora' básico solo te va a mostrar desde 0 a 24. Pasa la columna de respuesta al formato 'hora' que marca como '37:30:55', o sea, que aparezcan los días como horas.
Y la fórmula que necesitas es =C1-A1+D1-B1. Esto te dará el total de horas.


Q: Can every element of the completion $\widehat{A}$ of a local ring $A$ be written as an element of $A$ with a unit of $\widehat{A}$? Let $A$ be a noetherian local ring, $\widehat{A}$ its completion. Can every element $f\in\widehat{A}$ be written as a product $f'u$ with $f'\in A$ and $u\in\widehat{A}^\times$?

A: No,try with $A=k[x,y]_{(x,y)},  \widehat{A} = k[[x,y]]$ and take $f = x-g(y)$ with $g(y) \in y k[[y]]$ non-algebraic over $k[y]$.
Then $\widehat{A}/(f)\cong k[[g(y),y]]$ and there is no non-zero $F(x,y)\in k[x,y]_{(x,y)}$ such that $F(g(y),y)=0$ ie. $f\widehat{A}\cap k[x,y]_{(x,y)}=\{0\}$.


Q: Convert POJO into JSON I have a POJO.
@Data
@AllArgsConstructor
@Builder
public class Emp {
    private String position;
    private String name;
}

Suppose, we have created an object
Emp emp = new Emp("Manager", "Bob");

How can I convert it to a list and save it in a database in JSON format?
The data should be stored in the database in the format below:
{
  list:[
    {
       position: Manager
       name: Bob
    }
  ]
}

Are there any ready solutions for that?
I  converted an object into a list and then I called the .toString() method on it:
Collections.singletonList(emp);

But when I store it in the database, the next save goes to the database:
[Emp(position=Manager, name=Bob)]

But I need to store the record in a different way

A:
How can I convert it to a list and save it in a database in JSON
format?
The data should be stored in the database in the format below:
{
  "list": [
    {
       "position": "Manager"
       "name": "Bob"
    }
  ]
}

Since the serialized JSON is required to have a property "list" you can't simply serialize the List as is.
Instead, you can define a POJO wrapping this list.
That's how it might look like (I've made it generic in order to make it suitable for serializing any type of list):
@Data
@AllArgsConstructor
public static class ListWrapper<T> {
    private List<T> list;
}

And that's how it can be serialized using Jackson's ObjectMapper and ObjectWriter:
List<Emp> emps = List.of(new Emp("Manager", "Bob"));
ListWrapper<Emp> listWrapper = new ListWrapper<>(emps);

ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();

String json = writer.writeValueAsString(listWrapper);
System.out.println(json);

Output:
{
  "list" : [ {
    "name" : "Manager",
    "position" : "Bob"
  } ]
}

A: If you need to store the object list as JSON in DB then you need Convert the list of object to JSON string using Jackson ObjectMapper. Store the converted string to DB.


Q: Find periodic orbits and calculate number of rotation. I've got two homeomorphisms $f$ and $g$ such that their lifts are given by
$F(x) = x + \varepsilon \sin( 2 \pi n x)$ and $G(x) = x + \frac{1}{n} + \varepsilon \sin( 2 \pi n x)$, where $0 < \varepsilon < \frac{1}{2 n \pi}$.
Problem: Evaluate number of rotation $f$ and $g$ and find periodic orbits.
First part was easy to me: $\rho(f) = 0$ and $\rho(g) = \frac{1}{n}$, directly by definition and independence of $x$. But I don't know how it corresponds  with periodic orbits.


Q: testing sails.js with mocha: can't find /api/services/myService consider this mocha test:
var Sails = require('sails');

describe("Foo Model creation:", function() {
  // create a variable to hold the instantiated sails server
  var app;

  // Global before hook
  before(function(done) {
    // Lift Sails and start the server
    Sails.lift({
      log: {
        level: 'error'
      }
    }, function(err, sails) {
      app = sails;
      done(err, sails);
    });
  });

  // Global after hook
  after(function(done) {
    app.lower(done);
  });

  describe("new foo", function() {
    var foo;
    before(function (cb) {
      var fooData = {
        name: "test foo to be removed after test"
      };

      Foo.create(fooData, function (err, newFoo)
        if (err) return cb(err);
        foo = newFoo;
        cb();
      });
    });
    it("must show the name", function() {
      foo.must.have.property('name');
    });

    after(function (cb){
      foo.destroy(function (err) {
        cb(err);
      });
    });
  });
})

This would work except that the Foo model depends on a sails service i.e. library code defined in /api/services.  Sails, when lifted here, can't find those services.
Is there a way to instruct Sails during a mocha test to also load the services?

A: I had a similar issue, and indeed, Sails should be loading services, controllers, etc.
There were some debug tools that helped when lifting Sails:
Sails.lift({
  log: {
    level: 'verbose'
  },
  appPath: '../',
  // explicitly load almost everything but policies
  //loadHooks: ['moduleloader', 'userconfig', 'orm', 'http', 'controllers', 'services', 'request', 'responses', 'blueprints']
}

I also did a live debug of Mocha (though I won't go into steps on that here).
What I found out through debugging and a log level of verbose (you could also try silly if verbose doesn't answer a question) is that I was loading Sails from the wrong directory - the test directory.  Once I changed appPath to '../', I could tell from the log messages that it was loading the proper content, and voila, my sails.services.myService object was now there!
Hope that helps!


Q: How to capture file save as cancel respond I followed this post http://www.the-art-of-web.com/php/dataexport/ and successfully create an export to csv file from DB, base on user current search view. But to prevent hit to db while export is happening so I disable the export unless there is change within the view or user query.  The issue I face with is when user hit on export a file save as confirm dialog pop up and if user changed her mind click on cancel.  The export button remain disable.  The only way for user to get back is to change query and come back again.
My question is there anyway I could capture the cancel click respond on file save as confirm dialog.
Thanks
The code is very similar to http://www.the-art-of-web.com/php/dataexport/  Where as the view would be a grid with bunch of customer information from given date range.  If user like the view they choose.  They would click on export button.
sample code
export.php
function exportCSV(){
  document.getElementById("exportCSV").src = "test1.php";
  document.getElementById("exportBtn").disabled = true;
}

function performSearch(){
  //perform search get result and display
  //if resultset length > 0
  document.getElementById("exportBtn").disabled = false;
}

Grid display right here
 <button id="search" onclick="performSearch()">Search
 <button id="exportBtn" onclick="exportCSV()"> Export
 <iframe id="exportCSV" style="display:none"/>
test1.php
$data = array(
       array("firstname" => "Mary", "lastname" => "Johnson", "age" => 25),
       array("firstname" => "Amanda", "lastname" => "Miller", "age" => 18),
       array("firstname" => "James", "lastname" => "Brown", "age" => 31),
       array("firstname" => "Patricia", "lastname" => "Williams", "age" => 7),
       array("firstname" => "Michael", "lastname" => "Davis", "age" => 43),
       array("firstname" => "Sarah", "lastname" => "Miller", "age" => 24),
       array("firstname" => "Patrick", "lastname" => "Miller", "age" => 27)
     );
# filename for download
 $filename = "website_data.xls";
header("Content-Disposition: application/octet-stream; filename=\"$filename\"");
 header("Content-Type: application/vnd.ms-excel");
$flag = false;
 foreach($data as $row) {
   if(!$flag) {
     # display field/column names as first row
     echo implode("\t", array_keys($row)) . "\n";
     $flag = true;
   }
   array_walk($row, 'cleanData');
   echo implode("\t", array_values($row)) . "\n";
 }
 exit;
 function cleanData(&$str)
 {
   $str = preg_replace("/\t/", "\\t", $str);
   $str = preg_replace("/\r?\n/", "\\n", $str);
   if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
 }

A: There's no way to capture the browser event for canceling a save file.  Using a confirm in an if statement(or something similar) is probably the best ux for that situation:
if(confirm('are you sure you want to export?'))
{
//export code
}
else
{
//cancel code
}

If you want your export button to become re-enabled I would call a re-enable function whenever your user's search(or whatever action they make to change data) is called. Or you can also use setTimeout() after the export button is hit and re-enable it after a certain time period.

A: Maybe you can send the dump file through a php script. There you (again: maybe, I dont know, if it really works) can test the connection status with connection_status(). But if you send the file through a php-script, you dont need to know the status, because if the script shutdown properly, it doenst matter, if the transmission were completed, if you just want to unlock the database.
Usually a normal database dump is safe anyway. So if you let the database dump the data it contains and save it to a file, there is no reason to lock the database while someone downloads a file.


Q: Better solution to data storage and passing I'm trying to find a more elegant solution for some code I'm working on at the moment. I have data that needs to be stored then moved around, but I don't really want to take up any more space than I need to for the data that is stored.
I have 2 solutions, but neither seem very nice.

Using inheritance and a tag
enum class data_type{
    first, second, third
};

class data_base{
    public:
        virtual data_type type() const noexcept = 0;
};

using data_ptr = data_base*;

class first_data: public data_base{
    public:
        data_type type() const noexcept{return data_type::first;}

        // hold the first data type
};

// ...

Then you pass around a data_ptr and cast it to the appropriate type.
I really don't like this approach because it requires upwards casting and using bare pointers.

Using a union and storing all data types
enum class data_type{
    first, second, third
};

class data{
    public:
        data(data_type type_): type(type_){}
        data_type type;
        union{
            // first, second and third data types stored
        };
};

But I don't like this approach because then you start wasting a lot of memory when you have a large data type that may get passed around.

This data will then be passed onto a function that will parse it into a greater expression. Something like this:
class expression{/* ... */};
class expr_type0: public expression{/* ... */};
// every expression type

using expr_ptr = expression*;

// remember to 'delete'
expr_ptr get_expression(){
    data_ptr dat = get_data();

    // interpret data
    // may call 'get_data()' many times
    expr_ptr expr = new /* expr_type[0-n] */

    delete dat;
    return expr;
}

and the problem arrises again, but it doesn't matter in this case because the expr_ptr doesn't need to be reinterpreted and will have a simple virtual function call.

What is a more elegant method of tagging and passing around the data to another function?

A: It's difficult to envisage exactly what you're looking for without more information. But if I wanted some framework that allowed me to store and retrieve data in some structured way, in as-yet-unknown storage devices this is the kind of way I'd be thinking.
This may not be the answer you're looking for, but I think there'll be concepts here that will inspire you in the right direction.
#include <iostream>
#include <tuple>
#include <boost/variant.hpp>
#include <map>

// define some concepts

// bigfoo is a class that's expensive to copy - so lets give it a shared-handle idiom
struct bigfoo {

    struct impl {
        impl(std::string data) : _data(std::move(data)) {}
        void write(std::ostream& os) const {
            os << "I am a big object. Don't copy me: " << _data;
        }
    private:
        std::string _data;
    };

    bigfoo(std::string data) : _impl { std::make_shared<impl>(std::move(data)) } {};

    friend std::ostream& operator<<(std::ostream&os, const bigfoo& bf) {
        bf._impl->write(os);
        return os;
    }

private:
    std::shared_ptr<impl> _impl;
};

// all the data types our framework handles
using abstract_data_type = boost::variant<int, std::string, double, bigfoo>;

// defines the general properties of a data table store concept
template<class...Columns>
struct table_definition
{
    using row_type = std::tuple<Columns...>;
};

// the concept of being able to store some type of table data on some kind of storage medium
template<class IoDevice, class TableDefinition>
struct table_implementation
{
    using io_device_type = IoDevice;
    using row_writer_type = typename io_device_type::row_writer_type;

    template<class...Args> table_implementation(Args&...args)
    : _io_device(std::forward<Args>(args)...)
    {}

    template<class...Args>
    void add_row(Args&&...args) {
        auto row_instance = _io_device.open_row();
        set_row_args(row_instance,
                     std::make_tuple(std::forward<Args>(args)...),
                     std::index_sequence_for<Args...>());
        row_instance.commit();
    }

private:
    template<class Tuple, size_t...Is>
    void set_row_args(row_writer_type& row_writer, const Tuple& args, std::index_sequence<Is...>)
    {
        using expand = int[];
        expand x { 0, (row_writer.set_value(Is, std::get<Is>(args)), 0)... };
        (void)x; // mark expand as unused;
    }

private:
    io_device_type _io_device;
};

// model the concepts into a concrete specialisation

// this is a 'data store' implementation which simply stores data to stdout in a structured way
struct std_out_io
{
    struct row_writer_type
    {
        void set_value(size_t column, abstract_data_type value) {
            // roll on c++17 with it's much-anticipated try_emplace...
            auto ifind = _values.find(column);
            if (ifind == end(_values)) {
                ifind = _values.emplace(column, std::move(value)).first;
            }
            else {
                ifind->second = std::move(value);
            }
        }

        void commit()
        {
            std::cout << "{" << std::endl;
            auto sep = "\t";
            for (auto& item : _values) {
                std::cout << sep << item.first << "=" << item.second;
                sep = ",\n\t";
            }
            std::cout << "\n}";
        }

    private:
        std::map<size_t, abstract_data_type> _values;  // some value mapped by ascending column number
    };

    row_writer_type open_row() {
        return row_writer_type();
    }
};

// this is a model of a 'data table' concept
using my_table = table_definition<int, std::string, double, bigfoo>;

// here is a test
auto main() -> int
{
    auto data_store = table_implementation<std_out_io, my_table>( /* std_out_io has default constructor */);
    data_store.add_row(1, "hello", 6.6, bigfoo("lots and lots of data"));

    return 0;
}

expected output:
{
        0=1,
        1=hello,
        2=6.6,
        3=I am a big object. Don't copy me: lots and lots of data
}


Q: Application is getting crash while using gridview in Android In my app i want to use a gridView in fragment of navigation drawer but my application is getting crash.
this is my code:
public class HomeFragment extends Fragment {

    GridView gridView;
    private String[] categoryHomeGridView;
    private Integer[] icon={R.drawable.cat_offer_women,R.drawable.cat_offer_men,
            R.drawable.cat_offer_food_and_drink,R.drawable.cat_offer_electronics};
    private ArrayList homeGridViewItems;
    private HomeGridViewListAdapter adapter;
    public HomeFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        init();
        return view;
    }

    private void init() {
        // TODO Auto-generated method stub
        gridView=(GridView) getActivity().findViewById(R.id.homeGridView);
        categoryHomeGridView=getActivity().getResources().getStringArray(R.array.category_array);

        homeGridViewItems=new ArrayList();
        homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[0],
                icon[0]));
        homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[1],
                icon[1]));
        homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[2],
                icon[2]));
        homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[3],
                icon[3]));
    //  iconHomeGridView.recycle();

        adapter=new HomeGridViewListAdapter(getActivity().getApplicationContext()
                ,homeGridViewItems);
        gridView.setAdapter(adapter);

    }
}

and this is crash log

03-26 14:50:56.524: E/AndroidRuntime(2355): FATAL EXCEPTION: main
03-26 14:50:56.524: E/AndroidRuntime(2355): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.couponoffer/com.example.couponoffer.MainActivity}: java.lang.NullPointerException
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.os.Looper.loop(Looper.java:137)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.ActivityThread.main(ActivityThread.java:4745)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at java.lang.reflect.Method.invokeNative(Native Method)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at java.lang.reflect.Method.invoke(Method.java:511)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at dalvik.system.NativeStart.main(Native Method)
03-26 14:50:56.524: E/AndroidRuntime(2355): Caused by: java.lang.NullPointerException
03-26 14:50:56.524: E/AndroidRuntime(2355):     at fragments.HomeFragment.init(HomeFragment.java:57)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at fragments.HomeFragment.onCreateView(HomeFragment.java:34)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:829)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.BackStackRecord.run(BackStackRecord.java:635)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1397)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.Activity.performStart(Activity.java:5017)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2032)
03-26 14:50:56.524: E/AndroidRuntime(2355):     ... 11 more

A: Place this line gridView=(GridView) getActivity().findViewById(R.id.homeGridView); in onCreate and do it like this gridView=(GridView) view.findViewById(R.id.homeGridView); because your gridview is part of your View. Or pass the View view to init();
like this:
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        init(view);
        return view;
    }

private void init(View rootView) {
        // TODO Auto-generated method stub
        gridView=(GridView) rootView.findViewById(R.id.homeGridView);
        categoryHomeGridView=getActivity().getResources().getStringArray(R.array.category_array);

        homeGridViewItems=new ArrayList();
        homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[0],
                icon[0]));
        homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[1],
                icon[1]));
        homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[2],
                icon[2]));
        homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[3],
                icon[3]));
    //  iconHomeGridView.recycle();

        adapter=new HomeGridViewListAdapter(getActivity().getApplicationContext()
                ,homeGridViewItems);
        gridView.setAdapter(adapter);

    }

A: The gridView probably belongs to the fragment layout
So you need to change this
 gridView=(GridView) getActivity().findViewById(R.id.homeGridView);

to
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
 View view = inflater.inflate(R.layout.fragment_home, container, false)
 gridView=(GridView) view.findViewById(R.id.homeGridView);

A: Change this:
gridView=(GridView) getActivity().findViewById(R.id.homeGridView);

to this:
View view = inflater.inflate(R.layout.fragment_home, container, false);
gridView=(GridView) view .findViewById(R.id.homeGridView);


Q: Viewing outstanding requests Is there any way to view what requests Protractor are waiting on? I'm trying to debug flaky state testing, but it is hard to tell whether a button didn't trigger a response or if Protractor didn't bother to wait.
TL;DR: How can I view the remaining promises on the Protractor control flow?

A: The usual approach is to start protractor in a debug mode and put browser.debugger() breakpoint before the problem block of code.
See more information at Debugging Protractor Tests.

On the other hand, you can catch the chromedriver service logs that look like:
[2.389][INFO]: COMMAND FindElement {
   "sessionId": "b6707ee92a3261e1dc33a53514490663",
   "using": "css selector",
   "value": "input"
}
[2.389][INFO]: Waiting for pending navigations...
[2.389][INFO]: Done waiting for pending navigations
[2.398][INFO]: Waiting for pending navigations...
[2.398][INFO]: Done waiting for pending navigations
[2.398][INFO]: RESPONSE FindElement {
   "ELEMENT": "0.3367185448296368-1"
}

Might also give you a clue of what is happening.
For this, you need to start chrome with --verbose and --log-path arguments:
{
     browserName: "chrome",
     specs: [
         "*.spec.js"
     ],
     chromeOptions: {
         args: [
             "--verbose",
             "--log-path=/path/to/the/log/file"
         ]
     }
 }

(not tested)
For firefox, you can turn on and view logs by setting webdriver.log.driver and webdriver.log.file firefox profile settings.
See also:

*

*Monitoring JSON wire protocol logs

*How to change firefox profile