Q:

What kind of "gff" format does bioawk parse?

I was wondering if I could use the gff parsing capability of bioawk to facilitate the parsing of gtf files, and I looked at the following help message:
$ bioawk -c help
bed:
    1:chrom 2:start 3:end 4:name 5:score 6:strand 7:thickstart 8:thickend 9:rgb 10:blockcount 11:blocksizes 12:blockstarts
sam:
    1:qname 2:flag 3:rname 4:pos 5:mapq 6:cigar 7:rnext 8:pnext 9:tlen 10:seq 11:qual
vcf:
    1:chrom 2:pos 3:id 4:ref 5:alt 6:qual 7:filter 8:info
gff:
    1:seqname 2:source 3:feature 4:start 5:end 6:score 7:filter 8:strand 9:group 10:attribute
fastx:
    1:name 2:seq 3:qual 4:comment

I see that there are 10 fields defined for gff parsing.
However, when I look at the pages for gtf and gff in the ensembl website (gff/gtf and gff3), all have 9 fields.
I'm curious about these "filter" and "group" fields. What are they meant for? Are they extracted from some of the columns mentioned in the above pages?

A:

I would consider the description there a bug. The filter is actually the strand, strand is the frame, group is the attribute, and attribute does nothing. These are really meant to be the 9 columns.
Edit: There's a bug report related to this.
Edit 2: I've made a pull request to clarify this and fix the aforementioned bug report.
Edit 3: I realized that I never directly answered the title of your question (mea culpa). bioawk itself will work with gff, gff3, or gtf files. It really is just treating them as tab-separated files with named columns (this is surprisingly convenient, since it's a PITA to remember what column does what).
Edit 4: The PR has been merged. If you install from github then you'll see corrected field names.


Q:

How to download zip file from PHP Laravel API using Angular in front end?

I want to download the zip file from the server using PHP Laravel. The Laravel passes zip files through following return command:
return response()->download($file);

It downloads the zip file when I hit the route URL for the controller in the browser, and it also downloads the zip file when I use window.open(url) in the Angular but it is not secure as anyone can download the file. The user has to authenticate before downloading the file but I cannot pass header with window.open(url), therefor I need a different approach to achieve this.
I went through most of the questions here, and they suggest to use FileSaver and Blob. I tried to test with those but didn't work and it's because the API doesn't pass the zip file to the client.
Here is the Angular http.get:
return http.get('localhost:8000/dashboard/backup')
  .subscribe(res => {
    console.log('Successfull');
  }, err => {
    console.log(err);
  });

I can get the file path, but the path is not public and cannot download it using Angular. The path is returned as Application/XAMP.... and when I set it as HREF and click on it, it loads in browser as localhost:4200/Application/XAMP....
In the console log, I have an invalid character at JSON file line 1. Why is the zip file passed as JSON?

A:

use post method and responseType arraybuffer
$http.post('localhost:8000/dashboard/backup', {}, {responseType:'arraybuffer'}){
}


Q:

How to Role-Provider Implementation into LINQ?

I want convert following sample Role-Provider Implementation to LINQ.
How to: Sample Role-Provider Implementation
I want uses the ADO.NET Entity Data Model(Entity Framework 6).

A:

Found a solution:
using System.Web.Security;
using System.Configuration.Provider;
using System;
using System.Linq;

/*

 This provider works with the following schema for the tables of role data.

CREATE TABLE [tblRoles] (
 [Rolename]        NVARCHAR (255) NOT NULL,
 [ApplicationName] NVARCHAR (255) NOT NULL,
 CONSTRAINT [PKRoles] PRIMARY KEY
 CLUSTERED ([Rolename] ASC, [ApplicationName] ASC)
);

CREATE TABLE [tblUsersInRoles] (
[Username]        NVARCHAR (255) NOT NULL,
[Rolename]        NVARCHAR (255) NOT NULL,
[ApplicationName] NVARCHAR (255) NOT NULL,
CONSTRAINT [PKUsersInRoles] PRIMARY KEY
CLUSTERED ([Username] ASC, [Rolename] ASC, [ApplicationName] ASC)
);

*/

namespace mvc2.Models
{
  public class CustomRoleProvider : RoleProvider
  {
    private string pApplicationName = "MyApplicationName";
    Database1Entities db; //ADO.NET Entity Data Mode(Entity Framework 6.0)
    public override string ApplicationName
    {
        get { return pApplicationName; }
        set { pApplicationName = value; }
    }
    public override bool DeleteRole(string rolename, bool throwOnPopulatedRole)
    {
        db = new Database1Entities();
        if (!RoleExists(rolename))
        {
            throw new ProviderException("Role does not exist.");
        }
        if (throwOnPopulatedRole && GetUsersInRole(rolename).Length > 0)
        {
            throw new ProviderException("Cannot delete a populated role.");
        }

        var resultRoles = db.tblRoles.Where(x => x.Rolename == rolename &&
            x.ApplicationName == ApplicationName);
        db.tblRoles.RemoveRange(resultRoles);

        var resultUserInRoles = db.tblUsersInRoles.Where(x => x.Rolename == rolename &&
           x.ApplicationName == ApplicationName);
        db.tblUsersInRoles.RemoveRange(resultUserInRoles);
        db.SaveChanges();
        return true;
    }
    public override string[] GetAllRoles()
    {
        db = new Database1Entities();
        return db.tblRoles.Where(x => x.ApplicationName == ApplicationName)
            .Select(x => x.Rolename).ToArray();
    }
    public override string[] GetUsersInRole(string rolename)
    {
        db = new Database1Entities();
        return db.tblUsersInRoles.Where(x => x.Rolename == rolename &&
            x.ApplicationName == ApplicationName).Select(x => x.Username).ToArray();
    }
    public override void RemoveUsersFromRoles(string[] usernames, string[] rolenames)
    {
        foreach (string rolename in rolenames)
        {
            if (!RoleExists(rolename))
            {
                throw new ProviderException("Role name not found.");
            }
        }
        foreach (string username in usernames)
        {
            foreach (string rolename in rolenames)
            {
                if (!IsUserInRole(username, rolename))
                {
                    throw new ProviderException("User is not in role.");
                }
            }
        }
        db = new Database1Entities();
        foreach (string username in usernames)
        {
            foreach (string rolename in rolenames)
            {
                tblUsersInRole result = db.tblUsersInRoles.Where(x =>
                    x.Username == username &&
                    x.Rolename == rolename &&
                    x.ApplicationName == ApplicationName).FirstOrDefault();
                if (result != null)
                {
                    db.tblUsersInRoles.Remove(result);
                }
            }
        }
        db.SaveChanges();
    }
    public override string[] FindUsersInRole(string rolename, string usernameToMatch)
    {
        db = new Database1Entities();
        return db.tblUsersInRoles.Where(x =>
            x.Username == usernameToMatch &&
            x.Rolename == rolename &&
            x.ApplicationName == ApplicationName
            ).Select(x => x.Username).ToArray();
    }
    public override bool RoleExists(string rolename)
    {
        Database1Entities db = new Database1Entities();
        bool exists = db.tblRoles.Where(x => x.Rolename == rolename &&
            x.ApplicationName == ApplicationName).Count() > 0 ? true : false;
        return exists;
    }
    public override void AddUsersToRoles(string[] usernames, string[] rolenames)
    {
        db = new Database1Entities();
        int RoleCheck = rolenames.Where(x => RoleExists(x)).Count();
        if (RoleCheck == 0)
        {
            throw new ProviderException("Role name not found.");
        }
        int CheckCommasInUsername = usernames.Where(x => x.ToString().Contains(",")).Count();
        if (CheckCommasInUsername > 0)
        {
            throw new ArgumentException("User names cannot contain commas.");
        }
        foreach (string username in usernames)
        {
            foreach (string rolename in rolenames)
            {
                if (IsUserInRole(username, rolename))
                {
                    throw new ProviderException("User is already in role.");
                }
            }
        }
        foreach (string username in usernames)
        {
            foreach (string rolename in rolenames)
            {
                tblUsersInRole newRecord = new tblUsersInRole();
                newRecord.Username = username;
                newRecord.Rolename = rolename;
                newRecord.ApplicationName = ApplicationName;
                db.tblUsersInRoles.Add(newRecord);
            }
        }
        db.SaveChanges();

    }
    public override void CreateRole(string rolename)
    {
        if (rolename.Contains(","))
        {
            throw new ArgumentException("Role names cannot contain commas.");
        }
        if (RoleExists(rolename))
        {
            throw new ProviderException("Role name already exists.");
        }
        db = new Database1Entities();
        tblRole newRole = new tblRole();
        newRole.Rolename = rolename;
        newRole.ApplicationName = ApplicationName;
        db.tblRoles.Add(newRole);
        db.SaveChanges();
    }
    public override string[] GetRolesForUser(string username)
    {
        db = new Database1Entities();
        return db.tblUsersInRoles.Where(x => x.Username == username &&
            x.ApplicationName == ApplicationName).Select(x => x.Rolename).ToArray();
    }
    public override bool IsUserInRole(string username, string rolename)
    {
        db = new Database1Entities();
        return db.tblUsersInRoles.Where(x =>
            x.Username == username &&
            x.Rolename == rolename &&
            x.ApplicationName == ApplicationName).Count() > 0 ? true : false;
    }
  }
}


Q:

How to make Dreamweaver AP Div Show/hide functions work in IE9?

I created a page using Dreamweaver and fireworks that uses one AP Div as a button to show and hide two other AP Divs using JavaScript. However, the AP divs are relatively places. It all works fine in google chrome and safari but it doesn't work at all in IE 9. I suspect it's an issue with the JavaScript and IE9. I am new to this, and I know my site is built in a weird way. All help is appreciated.
I also tried using this tutorial:
http://webdesign.about.com/od/dhtml/a/aa101507.htm  (Shows and Hides divs with a link)
where the a div is a link, to make it work, but it didn't fix it.
Thanks in Advance

A:

Right, I've scrapped your code, not because it's bad but because I dont understand it :P, I've used something different, this may mean that you have to re-write some code on your page. What my code does it replaces the content with-in the div instead of hiding/showing between 2 divs... Below is a link to a jsfiddle, try running it in IE9 and see if that works.
http://jsfiddle.net/hSMk3/
If it doesn't work tell me in the comment section thingy below :)


Q:

How to embed HTML content in BI report for bursting?

I want to send HTML Email from BI publisher, but the HTML is not getting recognized by the SQL query and it is trying to interpret it further.
How can I make use of that HTML as a literal with dynamic values returned by the query?

A:

You can make use of htf.escape_sc() function which will take care of escaping HTML. It will use HTML entities internally. e.g. < will get converted into <


Q:

How to clean duplicates existing in one folder from another recursively?

Summary: Folder A has only many Excelent files
Folder B has many folders of mixed Excelent/Good/Bad files
How can i delete files in Folder B folders only in case they will be in Folder A.
Or simply putting same thing:
How to make checking of Folder A files if they exist in Folder B folders then delete from Folder B folders?
Idea of solution
Maybe a command witch:

Checks part of alphabet like all starting with A
Executing deletion on files found in Folder B subfolders
Repeat 1. + one alphabet up.

Cause duplication programs were bad:

Long time until 1st deletion- its only when finished scanning
And no possible to choose deleting in Folder B. Its possible only to keep latest and something else also but not by choosing in witch folder to keep.

Useless history: Files were copied from Recuva in Folder B and partly arranged but a lot of them are bad so 1st im thinking Folder B comparing if exist to thouse witch recovered again but now just Excelent recovered in Folder A by Recuva so most of Excelent will be just in Folder A.
Example file tree:
.
├── A
│   ├── 1.png
│   ├── 2.png
│   └── Excellent
│       ├── e1.png
│       └── e2.png
└── B
    ├── 1.png
    ├── 2.png
    ├── Bad
    │   ├── 1.png
    │   ├── 2.png
    │   ├── e1.png
    │   └── e2.png
    └── Excellent
        ├── e1.png
        └── e2.png

A:

Below are two solutions, depending on how we define "duplicate":

Files with the same relative path, or
Files with the same content but not necessarily the same name

If by "duplicate" we mean two files which share the same relative path, then you could use find and xargs to remove the duplicates. For example, suppose you have
~/tmp% tree A
A
└── Excellent
    ├── bar
    ├── baz
    └── foo
~/tmp% tree B
B
├── Bad
│   └── quux
├── Excellent
│   ├── bar
│   ├── baz
│   └── foo
└── Good

Then
find /home/unutbu/tmp/A  -depth -type f -print0 | xargs -0 -I{} bash -c 'rm "/home/unutbu/tmp/B${1#*A}"' - {}

results in
~/tmp% tree B
B
├── Bad
│   └── quux
├── Excellent
└── Good

Or, if by "duplicate" we mean two files share the same content, though perhaps not the same filename, then you could use rdfind:
sudo apt-get install rdfind

If we have this directory structure:
~/tmp% tree A
A
└── Excellent
    ├── bar
    ├── baz
    └── foo

1 directory, 3 files
~/tmp% tree B
B
├── Bad
│   └── quux
├── Excellent
│   ├── barbar
│   ├── bazbaz
│   └── foofoo
└── Good

where barbar has the same content as bar, and similarly for bazbaz and foofoo, then
rdfind -deleteduplicates true A B

results in
~/tmp% tree B
B
├── Bad
│   └── quux
├── Excellent
└── Good

Alternate solution in case your version of Ubuntu does not include rdfind:
You could instead use fdupes:
sudo apt-get install fdupes
fdupes --recurse --delete --noprompt A B


Q:

Call c# delegate from c++ code in cocos2d-x wp8-xaml

I want to call c# delegate from c++ code in my cocos2d-x 3.3 game (wp8-xaml backend).
I found this:
http://discuss.cocos2d-x.org/t/wp8-cocos2dx-and-xaml/4886/6
And here's my class "NativeEventHelper.cpp" in c++ project:
#pragma once
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
namespace PhoneDirect3DXamlAppComponent
{
public delegate void CallNativeFunctionDelegate();
public ref class NativeEventHelper sealed
{
public:
    NativeEventHelper(void);
    void SetCallNativeFunctionDelegate(CallNativeFunctionDelegate^ delegate) {
        m_CallNativeFunctionDelegate = delegate;
    }

    bool NativeEventHelper::CallNativeFunction()
    {
        if (m_CallNativeFunctionDelegate)
        {
            m_CallNativeFunctionDelegate->Invoke();
            return true;
        }
        return false;
    }

private:
    property static CallNativeFunctionDelegate^ m_CallNativeFunctionDelegate;
};

}
#endif

Here's my callback in c# (MainPage.xaml.cs) class:
 public void CallNativeFunction()
    {
        Dispatcher.BeginInvoke(() =>
        {
            Debug.WriteLine("# NATIVE CODE #");
        });
        return;
    }

And here's an issue. In constructor I have to create new NativeEventHelper (from c++ class), but I don't know how to add refence, because compiler is complaining about unknown identifier "NativeEventHelper".
 NativeEventHelper helper = new NativeEventHelper();
 helper.SetCallNativeFunctionDelegate(CallNativeFunction);

I also found this:
Calling C# method from C++ code in WP8
This seems to be exactly the same, but again I don't know how to reference this class. This is not working in my case: https://software.intel.com/en-us/articles/using-winrt-apis-from-desktop-applications Instead of windows I see windows phone sdk in references and cannot add winrt.

A:

I finally solved it!!
First of all: I had to change namespace to cocos2d. Also I had to ignore warnings and just make full clean and rebuild. After that it works. To call code in c++ I figured out this:
NativeEventHelper^ nativeEventHelper = ref new NativeEventHelper();
nativeEventHelper->CallNativeFunction();

Fixed NativeEventHelper.cpp file:
#pragma once
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
namespace cocos2d
{
    public delegate void CallNativeFunctionDelegate();
    public ref class NativeEventHelper sealed
    {
    public:
        NativeEventHelper(void);
        void SetCallNativeFunctionDelegate(CallNativeFunctionDelegate^ delegate) {
            m_CallNativeFunctionDelegate = delegate;
        }

        bool NativeEventHelper::CallNativeFunction()
        {
            if (m_CallNativeFunctionDelegate)
            {
                m_CallNativeFunctionDelegate->Invoke();
                return true;
            }
            return false;
        }

    private:
        property static CallNativeFunctionDelegate^ m_CallNativeFunctionDelegate;
    };

}
#endif


Q:

reactjs state is being lost between events

I have a React component that's created dynamically, with data loaded into its state. This state is being cleared between click events, resulting in the visible info being lost (undefined). Where has it gone?
const React = require('react');
const ReactDOM = require('react-dom');

class App extends React.Component {

  constructor(props) {
    super(props);
    this.nodesQuantity = 0;
    this.state = {roots: []};
  }

  nextId(me) {
    return me.nodesQuantity++;
  }

  componentDidMount() {
    var roots = [1,2,3].map(node => {
        let nextId = this.nextId(this);
        return <Node key={nextId} data={node} nextId={this.nextId} depth={0} god={this} />
    });
    this.setState({roots: roots});
  }

  render() {
    return (

{this.state.roots}

    )
  }
}

class Node extends React.Component{
  constructor(props) {
    super(props);
    this.state = {data: this.props.data, childNodes: [], visible: true};
    this.toggleExpanded = this.toggleExpanded.bind(this);
  }

  toggleExpanded(event) {
    console.log(this.state.childNodes.length)
    let val={id:"asdf",label:"asdf"}

    if (this.state.childNodes.length > 0) {
        this.state.childNodes.forEach((childNode) => {
            childNode.setState({visible: !childNode.state.visible})
        });
    } else {
        this.setState((oldState, props) => {
            let nextId = props.nextId(props.god);
            console.log(nextId);
            oldState.childNodes.push(<Node key={nextId} data={val} nextId={props.nextId} depth={props.depth+1} god={props.god} />);
        });
    }
    event.stopPropagation();
  }

  render() {
    return (

            {this.state.data.id} ({this.state.data.label})

{this.state.childNodes}

    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('react')
)

A:

I solved it. My main problem was a misunderstanding of react lifecycle.
This answer, albeit a bit outdated, was quite useful in understanding my problem.
Also a bit switch was to store the Node as json and only build the nodes during render step. Updates are triggered with setState which pass through the componentWillReceiveProps method that updates the state of the node json and proceeds to render
Here's my solution: https://jsfiddle.net/n3ygz7uk/2/


Q:

format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’

I'm using Linux and when I try using this code to display:
#include <stdio.h>
#include <math.h>

int main()
{
    int a,b,c;
    int result;

    printf( "How Many Times Would You Like to Add: ");
    scanf( "%d", &a );
    //getchar();

    printf( "What Number Would You Like to Add: ");
    scanf( "%d", &b );
    //getchar();

    printf( "What Number Would You Like to Add to It?: ");
    scanf( "%d", &c );
    //getchar();

    for( int $i = 0; $i < a; $i++ )
    {
        result = b + c;
        printf( "%d", &result );
        printf( "\n" );

    }

    return 0;
}

I get this:
main.c: In function ‘main’:
main.c:26:3: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat]

Using this compilation command:
cd ./TSTS
gcc -std=c99 main.c -o LetsADD!

A:

for( int $i = 0; $i < a; $i++ )

Remove the $ here. This isn't PHP.
    printf( "%d", &result );

Remove the & here. printf takes a value, not a pointer. & gets the address of a variable. (Note that scanf does take a pointer, because C uses pass-by-value, and scanf needs to modify the value.)


Q:

CrossBrowser transparent text with css

What I have is a div with a background image, inside such div I have another element which is smaller and has a background colour of white. Inside this element I have text which I wan't to be transparent, so we can see background image of first div.
Tried applying color: transparent; but it doesn't seem to work. Is there reliable, css method to achieve this?

A:

You can't. The only way to do anything like this is to have the "background with the text taken out" be an image that you put on top of the background image.


Q:

Run-time error '91' (Object variable or With block variable not set)

I am relatively new to VBA and am trying to put together a msgbox that will give me a specific number from a web scrape, however I keep running into a run-time error '91' and I simply cannot figure out how to fix this. I have searched countless stackoverflow questions, youtube videos and generic google searches, however have not been successful in finding out the error on my own.
Here is the code:
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.Navigate ("http://brokercheck.finra.org")
Do
DoEvents
Loop Until IE.ReadyState = 4

'Enter values from the corresponding sheet
'Set some generic typing for ease
Set doc = IE.document

    doc.GetElementbyID("GenericSearch_IndividualSearchText").Value = Worksheets("Master").Range("D203")
    doc.GetElementbyID("GenericSearch_EmploymingFirmSearchText").Value = Worksheets("Master").Range("C203")

    Set elements = doc.getElementsByTagName("button")
    For Each element In elements
    If element.getAttribute("type") = "submit" Then
        element.Click
        Exit For
    End If
    Next element

Do
DoEvents
Loop Until IE.ReadyState = 4

'find CRD#
    Set crd = doc.getElementsByClassName("summarydisplaycrd")(0).innerText 'here is where the run time error occurs
    MsgBox crd

and the HTML I am trying to get the information from:

 [redacted] (CRD# 5944070)

A:

I'm reviewing this code and the finra.org site, and have the following observations, which when addressed, should resolve the problem.

The HTML example you provided is simply incorrect, based on the actual HTML that is returned from the "Check" button.
The actual HTML returned looks like this, and the classname is "displayname", not "summarydisplaycrd":

                [redacted] (CRD# 123456789)

Your code exits the For each element loop upon finding the first "submit" button. This may not be the "Check" button (although I can get results either way, you may want to add more logic in the code to ensure the "Check " button is submit.

UPDATE
On further review, while I can replicate the Type 91 error, I still don't know why your class name appears different than mine (maybe an IE11 thing, dunno...) in any case, I'm able to resolve that by forcing a longer delay, as in this case the DoEvents loop is simply not adequate (sometimes this is the case when data is served dynamically from external functions, the browser is ReadyState=4 and .Busy=True, so the loop doesn't do anything)
I use the WinAPI Sleep function and force a 1 second delay after the "Click" button pressed, looping on condition of ReadyState = 4 and .Busy=True.
NOTE you will need to modify the classname parameter depending on how it is appearing on your HTML.
Option Explicit
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sub finra()
Dim IE As Object
Dim doc As Object, element As Object, elements As Object, crd

Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.Navigate ("http://brokercheck.finra.org")

Call WaitIE(IE, 1000)

'Enter values from the corresponding sheet
'Set some generic typing for ease
Set doc = IE.document

    doc.GetElementbyID("GenericSearch_IndividualSearchText").Value = "steve"
    doc.GetElementbyID("GenericSearch_EmploymingFirmSearchText").Value = "ed"

    Set elements = doc.getElementsByTagName("button")
    For Each element In elements
    If element.getAttribute("type") = "submit" Then
        If element.innerText = "Check " Then
            element.Click
            Exit For
        End If
    End If
    Next element

Call WaitIE(IE, 1000)

Dim itms As Object
'Set itms = doc.getElementsByClassName("displaycrd")
    crd = doc.getElementsByClassName("displaycrd")(0).innerText 'here is where the run time error occurs
    MsgBox crd
End Sub

Sub WaitIE(IE As Object, Optional time As Long = 250)
Dim i As Long
Do
    Sleep time
    Debug.Print CStr(i) & vbTab & "Ready: " & CStr(IE.ReadyState = 4) & _
                vbCrLf & vbTab & "Busy: " & CStr(IE.Busy)
    i = i + 1
Loop Until IE.ReadyState = 4 And Not IE.Busy
End Sub


Q:

Does build made on xcode 3.2 runs on IOS 5

May be this will be silliest question but users are facing such problems.
Sorry for same.
I have made build on xcode 3.2 which has maximum IOS 4.3 and uploaded on itunes.
Now users which are downloading application having IOS 5.0 says that application is getting crashed or vanished.
So, just want to ask that build made on xcode 3.2 runs on IOS 5.0
Please help.....
Thanks a lot....

A:

The short answer is that you have a bug in your app.
An app compiled for iOS 4.3 should work just fine. However, as with any update to the operating system, ambiguities in API calls are tightened, undocumented behaviours vanish and some APIs become deprecated. Deprecations won't cause problems (yet), though both of the others might.
For this reason you should be testing with new versions as they become available.


Q:

What is the namespace for UploadedFile in C#

I am getting the type or namespace name could not be found error at UploadedFile . Please tell me what is the namespace for UploadedFile.
 if (RadAsyncUploadAttachmnt.UploadedFiles.Count > 0)
            {
                foreach (UploadedFile file in RadAsyncUploadAttachmnt.UploadedFiles)
                {
                    try
                    {
                        System.Net.Mail.Attachment attachment;
                        string strFileName = string.Empty;
                        strFileName = System.IO.Path.GetFullPath(file.FileName);
                        attachment = new System.Net.Mail.Attachment(file.InputStream, file.GetName());
                        message.Attachments.Add(attachment);
                    }
                    catch { }
                }
            }

Thank you.

A:

Its not a part of C# built in libraries.
Its a 3rd party Telerik.WebControls you are using


Q:

Iterating over a text file using Fortran like format in C++

I am making an application that deals with txt file data.
The idea is that txt files may come in different formats, and it should be read into C++.
One example might be 3I2, 3X, I3, which should be done as: "first we have 3 integers of length 2, then we have 3 empty spots, then we have 1 integer of length 3.
Is the best to iterate over the file, yielding lines, followed by iterating over the lines as strings? What would be an effective approach for iterating smartly leaving out the 3 spots to be ignored?
E.g.
101112---100
102113---101
103114---102

to:
10, 11, 12, 100
10, 21, 13, 101
10, 31, 14, 102

A:

The link given by Kyle Kanos is a good one; *scanf/*printf format strings map pretty well onto fortran format strings.  It's actually easier to do this using C-style IO, but using C++ style streams is doable as well:
#include <cstdio>
#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream fortranfile;
    fortranfile.open("input.txt");

    if (fortranfile.is_open()) {

        std::string line;
        getline(fortranfile, line);

        while (fortranfile.good()) {
            char dummy[4];
            int i1, i2, i3, i4;

            sscanf(line.c_str(), "%2d%2d%2d%3s%3d", &i1, &i2, &i3, dummy, &i4);

            std::cout << "Line: '" << line << "' -> " << i1 << " " << i2 << " "
                      << i3 << " " << i4 << std::endl;

            getline(fortranfile, line);
        }
    }

    fortranfile.close();

    return 0;
}

Running gives
$ g++ -o readinput readinput.cc
$ ./readinput
Line: '101112---100' -> 10 11 12 100
Line: '102113---101' -> 10 21 13 101
Line: '103114---102' -> 10 31 14 102

Here the format string we're using is %2d%2d%2d%3s%3d - 3 copies of %2d (decimal integer of width 2) followed by %3s (string of width 3, which we read into a variable we never use) followed by %3d (decimal integer of width 3).

A:

Given that you wish to dynamically parse Fortran Format specifier flags, you should note that: you've immediately walked into the realm of parsers.
In addition to the other methods of parsing such input that others have noted here:

By using Fortran and CC/++ bindings to do the parsing for you.
Using pure C++ to parse it for you by writing a parser using a combination of:

sscanf
streams

My proposal is that if boost is available to you, you can use it to implement a simple parser for on-the-fly operations, using a combination of Regexes and STL containers.
From what you've described, and what is shown in different places, you can construct a naive implementation of the grammar you wish to support, using regex captures:
(\\d{0,8})([[:alpha:]])(\\d{0,8})

Where the first group is the number of that variable type.
The second is the type of the variable.
and the third is the length of variable type.

Using this reference for the Fortran Format Specifier Flags, you can implement a naive solution as shown below:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <cstdlib>
#include <boost/regex.hpp>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

//A POD Data Structure used for storing Fortran Format Tokens into their relative forms
typedef struct FortranFormatSpecifier {
    char type;//the type of the variable
    size_t number;//the number of times the variable is repeated
    size_t length;//the length of the variable type
} FFlag;

//This class implements a rudimentary parser to parse Fortran Format
//Specifier Flags using Boost regexes.
class FormatParser {
public:
    //typedefs for further use with the class and class methods
    typedef boost::tokenizer<boost::char_separator<char> > bst_tokenizer;
    typedef std::vector<std::vector<std::string> > vvstr;
    typedef std::vector<std::string> vstr;
    typedef std::vector<std::vector<int> > vvint;
    typedef std::vector<int> vint;

    FormatParser();
    FormatParser(const std::string& fmt, const std::string& fname);

    void parse();
    void printIntData();
    void printCharData();

private:
    bool validateFmtString();
    size_t determineOccurence(const std::string& numStr);
    FFlag setFortranFmtArgs(const boost::smatch& matches);
    void parseAndStore(const std::string& line);
    void storeData();

    std::string mFmtStr;                //this holds the format string
    std::string mFilename;              //the name of the file

    FFlag mFmt;                         //a temporary FFlag variable
    std::vector<FFlag> mFortranVars;    //this holds all the flags and details of them
    std::vector<std::string> mRawData;  //this holds the raw tokens

    //this is where you will hold all the types of data you wish to support
    vvint mIntData;                     //this holds all the int data
    vvstr mCharData;                    //this holds all the character data (stored as strings for convenience)
};

FormatParser::FormatParser() : mFmtStr(), mFilename(), mFmt(), mFortranVars(), mRawData(), mIntData(), mCharData() {}
FormatParser::FormatParser(const std::string& fmt, const std::string& fname) : mFmtStr(fmt), mFilename(fname), mFmt(), mFortranVars(), mRawData(), mIntData(), mCharData() {}

//this function determines the number of times that a variable occurs
//by parsing a numeric string and returning the associated output
//based on the grammar
size_t FormatParser::determineOccurence(const std::string& numStr) {
    size_t num = 0;
    //this case means that no number was supplied in front of the type
    if (numStr.empty()) {
        num = 1;//hence, the default is 1
    }
    else {
        //attempt to parse the numeric string and find it's equivalent
        //integer value (since all occurences are whole numbers)
        size_t n = atoi(numStr.c_str());

        //this case covers if the numeric string is expicitly 0
        //hence, logically, it doesn't occur, set the value accordingly
        if (n == 0) {
            num = 0;
        }
        else {
            //set the value to its converted representation
            num = n;
        }
    }
    return num;
}

//from the boost::smatches, determine the set flags, store them
//and return it
FFlag FormatParser::setFortranFmtArgs(const boost::smatch& matches) {
    FFlag ffs = {0};

    std::string fmt_number, fmt_type, fmt_length;

    fmt_number = matches[1];
    fmt_type = matches[2];
    fmt_length = matches[3];

    ffs.type = fmt_type.c_str()[0];

    ffs.number = determineOccurence(fmt_number);
    ffs.length = determineOccurence(fmt_length);

    return ffs;
}

//since the format string is CSV, split the string into tokens
//and then, validate the tokens by attempting to match them
//to the grammar (implemented as a simple regex). If the number of
//validations match, everything went well: return true. Otherwise:
//return false.
bool FormatParser::validateFmtString() {
    boost::char_separator<char> sep(",");
    bst_tokenizer tokens(mFmtStr, sep);
    mFmt = FFlag();

    size_t n_tokens = 0;
    std::string token;

    for(bst_tokenizer::const_iterator it = tokens.begin(); it != tokens.end(); ++it) {
        token = *it;
        boost::trim(token);

        //this "grammar" is based on the Fortran Format Flag Specification
        std::string rgx = "(\\d{0,8})([[:alpha:]])(\\d{0,8})";
        boost::regex re(rgx);
        boost::smatch matches;

        if (boost::regex_match(token, matches, re, boost::match_extra)) {
            mFmt = setFortranFmtArgs(matches);
            mFortranVars.push_back(mFmt);
        }
        ++n_tokens;
    }

    return mFortranVars.size() != n_tokens ? false : true;
}

//Now, parse each input line from a file and try to parse and store
//those variables into their associated containers.
void FormatParser::parseAndStore(const std::string& line) {
    int offset = 0;
    int integer = 0;
    std::string varData;
    std::vector<int> intData;
    std::vector<std::string> charData;

    offset = 0;

    for (std::vector<FFlag>::const_iterator begin = mFortranVars.begin(); begin != mFortranVars.end(); ++begin) {
        mFmt = *begin;

        for (size_t i = 0; i < mFmt.number; offset += mFmt.length, ++i) {
            varData = line.substr(offset, mFmt.length);

            //now store the data, based on type:
            switch(mFmt.type) {
                case 'X':
                  break;

                case 'A':
                  charData.push_back(varData);
                  break;

                case 'I':
                  integer = atoi(varData.c_str());
                  intData.push_back(integer);
                  break;

                default:
                  std::cerr << "Invalid type!\n";
            }
        }
    }
    mIntData.push_back(intData);
    mCharData.push_back(charData);
}

//Open the input file, and attempt to parse the input file line-by-line.
void FormatParser::storeData() {
    mFmt = FFlag();
    std::ifstream ifile(mFilename.c_str(), std::ios::in);
    std::string line;

    if (ifile.is_open()) {
        while(std::getline(ifile, line)) {
            parseAndStore(line);
        }
    }
    else {
        std::cerr << "Error opening input file!\n";
        exit(3);
    }
}

//If character flags are set, this function will print the character data
//found, line-by-line
void FormatParser::printCharData() {
    vvstr::const_iterator it = mCharData.begin();
    vstr::const_iterator jt;
    size_t linenum = 1;

    std::cout << "\nCHARACTER DATA:\n";

    for (; it != mCharData.end(); ++it) {
        std::cout << "LINE " << linenum << " : ";
        for (jt = it->begin(); jt != it->end(); ++jt) {
            std::cout << *jt << " ";
        }
        ++linenum;
        std::cout << "\n";
    }
}

//If integer flags are set, this function will print all the integer data
//found, line-by-line
void FormatParser::printIntData() {
    vvint::const_iterator it = mIntData.begin();
    vint::const_iterator jt;
    size_t linenum = 1;

    std::cout << "\nINT DATA:\n";

    for (; it != mIntData.end(); ++it) {
        std::cout << "LINE " << linenum << " : ";
        for (jt = it->begin(); jt != it->end(); ++jt) {
            std::cout << *jt << " ";
        }
        ++linenum;
        std::cout << "\n";
    }
}

//Attempt to parse the input file, by first validating the format string
//and then, storing the data accordingly
void FormatParser::parse() {
    if (!validateFmtString()) {
        std::cerr << "Error parsing the input format string!\n";
        exit(2);
    }
    else {
        storeData();
    }
}

int main(int argc, char **argv) {
    if (argc < 3 || argc > 3) {
        std::cerr << "Usage: " << argv[0] << "\t<Fortran Format Specifier(s)>\t<Filename>\n";
        exit(1);
    }
    else {
        //parse and print stuff here
        FormatParser parser(argv[1], argv[2]);
        parser.parse();

        //print the data parsed (if any)
        parser.printIntData();
        parser.printCharData();
    }
    return 0;
}

This is standard c++98 code and can be compiled as follows:
g++ -Wall -std=c++98 -pedantic fortran_format_parser.cpp -lboost_regex

BONUS
This rudimentary parser also works on Characters too (Fortran Format Flag 'A', for up to 8 characters). You can extend this to support whatever flags you may like by editing the regex and performing checks on the length of captured strings in tandem with the type.
POSSIBLE IMPROVEMENTS
If C++11 is available to you, you can use lambdas in some places and substitute auto for the iterators.
If this is running in a limited memory space, and you have to parse a large file, vectors will inevitably crash due to the way how vectors manages memory internally. It will be better to use deques instead. For more on that see this as discussed from here:
http://www.gotw.ca/gotw/054.htm
And, if the input file is large, and file I/O is a bottleneck, you can improved performance by modifying the size of the ifstream buffer:
How to get IOStream to perform better?
DISCUSSION
What you will notice is that: the types that you're parsing must be known at runtime, and any associated storage containers must be supported in the class declaration and definition.
As you would imagine, supporting all types in one main class isn't efficient. However, as this is a naive solution, an improved full solution can be specialized to support these cases.
Another suggestion is to use Boost::Spirit. But, as Spirit uses a lot of templates, debugging such an application is not for the faint of heart when errors can and do occur.
PERFORMANCE
Compared to @Jonathan Dursi's solution, this solution is slow:
For 10,000,000 lines of randomly generated output (a 124MiB file) using this same line format ("3I2, 3X, I3"):
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main(int argc, char **argv) {
    srand(time(NULL));
    if (argc < 2 || argc > 2) {
        printf("Invalid usage! Use as follows:\t<Program>\t<Output Filename>\n");
        exit(1);
    }

    ofstream ofile(argv[1], ios::out);
    if (ofile.is_open()) {
        for (int i = 0; i < 10000000; ++i) {
             ofile << (rand() % (99-10+1) + 10) << (rand() % (99-10+1) + 10) << (rand() % (99-10+1)+10) << "---" << (rand() % (999-100+1) + 100) << endl;
        }
    }

    ofile.close();
    return 0;
}

My solution:
0m13.082s
0m13.107s
0m12.793s
0m12.851s
0m12.801s
0m12.968s
0m12.952s
0m12.886s
0m13.138s
0m12.882s

Clocks an average walltime of 12.946s
Jonathan Dursi's solution:
0m4.698s
0m4.650s
0m4.690s
0m4.675s
0m4.682s
0m4.681s
0m4.698s
0m4.675s
0m4.695s
0m4.696s

Blazes with average walltime of 4.684s
His is faster than mine by at least 270% with both on O2.
However, since you don't have to actually modify the source code every time you want to parse an additional format flag, then this solution is more optimal.
Note: you can implement a solution that involves sscanf / streams that only requires you to know what type of variable you wish to read (much like mine), but the additional checks such as verifying the type(s) bloats development time. (This is why I offer my solution in Boost, because of the convenience of tokenizers and regexes - which makes the development process easier).
REFERENCES
http://www.boost.org/doc/libs/1_34_1/libs/regex/doc/character_class_names.html

A:

You could translate 3I2, 3X, I3 in a scanf format.


Q:

Was bedeutet „einmal zu oft“?

Einmal zu oft scheint ein fester Ausdruck zu sein.
Die Bedeutung der einzelnen Wörter ist klar, allerdings erschließt sich mir die Bedeutung im Kontext nicht.

Ich habe einmal zu oft erfolglos nach einem passenden Script oder Plugin für den trueSpace Workspace gestöbert.

Wer also lieber einmal zu oft davonlief als einmal zu wenig, geriet zwar häufiger außer Atem, kam aber ungeschoren davon.

Was bedeutet einmal zu oft?

A:

Eigentlich ist der Sinn der Phrase klar, daher versuche ich es mit einem Beispiel zu erklären:
Jemand spielt mit einem Revolver russisches Roulett. Fünfmal hat er bereits den Abzug betätigt, ohne dass sich ein Schuss gelöst hat. Beim sechsten Mal stirbt er.
Er hätte spätestens nach der fünften Runde aufhören müssen, dann hätte er überlebt. Er hat aber einmal zu oft mit seinem Leben gespielt, und nun ist er tot.


Q:

Best method for paying out of network licensed professional counselor?

I am interested in a specific LPC (Licensed Professional Counselor) because I like their model and services, but they are out of network. I have very limited understanding in the medical/insurance field so my questions may come off rudimentary (or just confusing :).
How feasible is it for a counseling group to "apply" for in-network status? What are some of the reasons why behavioral professionals are not in network with insurance companies?

A:

1. How feasible is it for a counseling group to "apply" for in-network status?
Generally, this is pretty easy. Every insurer will have different specific methods, but generally it will come down to how many members covered by the insurance are likely to visit that provider (there's little point in contracting individually with a practice 6000 miles away from their main region, and never visited by members), and whether or not the provider can/will accept the rates the insurer offers.
Some providers also decline to contract with insurers because the burden of doing so is too high for them (too much bureaucratic back-and-forth, too many prior authorizations required, too much hassle resolving bills, etc.).
Other criteria may apply, again specific to each insurer, which may preclude the provider from being in the insurer's network. For example, a surgeon with a disproportionately high mortality rate (compared with similar surgeons in the network and region) may be summarily rejected for contracting with a particular insurer. There is very little downside to asking about contracting.
2. Why are behavioral professionals not in-network with insurance companies?
This one is too broad to answer in the general case. There are countless reasons why an insurer might not contract with a specific provider. Maybe they can't agree on rates, maybe the provider doesn't have a credential that the insurer requires for that specialty, maybe market consolidation (on either side) makes contracting unattractive for some broad, market-competition perspective, maybe the provider uses methods that the insurer thinks are ineffective, and numberless others.
It could simply be that neither the insurer or the provider have approached each other about contracting.
There may also be an arrangement you're not aware of. Some insurers just don't cover some services (if they don't cover behavioral health issues, then a behavioral health-focused provider is not likely to be in their network). Some insurers use what's referred to as a carve-out, where that insurer doesn't cover the conditions directly but "buys" that coverage from a different insurer, which handles those claims but may have its own network which doesn't match your primary insurer's. In the U.S., this has long been a common practice for behavioral health coverage (often to manage premiums for members which don't use those services).
3. What is the best method for paying an out of network LPC?
It depends on how your insurance policy handles out-of-network providers. What I would do, in order:

Check with the insurer about what rates they pay for out-of-network
services in this category.
This may be explained in your plan documentation (not necessarily very clearly), but even if it isn't the insurer should be able to quickly determine this.
In addition to the rates they pay directly to the provider, your cost-sharing may change as well (out-of-network providers typically feature higher copays and deductibles than in-network, and may have other service exclusions). If out-of-network services are not covered at all in this case, then going through the insurance is probably not going to be helpful.
Check with the provider about how they handle patients without
insurance coverage.
Lack of coverage is a pretty common issue, especially when it comes to networks. This provider almost certainly has policies in place that describe what rates are charged to patients without coverage. If those rates are affordable for you, then simply not using the insurance may be an option. It's frequently the case that special sliding-scale rates are available for patients without insurance (or with insurance that's not adequate).


Q:

Upload multiple file at once php html

Can someone help me to make my code more simple and effective ? srry i'm just a newbie. I'm trying to upload multiple file at once but the action just take one upload. Pls fix my code thx
<input type="file" name="photo" id="fileSelect" multiple="multiple"><?php echo $photo_err;?>

<input type="file" name="photo2" id="fileSelect" multiple="multiple"><?php echo $photo_err;?>

if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
    $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
    $filename = $_FILES["photo"]["name"];
    $filetype = $_FILES["photo"]["type"];
    $filesize = $_FILES["photo"]["size"];
    $temp = explode(".", $_FILES["photo"]["name"]);
    $newfilename = round(microtime(true)) . '.' . end($temp);
    // Verify file extension
    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    if(!array_key_exists($ext, $allowed))
        die("Error: Please select a valid file format.");

    // Verify file size - 5MB maximum
    $maxsize = 5 * 1024 * 1024;
    if($filesize > $maxsize)
        die("Error: File size is larger than the allowed limit.");

    // Verify MYME type of the file
    if(in_array($filetype, $allowed)){
        move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $newfilename);
    } else{
        echo "Error: There was a problem uploading your file. Please try again.";
    }
}
// No file was selected for upload, your (re)action goes here
if($_FILES['photo']['size'] == 0)
{
    $photo_err = "Please Select an Image.";
}

Also
if(isset($_FILES["photo2"]) && $_FILES["photo2"]["error"] == 0){
    $allowed2 = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
    $filename2 = $_FILES["photo2"]["name"];
    $filetype2 = $_FILES["photo2"]["type"];
    $filesize2 = $_FILES["photo2"]["size"];
    $temp2 = explode(".", $_FILES["photo2"]["name"]);
    $newfilename2 = round(microtime(true)) . '.' . end($temp2);
    // Verify file extension
    $ext2 = pathinfo($filename2, PATHINFO_EXTENSION);
    if(!array_key_exists($ext2, $allowed2))
        die("Error: Please select a valid file format.");

    // Verify file size - 5MB maximum
    $maxsize2 = 5 * 1024 * 1024;
    if($filesize2 > $maxsize2)
        die("Error: File size is larger than the allowed limit.");

    // Verify MYME type of the file
    if(in_array($filetype2, $allowed2)){
        move_uploaded_file($_FILES["photo2"]["tmp_name"], "upload/" . $newfilename2);
    } else{
        echo "Error: There was a problem uploading your file. Please try again.";
    }
}
// No file was selected for upload, your (re)action goes here
if($_FILES['photo2']['size'] == 0)
{
    $photo_err2 = "Please Select an Image.";
}

Any help will be grateful.Thx

A:

I think this what you looking for
    <?php
    define( 'MAX_ALLOWED_FILE_SIZE', 5 * 1024 * 1024 ); // 5Mo
    define( 'UPLOAD_PATH', 'upload' );

    function is_allowed_file_ext( $filename = null )
    {
        $allowed_ext = array("jpg", "jpeg", "gif", "png");
        $_parts = explode( '.', $filename );
        $_ext = end( $_parts );
        $_ext = strtolower( $_ext );
        if( in_array( $_ext , $allowed_ext ) ){
            return $_ext;
        }
        return false;
    }

    if( !empty( $_FILES['photo'] ) ){
        foreach ($_FILES['photo']['name'] as $key => $filename ) {
            if( $_FILES['photo']['error'][$key] == UPLOAD_ERR_OK ){

                if( $file_ext = is_allowed_file_ext( $filename ) ){
                    $new_filename = sprintf( '%d-%s.%s', round(microtime(true)), uniqid(), $file_ext );
                    if( $_FILES['photo']['size'][$key] <= MAX_ALLOWED_FILE_SIZE ){
                        // Everything is okay now, save the file
                        $dest_path = sprintf( '%s/%s', rtrim(UPLOAD_PATH,'/'), $new_filename );
                        move_uploaded_file( $_FILES['photo']['tmp_name'][$key], $dest_path );
                    }else{
                        $photo_errors[] = 'Error: File size is larger than the allowed limit.';
                    }
                }else{
                    $photo_errors[] = $filename . ' is not a valid image';
                }
            }else{
                switch ( $_FILES['photo']['error'][$key] ) {
                    case UPLOAD_ERR_NO_FILE:
                        $photo_errors[] = 'No file sent';
                        break;
                    case UPLOAD_ERR_INI_SIZE:
                    case UPLOAD_ERR_FORM_SIZE:
                        $photo_errors[] = 'Max file size exceeded!';
                        break;
                    default:
                        $photo_errors[] = 'Unknown errors';
                        break;
                }
            }
        }
    }else{
        $photo_errors[] = 'No photos selected';
    }
    ?>
    <form method="post" enctype="multipart/form-data">
        <input type="file" name="photo[]" id="fileSelect" multiple="multiple">
        <?php foreach ($photo_errors as $photo_error):?>

<?php echo htmlspecialchars( $photo_error ); ?>

        <?php endforeach; ?>
        <button type="submit">Submit</button>
    </form>


Q:

Use a variable outside function

I'm trying to set numbers to be equal with digits.
How can I do that? I tried 'numbers' : digits but it doesn't work.
// Checks if the checkbox is checked or not
$('#digits').change(
  function(){
    if ($(this).is(':checked')) {
      digits = true;
    } else {
      digits = false;
    }
});

// When the button "apply" is pressed it sets numbers equal to digits and calls the function test
$(document).ready(function(){
    $('#apply').test({
        'numbers': digits // This is where I'm stuck
    });
});

(function($){
  var methods = {
    init : function( options, callbacks) {
      var settings = $.extend({
        'numbers': true,
    }, options);
    ...
    ...
    ...
    etc
    $.fn.test= function(method) {
      alert("SUCCESS");
      ...
      ...
    };
})(jQuery);

Working Example (JSFIDDLE)

A:

When you initialise your plugin you are giving it the value of digits at that stage. From the code you've posted, I'd guess that it is undefined. You need to update the value on the plugin each time it is changed via the checkbox.
A quick fix would be to move the code which initialises the plugin to the change handler of your checkbox, though you might also consider initialising the plugin once and implementing a setter method to allow you to update the value on the plugin after it has been initialised.
   // Checks if the checkbox is checked or not
    $('#digits').change(
      function(){

        $('#apply').test({
            'numbers': this.checked
        });
    });


Q:

How to make bootstrap column height to 100% row height?

I haven't found a suitable solution to this and it seems so trivial.
I have two columns inside a row:

sdfsdf

sdfsdf

sdfsdf

asdfdf

The row height is set by the larger row, left-side. However, I want the right side's height to be the same.
This seems intuitive, but it doesn't work
.left-side {
    background-color: blue;
}
.something {
    height: 100%;
    background-color: red;
}
.row {
    background-color: green;
}

http://jsfiddle.net/ccorcos/jz8j247x/

A:

You can solve that using display table.
Here is the updated JSFiddle that solves your problem.
CSS
.body {
    display: table;
    background-color: green;
}

.left-side {
    background-color: blue;
    float: none;
    display: table-cell;
    border: 1px solid;
}

.right-side {
    background-color: red;
    float: none;
    display: table-cell;
    border: 1px solid;
}

HTML

sdfsdf

sdfsdf

sdfsdf

sdfsdf

sdfsdf

sdfsdf

            asdfdf

A:

@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs sizes so you won't notice, but if you used anything else (e.g. col-sm, col-md, etc), you'd understand.
Another approach is to play with margins and padding. See the updated fiddle:
http://jsfiddle.net/jz8j247x/1/
.left-side {
  background-color: blue;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.something {
  height: 100%;
  background-color: red;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.row {
  background-color: green;
  overflow: hidden;
}


Q:

degenerating immersion

Initial question:
I would like to know if there exists a sequence of $C^2$ immersions $f_k : S^2 \rightarrow \mathbb{R}^3$ which converge (in the $C^2$ topology) to $z^2$ except on a finite set of points, i.e. $f_k \rightarrow z^2$ in $C^2_{\text{loc}}(S^2\setminus \{ a_1, \dots , a_n \})$.
Above, $S^2$ is identified with $\hat{\mathbb{C}}$, the Riemann sphere. Hence, the function $z^2: \hat{\mathbb{C}} \rightarrow \hat{\mathbb{C}} \sim S^2 \subset \mathbb{R}^3$ makes sense. In fact, my question is about any rational function $P/Q$ where $P$ and $Q$ are two elements of $\mathbb{C}[z]$; but we can start with $z^2$ in order to make it clearer.
The problem looks very hard topologically. For instance, if I assume "embedded" instead of "immersed", it is not very difficult to prove that such a sequence doesn't exist. But I am unable to show more.
Further questions:
Assuming there exists a sequence of immersions $f_k : S^2 \rightarrow \mathbb{R}^3$ satisfying the conditions in the first question, I would then like to know the following:

Can the immersions $f_k$ all extend to immersions from the closed ball to $\mathbb{R}^3$?
Can the sequence of immersions $f_k$ be chosen to have curvature bounded above?
How to produce such a sequence in the case of a general rational function? This problem reminds me of the sphere eversion: there appears to be no topological obstruction but it is hard to construct an explicit map.

I hope this is clear.
Thanks in advance for your contribution.

A:

There is no such sequence.
For an immersion $f_k\colon \mathbb S^2 \rightarrow \mathbb{R}^3$ (after a small perturbation) the set of self-intersections is formed by some number of closed curves $\gamma_1,,\gamma_2,\dots \gamma_n,$ in $\mathbb R^3$.
So any plane which intercets all $\gamma_i$ transversally, has to intersect them at even number of points.
On the other hand the the equator plane say $\Pi$ (or its small perturbation) has to itersect it odd number of times. Indeed, the curves in $f_k^{-1}(\Pi)$ is close to equator $\mathbb S^2$; the turning number of its image in $\Pi$ is $2$;
so it has odd number of self-intersections. (This works for if $f_k$ is $C^1$-close to $z^2$ near $\Pi$, which is easy to arrange.)


Q:

BeautifulSoup4 Получить контент в зависимости от тега h3 и удалить этот тег

Получаю такой HTML-код при парсинге:

Описание Makita 4329 Лобзик электрический

Новый эргономичный дизайн

Удобная D-образная рукоятка с резиновыми вставками

Маятниковый ход

Характеристики Makita 4329 Лобзик электрический

                    Производитель
                     Makita

                    Страна происхождения
                     Япония

                    Штрих код:
                    088381083102

В нем есть нужные мне 2 div'a, с классами "col-md-6".
Мне нужно получить из них все кроме h3, вот пример:
получаю Описание

Новый эргономичный дизайн

Удобная D-образная рукоятка с резиновыми вставками

Маятниковый ход

получаю Характеристики

            Производитель
             Makita

            Страна происхождения
             Япония

            Штрих код:
            088381083102

Вот с какими проблемами я столкнулся:
1) Может быть такое, что один из блоков отсутствует и нужно как-то "понять", где Описание, а где Характеристики. За что в таком случае зацепится и какие методы библиотеки при этом задействовать?
2) Как мне удалить ненужные мне h3?

A:

Вы можете найти тег h3 в div и извлечь из него первое слово, которое и будет говорить о назначении блока. А затем использовать метод extract, чтобы удалить его после анализа.
Пример:
from bs4 import BeautifulSoup

def main():
    with open('index.html', encoding='utf-8') as f:
        html = f.read()
    soup = BeautifulSoup(html, 'lxml')

    divs = soup.find_all('div', {'class': 'col-md-6'})
    for div in divs:
        h3 = div.find('h3')
        title = h3.get_text().split()[0]
        h3.extract()

        print(f'{title}:')
        print(div.prettify())
        print('=' * 73, end='\n\n')

if __name__ == '__main__':
    main()

stdout:

Описание:

    Новый эргономичный дизайн

    Удобная D-образная рукоятка с резиновыми вставками

   Маятниковый ход

=========================================================================

Характеристики:

     Производитель

     Makita

     Страна происхождения

     Япония

     Штрих код:

     088381083102

=========================================================================


Q:

Is this intuition behind product manifolds correct?

I've been studying differential geometry on Spivak's books and recently I proved that the cartesian product of manifolds is another manifold. Right, however, what's the intuition behind this? I've tried to develop some intuition, but I'm not sure it's correct.
For instance, we can say that the cylinder $C$ is the product of the circle and the real line, in other words $C = S^1 \times \mathbb{R}$. My intuition says that we do define this way because identifying a point on a cylinder is equivalent to identifying a point on a circle and then the position of this point on a line. In other words, describing one point on a cylinder should be equivalent to describing one point on a circle plus one point on a line.
Another example, the thorus given by $T = S^1 \times S^1$, again what's the intuition behind it? My idea is: given that we can describe the torus as the result of rotating a circle around some axes we would describe a point on the torus to be one point on the circle being rotated plus one point on the circle that represents the trajectory of that particular point  during the rotation.
So in general, my intuition is that given $r$ manifolds $M_1, \dots, M_r$ their product is a manifold that each point can be described by one point on each manifold in a particular way depending on the case we are considering.
Is this intuition correct? Is this the way we should think about product manifolds?
Thanks in advance for your help.

A:

For the product manifold there is a different explanation.
Take the example $S^1\times\mathbb R$. This means that at each point of the circle $S^1$ you attach the whole real line!! So in this way, going round the circle and attaching everywhere a real line you get a cylinder.
For the other example : $\mathbb T^2=S^1\times S^1$. At each point of a circle attach another circle (orthogonal to the 1st circle). Then, if for all points of the circle you attach an orthogonal circle, you are going to get the torus!
It's pretty fascinating how intuition works here!


Q:

Preg match does not find the correct string

I have a problem where i have a script that supposed to search an XML file for matching strings.
Here's my script:
   <?php
$file = "klein.xml";
$lines = file($file);
foreach ($lines as $line_num => $line)
{
    echo htmlentities($line);
    echo "
";

}

   if (preg_match("/message/", htmlentities($line), $found))
   {
     echo "Found!";
     echo $found[0];
     echo "test";
   }
   else
   {
       echo "Not Found!";
   }
?>

and this is the xml file im working with:
    <?xml version="1.0" encoding="ISO-8859-1"?>
<product-data>
<message-header>
<message-id>OR-1361163557-gr</message-id>
<message-timestamp>1361163557</message-timestamp>
<export-version current_version="1">OGPDX-2.01.01</export-version>
</message-header>
</product-data>

The problem is when i preg match 'product' it works correctly but when i try to preg match another string i.e 'message' it doesnt work?
Im curious for the solution, thanks in advance!

A:

Can you check this code, I noticed that you put the if loop outside foreach; hence only the last line is executed.
<?php
$file = "klein.xml";
$lines = file($file);
foreach ($lines as $line_num => $line)
{
   if (preg_match("/message/", htmlentities($line), $found))
   {
     echo "Found ".$found[0]."
";
   }
}
?>


Q:

Is there any way to autoindent a section of text in vimscript?

I'd like to autoindent a range of lines in a Vim plugin I'm writing, but there doesn't seem to be an easy way. Short of an actual vimscript command, I've been looking for ex-mode commands I could use to trigger autoindenting, but I haven't found a way there either.
Is there any way to trigger the autoindentation of a range of lines in Vim, besides hitting just hitting "="?

A:

why can't you use =?
you could do
:normal! 3G=10G

to auto-indent 3,10 lines


Q:

Are nullable value types just wrappers around the regular value type?

The reason I ask is that you can cast a nullable type to a regular type with the Value property. That makes me think that the regular type is just wrapped up in the nullable type.

A:

Yes, it is a generic struct:
public struct Nullable<T> where T : struct, new()

This is probably more confusing if you've only seen the T? syntax - but that is just syntactic sugar, the compiler is changing it to Nullable<T>.
Source: http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx , http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx

A:

Yes - 'Nullable<T> Structure':

Represents an object whose underlying
  type is a value type that can also be
  assigned null like a reference type.

[BTW, if your curious you can use Reflector to 'look under the hood']


Q:

How to make Java GUI full screen and similar to Playstation 3

Case
This is not really a games project. Its a project which runs in full screen for showing video conferencing, and watching TV in high definition, and is controlled from a Remote control.
Wish:

I am looking for GUI libraries.
Is there only this method available for developing full screen applications?
http://download.oracle.com/javase/tutorial/extra/fullscreen/index.html
I need a nice looking GUI with nice GUI buttons/grid/multiple video screen 9 or 4 and good layout. (OR something similar to VCR or DVD player GUI in full screen)
For example

Question: Which Java GUI libraries i can use to make such above user interfaces?

A:

Swing with a custom PLAF, some nice icons for the buttons, a couple of background image panels (custom component, easy to create) and nested layouts (mostly AWT with some Swing) should be able to achieve that effect.  You could then put the UI into whatever top level container, JFrame, undecorated JFrame, JWindow, (draggable) JApplet etc. that best suits it.
See also the Full-Screen Exclusive Mode API lesson in the Java Tutorial.


Q:

Flask {{ STATIC_URL }} giving a 304 redirect when the static directory is unspecified

Let's say I have a Flask application where
app = Flask(__name__, static_url_path='')

That is, {{ STATIC_URL }} == "" (empty string) and the static files are not stored under a dedicated /static directory (e.g. http://www.example.com/img/logo.png instead of http://www.example.com/static/img/logo.png)
Is it ok if I just leave it this way? The GET requests to any URL that contains {{ STATIC_URL }} give a 304 redirect instead of a 200 status code if I leave the variable in my code.
Is it necessary to:

Delete all occurrences of {{ STATIC_URL }} in my templates?
Create a real static directory instead of just setting it equal to an empty string?
Leave all occurrences of {{ STATIC_URL }} in my templates so that I can set a new static directory in the future if necessary?

A:

HTTP response 304 is for "Redirection to a previously cached result".
This means Flask is telling your browser that it already has the content.
Clear your Browser cache and you will notice that Flask returns a 200 on your next request.


Q:

how to bind an item selected in list view to the other list?

I have created two simple list views. In the first list view I have put category as the item name. And it is the only item which i have included in list one. In the list view I jave put lot of items , say for example orange, Apple, Mango , Banana etc.what i want to know is that if the user selects one particular item in the second list view , I want the selected item to be shown in the first list view.So that it is easy to identify the item which was earlier selected by the user. please help me....
This is my 1st list view code:
public class bview extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setListAdapter(new ArrayAdapter(this,
            android.R.layout.simple_list_item_1, cat));
        getListView().setTextFilterEnabled(true);
    }

    static final String[] cat = new String[] {
        "Category", };
protected void onListItemClick(ListView parent, View v, int position,
                                                                        long id) {

            Intent intent= new Intent(bview.this,listview.class);
            startActivity(intent);
            //intent.putExtra("value", value);

        }}

2nd listview code:
    public class listview extends Activity
{

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.submain);

        ListView mlistView = (ListView) findViewById(R.id.listview);
        mlistView.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,
                new String[] {"orange", "apple","mango","banana","grapes"}));

 mlistView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
     public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3){
         Intent in2 =new Intent(listview.this, bview.class);
         startActivity(in2);
     }
public void onNothingSelected(AdapterView<?>arg0){
 }});

}}

I used onitemselected but if click orange nothing will be happend. where i should go to wrong in my code....

A:

In the second listview, use a setOnItemSelectedListener. When the user clicks on one of the items, add it to the datastructure backing your first ListView. So you'd do something like this in your onCreate in you second activity:
protected void onCreate(Bundle icicle){
  //setup your listview here
  myListview.setOnItemSelectedListener(new AdpaterView.OnItemSelectedListener(){
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
      //add particular item that was clicked to the backing datastructure
      // of your listview in the first activity here
    }

    public void onNothingSelected(AdapterView<?> parent){
      //don't do anything here
    }
  });
  //any other stuff in your onCreate
}


Q:

Why does Ruby function not break on 'true' in nested loop?

Here's a piece of Ruby code that checks if a given email address is part of the array of 'To:' receivers in my email class property. Code should return true when email_address is found in the list and false when not.
def is_to_receiver?(email_address)
  if @raw_email.to != nil
    @raw_email.to.each do |to_field|
      if to_field == email_address
        true
      else
        next
      end
    end
  end
  false
end

I always thought that true in line 5 would break the function immediately and return the function with value true. However, the result for a matching email address kept being the false from line 11. I had to change line 5 into return true to make this work.
I migrated the code from Ruby 1.8.7 into Ruby 1.9.3. and was pretty sure it worked fine before. I am curious if I simply made a mistake or that this behaviour changed since Ruby 1.9.3? Any replies welcome!

A:

In the absence of a return statement in a Ruby method, Ruby will return the value of the last statement executed. Otherwise, statements with just a literal on them are basically no-ops. Used in the middle of a loop, they won't return because they are never the last statement executed (other statements relating to processing the loop itself have to be executed).
Put another way, the implied return behavior only happens at the very end of a function (a bit oversimplified, but works for this context), and you need to use the return keyword everywhere else.


Q:

CAD annotation guide lines do not show in Arcmap

When I open a CAD file in Arcmap the annotation's guid lines and arrows linking to feature do not appear. see snapshots below.
how can I show thses guides in armap?

A:

I've ran into this as well. Annotations (they're called dimensions actually) are not read by ArcGIS. The only workaround I've found is to import the CAD data into a GDB using Data Interoperability.


Q:

Performance Clustermap in R

I found this very appealing chart about the performance of the S&P500 from the WSJ.:

I'm trying to recreate it in R but I have no idea how to best plot the data, eg
data<-data.frame(stock=c("A","B","C","D"),group=c(rep("Fin",2),rep("Ind",2)),Perf=rnorm(4,0,1),mvalue=abs(rnorm(4,100,50)))

Has anybody a idea how to recreate it (e.g. with ggplot2?) or has anybody ever done a similar plot? Thx in advance.

A:

treemapify is a ggplot2 solution, as you were hoping for.
https://github.com/wilkox/treemapify
And the results are beautiful & flexible - typical of ggplot2 and its extensions.

A:

Or portfolio:
require(portfolio)

dt<-data.frame(ticker=paste0(sample(LETTERS,100,T),sample(LETTERS,100,T),sample(LETTERS,100,T)),
           value=abs(rnorm(100,10000,4000)),
           perc_change=rnorm(100,0,0.1),
           group=sample(LETTERS[1:4],100,T)
               )

rownames(dt)

map.market(dt$ticker,lab=c(T,T), area=dt$value, group=dt$group, color=dt$perc_change, main="Stock Map")


Q:

how to find a number X, if we move the last digit to the first, will equal double X

"Move the last digit to the first" means: 12345 --> 51234
Someone tell me there must be an answer. I thought it should be very simple, but I just can not find any X even with coding. Anybody help?
public static void main(String[] args) {
    for(int i=10; s<99999; i++){
        if(2*i==convertInt(i)){
            System.out.println(i);
        }
    }
}

private static int convertInt(int i) {
    String s = i+"";
    int index = s.length()-1;
    String newS = s.charAt(index) + s.substring(0, index);
    return Integer.parseInt(newS);
}

A:

I used this function:
public static boolean isMultiple(int x) {
    String g = String.valueOf(x);
    g = g.substring(g.length()-1) + g.substring(0, g.length()-1);
    int y = Integer.parseInt(g);
    if(y == x * 2) return true;
    return false;
}

In this loop:
int x = 10;
while(!isMultiple(x)) {
    System.out.println(x + ", " + isMultiple(x));
    x++;
}

And I have gotten no true value up to 650 million. I have a strong feeling this isn't actually possible. My guess is that no number will work for this, but I'm going to leave this running. I'll edit this if I find one.
Edit: It seems there are numbers like this. See above.

A:

http://answers.yahoo.com/question/index?qid=20080207083949AAoBkqv
Let's start with the number without the two. Call it n.

If you multiply this by 10 and add 2 you would have your first number:
10n + 2

Doubling this you'd have:
20n + 4

This should be equivalent to taking n and putting a two in the front.
n + 2 * 10^d

Here d represents the number of digits.
20n + 4 = n + 2* 10^d

19n + 4 = 2 * 10^d
n = (2 * 10^d - 4) / 19

If you try values of d = 1, 2, 3, etc. you eventually get to n = 17 that gives you an integer result:
n = (2 * 10^17 - 4) / 19
n = (200000000000000000 - 4) / 19
n = 199999999999999996 / 19
n = 10526315789473684

Just put a 2 at the end and you have your answer:

105263157894736842
x 2
---------------------------------
210526315789473684

Edit: I just read Joseph's method and I like it better.

2 / 2 = 1 remainder 0 (carry down 1 to the next division)
1 / 2 = 0 remainder 1 (carry down 10 to the next division)
10 / 2 = 5 remainder 0 (carry down 5 to the next division)
5 / 2 = 2 remainder 1 (carry down 12 to the next division)
12 / 2 = 6 remainder 0 (carry down 6 to the next division)
6 / 2 = 3 remainder 0 (carry down 3 to the next division)
3 / 2 = 1 remainder 1 (carry down 11 to the next division)
11 / 2 = 5 remainder 1 (carry down 15 to the next division)
15 / 2 = 7 remainder 1 (carry down 17 to the next division)
17 / 2 = 8 remainder 1 (carry down 18 to the next division)
18 / 2 = 9 remainder 0 (carry down 9 to the next division)
9 / 2 = 4 remainder 1 (carry down 14 to the next division)
14 / 2 = 7 remainder 0 (carry down 7 to the next division)
7 / 2 = 3 remainder 1 (carry down 13 to the next division)
13 / 2 = 6 remainder 1 (carry down 16 to the next division)
16 / 2 = 8 remainder 0 (carry down 8 to the next division)
8 / 2 = 4 remainder 0 (carry down 4 to the next division)
4 / 2 = 2 remainder 0

You can stop here because you have gotten to a 2. Now read the digits going down:
105263157894736842

Note: technically you could repeat the process and get a larger number, but it would just be this sequence of digits repeated, e.g.:
105263157894736842 105263157894736842

One final note:
You could even do this the other direction and it might be easier:
The lowest digit is 2. If you double this, you get 4.
..42
Then double the 4:
..842
Then double the 8 (remember the carry):
..(1)6842
Then double the 6 and add the carry (13), that gets you another carry:
..(1)36842
Double the 3 and add the carry (7)
..736842
Double the 7 (remember the carry)
..(1)4736842
Double the 4 and add the carry (9)
..94736842
Double the 9 and remember the carry
..(1)894736842
Double the 8 and add the carry (17), remember the new carry:
..(1)7894736842
etc.
..(1)57894736842
..(1)157894736842
..3157894736842
..63157894736842
..(1)263157894736842
..5263157894736842
..(1)05263157894736842
Now when you double you get back to the digit 2 so you are done:

Answer:
105263157894736842

A:

Somebody much smarter than me figured out the mathematical equation for this question:
Parasitic Number Equation
...which gives you a good way to code a non-brute force approach.
(where n = number of digits, and a = offset)
txtResult.Text = string.Empty;
for (int n = 2; n <= 100; n++)
{
    if (((ulong)(Math.Pow(10, n)) - 2) % 19 == 0)
    {
        for (ulong a = 1; a <= 9; a++)
        {
            var omgwut = (ulong)((decimal)Math.Pow(10, n+1) / 19m) * a;

            txtResult.Text = string.Format("{0}, {1}", omgwut.ToString(), txtResult.Text);
        }
    }
}

Which ultimately gets you these results:
473684210526315789,
421052631578947368,
368421052631578947,
315789473684210526,
263157894736842105,
210526315789473684,
157894736842105263,
105263157894736842,
52631578947368421

I've decided that the person who posited this question to you is a sadist. :)


Q:

For a graph $C_n$, why do we have $\lvert\operatorname{Aut}(C_n)\rvert \geq 2 |R| = 2n$?

In the book of Algebraic Graph Theory by Godsil, at page 8, it is stated that

However, the group $\langle g\rangle$ is of order $n$ and the group $\langle h\rangle $ is of order 2, so shouldn't we have
$$|Aut(C_n)| \geq n+2$$
 ? I mean I couldn't understand the argument that the author makes. Can some help me to understand the reason why we have
$$|Aut(C_n)| \geq 2 |R| = 2n$$
?

A:

In addition to the automorphisms
$$
1,g,g^2,\dots,g^{n-1}
$$
there are also
$$
h,hg,hg^2,\dots,hg^{n-1}
$$
making for at least $2n$ automorphisms. The first list is $R$, the second list is the set $hR=\{hr:r\in R\}$. This is called a coset of R, and is the second coset that text mentions.


Q:

What is the difference between SAN Hard Drives and Normal Hard Drives?

At work, we have decided to finally virtualize and have decided to upgrade out SAN setup with higher capacity Hard Drives. However, what exactly is the difference between Hard Drives that come packaged with a SAN set up, or going to New Egg and picking up a bunch of 1 TB hard drives?
I ask because the quote we received for a new SAN set up with 12 TB (6 TB usable) capacity was $15,000 which seems INSANELY high, especially since I could go to New Egg and pick up 12 TB hard drives for ~$1,500.

A:

Well there may be obvious differences, such as interface type, rotational speed, etc.
Beyond that, even when two disks have identical entries for the above spec, the drives that come in a SAN will probably be certified/warranted for 24hr continuous operation, and may also include custom firmware from the SAN manufacturer.
As for the price difference - if you're buying a decent (or even semi-decent SAN) you are buying a lot more than a bunch of hard disks - the drives may only be a relatively small part of the cost.

A:

The drives themselves will usually be high-end, high-rotation drives, possibly with custom firmwares installed to run on the particular SAN.  They are probably sole- or restricted-sourced, meaning the SAN vendor is paying a bit of a premium to ensure that they can get EXACTLY these drives for the next period of time.
There's far more to a SAN than just hard drives.
There's the RAID controllers.  There's the networking components.  There's the physical shell the drives come in, with associated power (frequently redundant).  There's the software that has been written to run, monitor, and manage the whole thing.  There's a large quality and testing organization which is there to ensure that when you get it, it "just works".  And there's probably a warranty service that will have a replacement drive show up within 8 to 24 hours should one fail.
Plus there's the fact that you are using this to gain some cost- or operational-efficiencies, and the vendor is simply monetizing some of that efficiency for themselves.
Sure, you could buy 12TB of drive space for $1500.  But you would still need a computer (or two) to put them in, an OS to present them to the network, and someone to make sure it would work and be reasonably redundant.


Q:

How to recover a crashed innodb table...?

I Have a Innodb table i got the error as
mysql> check table City;
+-------------------+-------+----------+----------------------------------------------------------+
| Table             | Op    | Msg_type | Msg_text                                                 |
+-------------------+-------+----------+----------------------------------------------------------+
| world_innodb.City | check | Error    | Incorrect information in file: './world_innodb/City.frm' |
| world_innodb.City | check | error    | Corrupt                                                  |
+-------------------+-------+----------+----------------------------------------------------------+
2 rows in set (0.00 sec)

I don't have changed anything in my.cnf.I don't know how it get crashed.
How can i recover it
...
Content of error log are as
120207 11:50:47 InnoDB: highest supported file format is Barracuda.
120207 11:50:47  InnoDB: Waiting for the background threads to start
120207 11:50:48 InnoDB: 1.1.8 started; log sequence number 5713326
120207 11:50:48 [Note] Event Scheduler: Loaded 0 events
120207 11:50:48 [Note] /usr/local/mysql/bin/mysqld: ready for connections.
Version: '5.5.20-log'  socket: '/tmp/mysql.sock'  port: 3306  MySQL Community Server (GPL)
120207 11:50:57 [ERROR] /usr/local/mysql/bin/mysqld: Incorrect information in file: './world_innodb/City.frm'

EDIT
Someone has opened the City.frm file and modified it's content.So How will I recover it.? I am using innodb_file_per_table.
UPDATE: Adding my.cnf as asked by some peoples.
Innodb Specific variables  in My.Cnf
innodb_file_per_table
innodb_data_home_dir            = /usr/local/mysql/data
innodb_data_file_path           = ibdata1:10M:autoextend
innodb_log_group_home_dir       = /usr/local/mysql/data
innodb_buffer_pool_size         = 1G
innodb_additional_mem_pool_size = 2M
innodb_log_file_size            = 128M
innodb_log_files_in_group       = 2
innodb_log_buffer_size          = 8M
innodb_flush_log_at_trx_commit  = 1
innodb_lock_wait_timeout        = 50
innodb_force_recovery           = 4

A:

I created a table called test2
CREATE TABLE `test2` (   `t` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

I then inserted one record
insert into test2 values(1);

I stopped MySQL and then added a bunch of characters to the test2.frm file with vi.
I then started MySQL and saw the following
mysql> show table status \G;
*************************** 1. row ***************************
           Name: test2
         Engine: NULL
        Version: NULL
     Row_format: NULL
           Rows: NULL
 Avg_row_length: NULL
    Data_length: NULL
Max_data_length: NULL
   Index_length: NULL
      Data_free: NULL
 Auto_increment: NULL
    Create_time: NULL
    Update_time: NULL
     Check_time: NULL
      Collation: NULL
       Checksum: NULL
 Create_options: NULL
        Comment: Incorrect information in file: './test2/test2.frm'

I then created another table with the same structure
CREATE TABLE `test3` (   `t` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

I then stopped mysql and copied test3.frm over test2.frm
cp /var/lib/mysql/testdb/test3.frm /var/lib/mysql/testdb/test2.frm

I restarted MySQL and had access to test2
mysql> show table status \G;
*************************** 1. row ***************************
           Name: test2
         Engine: InnoDB
        Version: 10
     Row_format: Compact
           Rows: 1
 Avg_row_length: 16384
    Data_length: 16384
Max_data_length: 0
   Index_length: 0
      Data_free: 25675431936
 Auto_increment: NULL
    Create_time: 2012-02-07 16:24:20
    Update_time: NULL
     Check_time: NULL
      Collation: latin1_swedish_ci
       Checksum: NULL
 Create_options:
        Comment:

Here is the record that I inserted
mysql> select * from test2;
+------+
| t    |
+------+
|    1 |
+------+
1 row in set (0.00 sec)

If you know the structure of the table City , you could create an identical table and then copy the .frm file over the existing corrupted one


Q:

Django: problems while loading custom filters in the base template file while using template inheritance

When doing the {% load custom_filters %} in the template, after {% extends "base.html" %} everything works fine, but when I move the load to the base.html template the filter gets a weird behaviour. This is my custom_filters.py:
from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

# To cut off strings at a specified character, at first occurance. Example:
#   time = 19:30:12.123456
#   {{ time|cut:'.' }}
#   returns: 19:30:12
@register.filter
@stringfilter
def cut(string, cutoff_point):
    return string.split(cutoff_point, 1)[0]

When I load it in the 'end-template' the behaviour is as expected. If time = 19:30:12.123456 then {{ time|cut:'.' }} returns 19:30:12. When I load it in base.html the returned value is 19:30:12123456, the same as the input but without the 'cutoff-point'.
Does anyone know why?

A:

You should place {% load ... %} in every template, where you want to use your custom tag or filter.
In your case it's also not a good idea to call a filter cut, because this filter already exists (and it's used to cut a dot from your string).


Q:

Using webbrowser to click on a button in a webpage

so what I need to do is to use this code:
WebBrowser browser = new WebBrowser();
browser.Navigate("www.somthing.com");
browser.Document.GetElementById("ID").InvokeMember("click");

and then i need to find the id of the button in the page and put in my code but my problem is some of the buttons don't have Id's! what should I do then? they only have type and class and some other things but no Id. i realized that some buttons might be java and maybe that's why i can't click on them by the usual way. so do you know what should I do?

A:

You said your button element has a className ,you can get this element with like this:
public Form1()
        {
            InitializeComponent();
            webBrowser1.Navigate("To your register account url");
        }
        int on = 0;
        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            foreach (HtmlElement btn in webBrowser1.Document.GetElementsByTagName("button"))
            {
                if (btn.GetAttribute("className") == "yourclassname")
                {
                    btn.InvokeMember("Click");
                    break;
                }
            }
        }


Q:

Do reviewers usually ask for data? (Computer Science/ Data Science / Data Mining)

I know it's a free process and it depends on reviewer if they want the data and for author if they want to submit it.
Questions:

What are the chances of a reviewer asking for data?
Why might reviewers ask for data?

A:

I have asked, or been asked, for data a vanishingly small but non-zero number of times. But I'm pretty secure in asserting that it's rare.
As for why - I would hope they would specify this when they requested it. Among the reasons would be to see if your results are genuinely obtainable from your methods. This is not necessarily just looking for fraud, etc. but checking to see if your writing is clear enough that by "following the recipe" they get the same answer.
Another possibility is they want to try an alternative analysis. For example, in my field, there is a variable selection method that is commonly used and also wrong. Generally, I ask authors to re-do their analysis with a more appropriate method as a reviewer, but it's entirely possible this won't change the answer. Having the data would let me check for myself.

A:

What are the chances of a reviewer asking for data?
It would be different from one field to another. For example, there is a small chance to be asked for more data (and very tiny chance of being asked for raw data in the fields such data analysis/science and machine learning, and optimization.
The odds will increase when the claims are very surprising (too good to be true!) or not clearly backed by theoretical proofs and discussions.
Why might reviewers ask for data?
To investigate the correctness of the presented conclusions and claimed achievements based on the obtained data. The reviewer/editor usually provide enough details on why such deep investigation is necessary and how it can affect their final decision.
How to decrease the chance?
To decrease the likelihood of such requests, that may make the review process even longer, one can:

provide as much supplementary data as possible right at the time of submission,
share codes (if applicable) via Git repositories to give the reviewers the confidence that the results are genuine and correct, and
provide sound and clear theoretical proofs (when applicable) that support the claims regardless of the quality of the data.

In general, it is really appreciated to make the researchers and their outcomes reproducible. That's why many researchers publically share their valuable datasets/outcomes.
Further Readings:

How to share a scientific dataset with the research community?
How to share to mention/publish large datasets?

A:

In my field (structural biology), we have repositories where we are required to deposit data and models prior to publication. The deposition date establishes precedence, and the data and models are only made public once the associated publication comes out. The repositories will grant the editor and reviewers of the article access to not yet released data and models if they request it during the review process. I don't know how often they actually ask, but I like the fact that the repositories make this possible in a formal and non-awkward way.


Q:

The 'getRow()' method is only allowed on scroll cursors SQLException error

I am trying to populate my JTable from my embedded database that I have set up in Netbeans.
My database contains 3 rows and 3 columns that I'd like to insert into a JTable, and make the table visible in my GUI application.
However, I am getting a java.sql.SQLException error as the title says above and my table will not turn visible in my GUI application.
Here's is my code:
public void FillTable(JTable table, String Query)
{
    try
    {
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
        Connection conn = DriverManager.getConnection("jdbc:derby:STOCK_CONTROL");
        Statement stat = conn.createStatement();
        ResultSet rs = stat.executeQuery(Query);

        //Remove previously added rows
        while (table.getRowCount() > 0)
        {
            ((DefaultTableModel) table.getModel()).removeRow(0);
        }

        int columns = rs.getMetaData().getColumnCount();

        while (rs.next())
        {
            Object[] row = new Object[columns];

            for (int i = 1; i <= columns; i++)
            {
                row[i - 1] = rs.getObject(i);
            }
            //The error is being generated here at 'rs.getRow()'
            ((DefaultTableModel) table.getModel()).insertRow(rs.getRow() - 1, row);
        }

        rs.close();
        stat.close();
        conn.close();
    }
    catch (InstantiationException |
            IllegalAccessException |
            ClassNotFoundException |
            SQLException e)
    {
        System.out.println(e);
        e.printStackTrace();
    }
}

I then create my table and call the method as above:
JTable tigerTable = new JTable();

FillTable(tigerTable, "SELECT * FROM TIGER_INFO");

I've tried to find information as to why this error is being caused, but to no avail.
My question is, how do I correctly populate my JTable from my embedded database, whilst also straying away from this unknown error I have come about?
What does this error exactly mean? I'm unsure what a 'scroll cursor' is.

A:

As documented in ResultSet.getRow():

Note: Support for the getRow method is optional for ResultSets with a result set type of TYPE_FORWARD_ONLY
  [..]
Throws:
  [..]
SQLFeatureNotSupportedException - if the JDBC driver does not support this method

You either need to ask for a scrollable cursor using
conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

Or - probably better - keep track of the row number yourself instead of using ResultSet.getRow(). For example:
int rowIdx = 0;
while (rs.next()) {
    Object[] row = new Object[columns];
    // ...

    ((DefaultTableModel) table.getModel()).insertRow(rowIdx++, row);
}

It is been a while since I have done anything with swing, but it might even be simpler to just remove existing rows from the table model and call addRow.


Q:

Comparison operator `<=>` and booleans

The <=> operator does not handle booleans well.
true <=> true # => 0
true <=> false # => nil

Is this behavior intended by design or am I missing something? I expect:
true <=> false # => 1
false <=> true # => -1

Edit
This is what I was looking for:
false.to_i <=> true.to_i # => -1

A:

The <=> operator isn't really a "combined boolean"; it is for ordering items of the same class, if they have an order defined. Numbers are ordered; 1 is greater than 0 and 0 is less than 8675309. Boolean values don't have an inherent order; true isn't greater than false or vice versa.

A:

They are not the same class. true is a singleton of TrueClass, while false is a singleton of FalseClass. You're comparing apples and oranges (or, in true <=> true case, an apple with the same apple).
For curiosity's sake, why do you think true <=> false should equal 1? EDIT: beaten to it by sawa


Q:

View comments in admin area before approval

How can I view posted comments in admin area before approval?
I mean previewing comment INSIDE admin area not node's page.

A:

Default comment administration page does not show you the entire comment. But it shows author and some other helpful information that should be helpful for most users to decide anther delete it or not.
You can replicate this form using Views and Views Bulk Operations module.
Just install both modules and create a new View on comment entity.
You can add a new page with a path like admin/content/comment2 (so you are not overriding the default page - if you want to do so, enter same path as core comment admin page).
Add necessary fields and set style as table. You can add a VBO checkbox and actions by adding a checkbox field.
There is an action "delete comment" that you can use to delete comments via VBO.
hooks will work without a problem.


Q:

Use macro to draw inside pgfplot/axis

I would like to implement a gantt chart function inside pgfplots. To draw the tasks, I have a macro that calculates the start and finish time of a task. However, when I use multiple tasks, the values inside are overridden and as a result it only shows a single task.
\documentclass[10pt]{article}
\usepackage{pgfplots}

\begin{document}

\newcommand{\task}[7]{
    \pgfmathparse{#1/365+#2/12+#3}
    \edef\taskstart{\pgfmathresult}
    \pgfmathparse{#4/365+#5/12+#6}
    \edef\taskfinish{\pgfmathresult}

    \pgfmathparse{#7-0.4}
    \edef\bottom{\pgfmathresult}
    \pgfmathparse{#7+0.4}
    \edef\top{\pgfmathresult}

    \draw[blue,fill=blue!50!white] (axis cs:\taskstart,\bottom) rectangle (axis cs:\taskfinish,\top);
}

\begin{tikzpicture}
    \begin{axis}[xmin=2011,xmax=2013,ymin=0,ymax=10]
        \task{26}{1}{2011}{23}{6}{2011}{1} % this is not drawn
        \task{26}{1}{2012}{23}{6}{2012}{3} % only this is drawn
    \end{axis}
\end{tikzpicture}

\end{document}

I know that this is a question of expansion, but I have to admit that I do not know how to handle it within the axis.

A:

The problem arises as you correctly have noticed due to the expansion of the variables. pgfplots collects all statements until \end{axis} and then executes them. Thus you need to make sure that the commands that are to contain data are containing the correct data! Your problem is that the data \taskstart, \bottom, \taskfinish and \top are defined to be the last value. That is from \task<2>.
Remember to consider all commands in TikZ or pgfplots terms to be already fully expanded for you to get the correct plot.
You can solve the problem by using this \newcommand:
\newcommand{\task}[7]{
    \pgfmathparse{#1/365+#2/12+#3}
    \edef\taskstart{\pgfmathresult}
    \pgfmathparse{#4/365+#5/12+#6}
    \edef\taskfinish{\pgfmathresult}

    \pgfmathparse{#7-0.4}
    \edef\bottom{\pgfmathresult}
    \pgfmathparse{#7+0.4}
    \edef\top{\pgfmathresult}
    \edef\tmp{%
        \noexpand\draw[blue,fill=blue!50!white] (axis cs:\taskstart,\bottom) rectangle
        (axis cs:\taskfinish,\top);}
    \tmp
}

The resulting image will be:


Q:

C - How to programmatically load a static library in Win32?

I need to be able to switch between a function in a static library and my overridden version in my main app. To do this, I'm trying to use function pointers. The problem is that I don't know how to load a static library into my program. Is this possible? Or do I have to use a DLL?

A:

I suppose this might be possible if you have an expert level knowledge of linkers, object file formats, calling conventions, and machine language for your target platform; but static libraries are not intended for this purpose.  Use a DLL.


Q:

Hide directory name in URL

I have been trying to hide a folder name from a URL and I'm failing miserably. My URL id 0.0.0.0/project/api/api/foo. As you can see there are two api's and I only want to show one. The .htaccess I have been working with resides on the root of the directory and looks like:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /api/api/$1 [L]
</IfModule>

I've tried a couple different variations of this but nothing is working. The first api is a directory name and the second api is something Laravel puts in for a route and is not a directory. It's ugly to have both, so how can I remove the first api?

A:

There is no need to mess with the .htaccess. You just need to update your routes file to not include the second api path.
You can either remove the leading api segment you've manually defined on your routes, or you can remove the automated api prefix that Laravel adds by default to all routes in the routes/api.php file.
To remove the default prefix, open your app/Providers/RouteServiceProvider.php file, go to the mapApiRoutes() method at the bottom, and remove the 'prefix' => 'api', line.