Q:

Are there drawbacks to taking a job where I will be using a unique programming language?

I just graduated from college with a degree in CS, so I would like to find a job where I can learn more about the field and build up some professional experience.
I've interviewed at a company that uses their own in-house programming language, and I don't think any others use it.  They have not mentioned using any other languages or what they use for a development environment.
What should I be concerned by taking a job like this?  If I were to switch jobs later, would I have to start looking for entry level positions again because I haven't gained any language-specific experience?

A:

Run away, and run away quickly.  Unless you're desperate for a job and are very hungry, this is a situation you want to steer clear of.
I have experience with a company that did this, and the only reason that they did so was so that their employees wouldn't gain meaningful, transferable experience.  It really was all about control.
Others who said here that "programming is programming" are right, but I'd turn that on its head and ask, why not use some standard language for which there is external support, libraries, forums, and a pool of available programmers to choose from?
The only time I think such a situation would be OK would be if the company-only language was for custom hardware.  For example, you have to write everything for the 9000X Gamma-Ray Interferometer using an assembly/machine code specific to that machine.

A:

The main downsides:

working in a "custom environment" can mean limited tools/support which can be infuriating when you get stuck on a problem.
The language they use may be poorly designed, leading to you picking up bad habits early on and write hacky code to create workarounds.
HR baffoons will not recognize your experience. (This is OK. A company that leans on HR to make technical hires is not the kind you typically want to work for. After a couple years, most of the great jobs come through connections anyway.)

If it were me, I would ask them why they use an in-house language. If it is for a legitimate reason, such as crazy hardware contraints, a domain that is not easily modeled in any existing languages then this is totally fine. On the other hand, if their answer suggests that they created their own language so that they could roll together a bunch of hacks and business logic into what amounts to a bunch of wacky macros, then this is a big red flag. You want to make sure that they use good engineering principles, so that you can learn from them and succeed with them. In this case you can see whether they can rationally justify using a home-grown language that does not have a community knowledge base and external support. You may find that their decision is perfectly rational (I believe facebook built their own version of PHP to deal with scalability, which has done pretty well for them), or you may find that they have created a monstrosity of a language that has been so tightly coupled with their core systems, that they cannot seem to break away from it. Trust me, you do not want to be working in a language who's core data type is called ImARInObj (Immutable Accounts Receivable Invoice Object). Tight coupling between a language and a business need often occur in these types of situations, and it would be an absolute nightmare to deal with that sort of system everyday.

A:

Since your resume is basically blank after you graduate, your first job puts a lot of momentum on your future career path.  Your next potential employer(s) will be putting a lot of weight on this job.  So, unless you will be programming in other (more marketable) languages as well, I would highly recommend against taking this job.
I say this from experience because I just left the first job I had after graduating with my C.S. degree, where I was in a position almost exactly as you describe.  Most of the programming was done in a basically unknown language called Progress (a.k.a. OpenEdge ABL).  It's horrible.  Not as bad as COBOL, but close.  I was stuck there because the area around where I graduated does not have many programming jobs, and I was waiting on my wife to graduate with her degree before moving.
Getting that language to talk with other languages or databases was nearly impossible (it came locked in with its own proprietary database as well - bonus!).  I spent a lot of time writing frameworks on my own that already existed in other languages, and were probably better implemented already as the language did not support this type of "extension" paradigm very well.  The language was more tailored towards a "contact Progress Corp. with a feature request, and wait until version n+1 for the new feature" approach.  Needless to say, the software industry doesn't move slow enough for this to be a viable approach.  I won't go on about how bad it was, but I assume you will face a similar thing if you are dealing with a proprietary language as well.  Rewriting existing frameworks in unknown languages has proven to not be a very marketable skill, in my own experience.
To add to that, the existing codebase was, shall we say, sub-optimal.  Lots of legacy code dating back to the late 80's / early 90's.  I would wager you should expect something similar, since I think most companies only stick with the proprietary languages because they carry a lot of this legacy baggage with them.  Remember, it's probably hard for such an employer to find programmers willing to code in this legacy/proprietary environment, plus they probably have to pay for training as well since no one's ever heard of it.  Your coworkers probably won't be titans of software engineering, either, due to the Dead Sea effect (anyone with talent probably already left).  I had a lot of trouble at code reviews trying to use object-oriented code, let alone any type of design patterns, as they just didn't understand it (the people on my team had, at best, an MIS degree (no offense)).
Finally, assuming you do take this job but yearn to do something better once you leave, in order to make yourself competitive for your next job you either have to sacrifice a lot of your free time outside work creating breakable toys in more marketable languages (and probably open source most of what you make), or do what I did and save up some money before you quit and spend a month or two doing same.  Either way, this is a very stressful thing, especially if you enjoy having any type of social relationships outside of work or spending your free time doing something that isn't coding once in awhile.
Now, my experiences may not map directly to your choice, but I'm sure some of it will apply.  Hopefully it will at least give you some questions to bring up.  As others have mentioned, you probably want to find out what tools they use (hardware, software development environment/IDE, and definitely version control).  The Joel Test might be a useful guide.
TL;DR
Don't do it.
P.S. To those saying that learning any new language is useful, that on its own is true.  The problem is when you get stuck using that language almost exclusively full-time for a long period of time, losing exposure to more useful languages (and techniques).  That is what you want to avoid.


Q:

File not downloading even though it says it did

I have a problem where a file won't download, even though it shows as completed.
The file is not showing in the location where it's supposed to be be downloaded to.
This is my code:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if(e.ColumnIndex == 2)
    {
        int rowIndex = e.RowIndex;
        DataGridViewRow row = dataGridView1.Rows[rowIndex];
        string value1 = row.Cells[2].Value.ToString();
        wc.DownloadFileCompleted += new AsyncCompletedEventHandler(AtlasCompleted);
        Uri fileUrl = new Uri(value1);
        Beta = fileUrl;
        //Console.WriteLine(FormPopup.Variables.Location1.Length);
        if (FormPopup.Variables.Location1 != null && FormPopup.Variables.Location1.Length >= 5)
        {
            Console.WriteLine(FormPopup.Variables.Location1);
            Console.WriteLine(fileUrl);
            wc.DownloadFileAsync(fileUrl, FormPopup.Variables.Location1);
            //MessageBox.Show(fileUrl.ToString() + "               " + FormPopup.Variables.Location1);
        }
        else
        {
            MessageBox.Show("Error: No file location specified.");
            FormPopup form = new FormPopup();
            form.Show(this);
        }

    }
}

private void AtlasCompleted(object sender, AsyncCompletedEventArgs e)
{
    MessageBox.Show(Beta.ToString() + "               " + FormPopup.Variables.Location1);
}

The file should download, but it's not downloading or appearing in the location specified.
If anyone can help that would be great, its really confusing me.
Thanks for the replies :D

A:

The WebClient code is fine and it should download the file without any issues. Just ensure that your file Uri is correct (paste the uri into browser and see its correct). Path to save file on local system should be valid (folders included in path must exists) and regular user must have permissions to write.
To test it further, first use the hard-coded values:
wc.DownloadFileAsync("File Uril","File path at local system");

Example:
wc.DownloadFileAsync(new Uri("http://example.com/myfile.txt"), @"d:\myfile.txt");

Double check your variables for Uri and location because there is no magic that would prevent downloading besides invalid parameters.
Additionally, add some error logging/Exception handling so it tells you what happened.
private void AtlasCompleted(object sender, AsyncCompletedEventArgs e)
{
if(e.Error !=null)
    Console.WriteLine(e.Error.Message);
     else
   Console.WriteLine("Completed");

    MessageBox.Show(Beta.ToString() + "               " + FormPopup.Variables.Location1);
}


Q:

How do I take screenshots and video in Halo?

I see all these beautiful halo videos on the internet, how do I take in-game videos and pictures?

A:

For Halo 3, simply use the in game Theater mode, and upload it to your file share. Then download it from your file share on bungie.net, found by typing your gamertag into the search box.

A:

Video:
This lists all sorts of various methods for recording 360 game footage. It would take a while to list them all; go through and figure out which one suits your situation best based on the equipment you have and the definition of your TV.
As for PC, you might want to look into buying FRAPS.
Screenshot:
On the PC, you can take a screenshot by pressing the print screen button on your keyboard.
On the Xbox, you might want to use a digital camera or look into using video capture hardware as detailed here.


Q:

Create a grid in OpenGL

I need to generate a NxN resolution grid in the xy-plane with OpenGL. The final grid needs to be made by triangles (GL_TRIANGLES), so it should seem like the following example:
 ^
 *   |  ----------
 *   |  |\ |\ |\ |
 *   |  | \| \| \|
 *   |  ----------
 *   |  |\ |\ |\ |
 * y |  | \| \| \|
 *   |  ----------
 *   |  |\ |\ |\ |
 *   |  | \| \| \|
 *   |  ----------
 *   |
 *   |-------------->
 *          x

Note that I need to store the grid in vertex-index form (given the structures by parameters).
My code at this point:
void generate_grid(
std::uint32_t N,
std::vector<glm::vec3>* vertices,
std::vector<glm::uvec3>* indices)
{
    for (int i = 0; i < N; i++) {
        glBegin(GL_TRIANGLES);
    for (int j = 0; j < N; j++) {
        int vertexNum = indices;  // Index for vertex j of face i.
        double[] vertexCoords = vertices[vertexNum];  // The vertex itself.
        glVertex3f(vertexCoords, 0);
    }
    glEnd();
}

Any advice? Regards.

A:

Since the language is C++ and you are using a std::vector you should change the function signature and pass the parameters by reference instead of by pointer.
void generate_grid(int N, std::vector<glm::vec3> &vertices, std::vector<glm::uvec3> &indices);

First you have to fill the vertex array. Note, for a N*N field you need (N+1)*(N+1) vertices. Second you have to generate the triangle indices, for each field you have to generate 2 triangles:
 float f(float x, float y)
{
    // use any curve function you want
    return sin(x*2.0f*3.141526f) * sin(y*2.0f*3.141526f) * 0.1f;
}

void generate_grid(int N, std::vector<glm::vec3> &vertices, std::vector<glm::uvec3> &indices)
{
    for (int j=0; j<=N; ++j)
    {
        for (int i=0; i<=N; ++i)
        {
            float x = (float)i/(float)N;
            float y = (float)j/(float)N;
            float z = f(x, y);
            vertices.push_back(glm::vec3(x, y, z));
        }
    }

    for (int j=0; j<N; ++j)
    {
        for (int i=0; i<N; ++i)
        {
            int row1 = j * (N+1);
            int row2 = (j+1) * (N+1);

            // triangle 1
            indices.push_back(glm::uvec3(row1+i, row1+i+1, row2+i+1));

            // triangle 2
            indices.push_back(glm::uvec3(row1+i, row2+i+1, row2+i));
        }
    }
}

The old school and deprecated way to draw this, would be like this:
void draw_grid(const std::vector<glm::vec3> &vertices, const std::vector<glm::uvec3> &indices)
{
    glBegin(GL_TRIANGLES);
    for ( auto i : indices )
    {
        glVertex3fv(glm::value_ptr(vertices[i.x]));
        glVertex3fv(glm::value_ptr(vertices[i.y]));
        glVertex3fv(glm::value_ptr(vertices[i.z]));
    }
    glEnd();
}

The common way to draw geometry is to create a Vertex Array Object:
GLuint generate_vao(const std::vector<glm::vec3> &vertices, const std::vector<glm::uvec3> &indices)
{
    GLuint  vao;
    glGenVertexArrays( 1, &vao );
    glBindVertexArray( vao );

    GLuint vbo;
    glGenBuffers( 1, &vbo );
    glBindBuffer( GL_ARRAY_BUFFER, vbo );
    glBufferData( GL_ARRAY_BUFFER, vertices.size()*sizeof(glm::vec3), glm::value_ptr(vertices[0]), GL_STATIC_DRAW );
    glEnableVertexAttribArray( 0 );
    glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, nullptr );

    GLuint ibo;
    glGenBuffers( 1, &ibo );
    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, ibo );
    glBufferData( GL_ELEMENT_ARRAY_BUFFER, indices.size()*sizeof(glm::uvec3), glm::value_ptr(indices[0]), GL_STATIC_DRAW );

    glBindVertexArray( 0 );
    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );

    return vao;
}

void draw_vao( GLuint vao, GLsizei n )
{
    glBindVertexArray( vao );
    glDrawElements( GL_TRIANGLES, (GLsizei)n, GL_UNSIGNED_INT, NULL );
    glBindVertexArray( 0 );
}

std::vector<glm::vec3> vertices;
std::vector<glm::uvec3> indices;

GLuint vao = generate_vao( vertices, indices );
.....
draw_vao( vao, (GLsizei)indices.size()*3 );


Q:

git push .git/description file

Is it possible to push the changes in the .git directory to a remote repository?
I wish to have a common project description and not have to re-enter it for all the clones of my repository.
It's strange that the project description is something that is not common to each clone.

A:

You could store a description (or .description, if you don't want it to be visible) in the root of your repo, and then symlink .git/description to that in each repo, like so:
repo/
  .description
  .git/
    description -> ../.description

You'd have to set up the symlink manually in each of your repos, but you'd only have to do that once (when the repo is created).
Or you could use a post-receive hook to copy your tracked description file into .git/description. You'd have to set up that hook on each remote repo, too, but again, that would only need to happen once (when the repo is created).


Q:

htaccess second rewrite rule not working

I made a website and placed this code in the .htaccess file
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule  (.*)$ profile.php?id=$1 [QSA,L]
RewriteRule  (.*)$ category.php?id=$1 [QSA,L]

Now, the first Rewrite rule works as expected, allowing me to have urls like site.com/profile instead of site.com/profile.php?id=foo.. but, when I added the second one, to achive the same result as the above solution, the page breaks down, and the css does not get included. So, it seems that the two can not be writen together, and I don't know what the solution is.

A:

Try changing to:
RewriteRule  ^profile/(.*)$ profile.php?id=$1 [QSA,L]
RewriteRule  ^category/(.*)$ category.php?id=$1 [QSA,L]


Q:

Displaying search results from mysql

I will paste my php code below. I have 4 jobs with web developer as the title. I essentially want it to print them in an organized table.
<?php
include_once 'header.php';

$output="";
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);

$query = mysql_query("SELECT * FROM job,address WHERE title LIKE '%$searchq%' or cname     LIKE '%$searchq%'") or die("could not search");
$count = mysql_num_rows($query);

$pageTitle="Search Results";

if($count == 0){
    $output = 'There are no results';
}else{
    while ($row = mysql_fetch_array($query)){
            $cname=$row["cname"];
            $title=$row["title"];

            $output .= '
'.
                        '
 Search Results
'.
                        '
'.$count.' results found searching for '."$searchq".'
'.

                        '
'.
                            '
'.
                            ' Company Name 	'.
                            ' Position Title 	'.
                            '
'.
                            ''. $cname.' 	'.
                            ''. $title .'	'.
                            ' <button onclick="myFunction()"> Location </button> 	'.
                            '
'.
                        '
'.

                        '
';

    }
}
}
?>

I don't want to copy and paste the whole thing. But at the bottom where I print the ''$output'' is just:
<?php
print ("$output$");
?>

EDIT: I am pretty new at PHP so this may not be the best way to do this.  (This is not a professional site. This is just a school project.)
Screenshot:
The Map was covering up the rest of the information for some reason. So I deleted the map and this was the result.

A:

You have a missing
 tag
  '
'.
   '
'.
    ' Company Name 	'.
    ' Position Title 	'.
    '
'.
    ''. $cname.' 	'.    //<---- here
    ''. $title .'	'.
    ' <button onclick="myFunction()"> Location </button> 	'.
    '
'.
'
'.

Also did you really mean to print an entire table for each result?
probably just
    '
'.
    ''. $cname.' 	'.
    ''. $title .'	'.
    ' <button onclick="myFunction()"> Location </button> 	'.
    '
';

should be in the while loop


Q:

Trying to install matplotlib on a macbook pro

I need to use matplotlib for a school project and cannot get it installed on my mac. I downloaded a version of it but when I try to import it does not work. I have mac os x 10.5.8 and was wondering if anyone could recommend where I could find the proper package.

A:

I could never get it to work the proper way so I did it through GitHub.
Open terminal and do:
git clone https://github.com/matplotlib/matplotlib.git

Then change to the folder it will make automatically (which is in your home folder) and do:
python setup.py build

then
python setup.py install

It's probable you'll have to sudo for some of those.


Q:

Unable to resolve component /atg/dynamo/servlet/adminpipeline/Authenticator

I'm trying to launch ATG on JBOSS. However, I'm getting this following exception in my log
Unable to set configured property "/atg/dynamo/servlet/adminpipeline/AuthenticationServlet.authenticator" atg.nucleus.ConfigurationException: Unable to resolve component /atg/dynamo/servlet/adminpipeline/Authenticator
I was under that impression that Authenticator is a default component. can any body guess as to why this may occur?

A:

Could you please provide your Authenticator's properties file. Do you have it overridden in your module? It should be because only then error should be occurring in your logs. If yes then please remove it and verify that the override is causing the problem.
Also please paste the full error log so we can get an idea.


Q:

The opacity works with the hover but not the background color. Why?

I want to create a black transparent overlay on 4 images, keeping the size and if possible add some text with the hover. I've looked preview answers but it doesn't work for me. Begginer. Could you help me ?
HTML

CSS
img {
  width: 47%;
  height: auto;
}

#John:hover {
  background: black;
  ;
  opacity: 0.7;
  /* i also tried */
  background: rgba(0, 0, 0, 0.7))
  /* the only thing that works on it is the opacity */
}

section.image {
  text-align: center;
}

Thank you

A:

The background you are trying to apply will not appear on the  tags because your image is blocking it out.
Think of your  tag as a layered element, the top is your actual picture, and below it is the container where the background is set.  Since your image fills up the entire container, your background will never appear.
What you want to do instead is create an element that appears on-top of your image, and appears upon hover.
In order to do this, you need to first wrap your  tags with an element, like this:

I used an  tag because I'm assuming you want something clickable.
Next we can apply some basic styling that inserts an element after the  tag, and makes it appears upon hover.  The result is something like this:

.img-link {
  display: inline-block;
  line-height: 0;
  position: relative;
}

.img-link:after {
  background: rgba(0,0,0,0.3);
  display: inline-block;
  content: '';
  height: 100%;
  opacity: 0;
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  transition: opacity 0.2s linear;
}

.img-link:hover:after {
  opacity: 1; /* show overlay */
}


Q:

differentiability and continuity in R3

Prove that if a function is differentiable at $(a,b,c)$ in $\mathbb R^3$ then it is continuous at $(a,b,c)$.
I tried to imitate the proof that if $f$ is differentiable at a specific point in $\mathbb R$ then it is continuous on that point of $\mathbb R$, but I did not know the differentiation formula in $\mathbb R^3$.

A:

Let $x=(a,b,c)$. By definition of derivative we have:
$$\lim_{h \to 0}\frac{\|f(x+h)-f(x)-f'(x)h\|}{\|h\|}=0$$
Let $\varepsilon>0$. Then we'll choose small $\delta>0$ that  for $\|h\|<\delta$ we have $\|f(x+h)-f(x)\|<\varepsilon$. There exists $\delta_1>0$ that for $\|h\|<\delta_1$:
$$\frac{\|f(x+h)-f(x)-f'(x)h\|}{\|h\|}<1$$
(it's by definition of limit) Now let $\delta=\min(\delta_1,\frac{\varepsilon}{1+\|f'(x)\|})$ and $\|h\|<\delta$ we have:
$$\|f(x+h)-f(x)-f'(x)h\|<\|h\|$$
By triangle inequality:
$$\|f(x+h)-f(x)\|-\|f'(x)\|<\|f(x+h)-f(x)-f'(x)h\|$$
So:
$$\|f(x+h)-f(x)\|<\|h\|+\|f'(x)h\|\leq \|h\|+\|f'(x)\|\|h\|<\frac{\varepsilon}{1+\|f'(x)\|}(1+\|f'(x)\|)=\varepsilon$$


Q:

vector and DataFrame length

I had a dataframe which consisted of 12 columns. Then I cut one vector from it and made it separate. I then performed train_test_split from sklearn library like below:
X=pd.DataFrame()

X['annua_inc']=annual_inc
X['delinq_2yrs']=delinq_2yrs
X['dti']=dti
X['emp_length']=emp_length
X['loan_amnt']=loan_amnt
X['installment']=installment
X['int_rate']=int_rate
X['total_acc']=total_acc
X['open_acc']=open_acc
X['pub_rec']=pub_rec
X['acc_now_delinq']=acc_now_delinq
X['loan_stat']=loan_stat

X=X.fillna(0)
y=X['loan_stat']
X=X.drop(['loan_stat'], axis=1)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=42)

When I check the length of for example X_test and y_test (which both should be the same) it returns me the same value. But when I try to call X_test[len(X_test)] it tells me that index is out of bounds for axis 0. But for y_test[len(y_test)] it gives me a correct value. Does anyone know why? because the last row in X_test and last row in y_test were previously combined in the same row in X so why now the last row for X_test doesn't exist and for y_test it does?

A:

arrays in python, pandas, numpy, scipy, and others are zero based in their indexing.  So the length of [0, 1, 2, 3] is 4.  But [0, 1, 2, 3][4] will be out of bounds.  Refer to the last element as either [0, 1, 2, 3][4 - 1] or [0, 1, 2, 3][-1]
In your case
X_test[len(X_test) - 1]

Or
X_test[-1]


Q:

Express $(z-e^{i\theta})(z-e^{-i\theta})$ as a quadratic function with real coefficients

Express $(z-e^{i\theta})(z-e^{-i\theta})$ as a quadratic function with real coefficients.
My attempt:
$(z-e^{i\theta})(z-e^{-i\theta}) \\ $
$=(z-(cos\theta+isin\theta))(z-(cos\theta-isin\theta)) \\ $
$=z^2-z(cos\theta-isin\theta)-z(cos(\theta)+isin\theta)+(cos\theta+isin\theta)(cos\theta-isin\theta) \\ $
$ \\ $
$Let \: a=cos\theta \: and \: b=sin\theta \\ $
$ \\ $
$\Rightarrow z^2-z(a-bi)-z(a+bi)+(a+bi)(a-bi) \\ $
$= z^2-z(a-bi)-z(a+bi)+a^2+b^2 \\ $
$= z^2-z((a-bi)+(a+bi))+1 \\ $
$= z^2-2az+1 \\ $
$\Rightarrow z^2-2zcos\theta+1$
I feel like I have some problems with arithmetic but I'm not really sure. Is this correct?

A:

You answer is right, but you took kind of a long way around to the answer.
I would suggest that you hold off applying Euler's formula until later. Instead, first just do the algebra:
$$(z-e^{i\theta})(z-e^{-i\theta}) = z^2 -(e^{i\theta} + e^{-i\theta})z + \underbrace{e^{i\theta}e^{-i\theta}}_{e^0=1} = z^2 - (e^{i\theta}+e^{-i\theta})z + 1
$$
Now bring in Euler's formula:
$$e^{i\theta} + e^{-i\theta} = (cos(\theta) + i \sin(\theta)) + (\cos(\theta) - i \sin(\theta)) = 2 \cos(\theta)
$$
Finally, substitute and you're done:
$$z^2 - 2 \cos(\theta)z + 1
$$


Q:

Materialize CSS - passing data to sideNav

I'm using materializeCss for my latest project and I have a problem.
I use sideNav to open a 'modal' inside of which is a contact form.
This contact form should be used in multiple occasions and different informations should be prefilled depending on which button does user click.
Let me explain it in an example:
If user clicks on Send Message then the forms input title should be something like
<input type='text' id='title' name='title' readonly value="General message">

and if user clicks on button Request Candy then this input should be something like
<input type='text' id='title' name='title' readonly value="I want candies!">

Since the sideNav opens by clicking on an element of type
menu

I had an idea to react on the click as
$(document).on('click', '.button-collapse', function() {
    console.log('got it!');
    $('#title').val('My custom message from data-* or something..');
})

but this doesn't work since probably materialize hijacks click events on these a.button-collapse's. I don't even get the console log got it!.
Does anybody know a way to pass some data to the newly open sideNav?
UPDATE:
jsfiddle

A:

<input> is a "head only" tag - has no closing </input> and yet element has no content.
So you markup shall look like
<input type='text' id='title' name='title' value='General message' readonly></input>

UPDATE:
Change to this:
$('.button-collapse').on('click', function() {
    $('#title').val($(this).data('title'));
    console.log('I have been clicked');
  })

and it will work. Seems like document or framework is consuming the event so you cannot handle it on that level.


Q:

Energy density of magnetostatic fields

Consider that we are given magnetostatic field $B=B_1$ and $\frac{dB}{dt}=0$ from the beginning of time to the end of time. We are interested in the potential energy contained in the field.
We know that $$dU=H{\cdot}dB$$ where $U$ is energy density and $B={\mu}H$.
There is a person who approached the problem as follow:
Because of that the magnetic field is constant then he set $dB=0$ and he puts it in the integral $$\begin{aligned}U&={\int}HdB\\&=\frac{1}{\mu}{\int}BdB\\&=\frac{1}{\mu}\int B\cdot0\\&=0\end{aligned}$$
So the person concluded that magnetostatic field does not have energy (does not contain potential energy at all).
The person did not allow me to perform the following integral $$\begin{aligned}U&={\int_0^{B_1}}HdB\\&=\frac{1}{\mu}{\int_0^{B_1}}BdB\\&=\frac{1}{2\mu}B_1^2\end{aligned}$$
Because, he said that the magnetic field is constant and has never changed from $0$ to $B_1$. For the integral from $0$ to $B_1$ to be valid $B$ must change from $0$ to $B_1$ he argued.
I need some comments.

A:

The equation
$$ dU = H \cdot dB $$
is valid only in context of virtual work and should be considered a differential equation determining the function $U(B)$. It tells you how would $U$ change if one changed $B$ by $dB$. So you are right and he is wrong.


Q:

Installing MacVim after having already configured Vim

This question could sound trivial, but i want to be sure of what i'm doing before trying something new.
I have an already configured Vim installation, which i have installed via brew install vim, and a vimrc file for my configurations. In order to properly install MacVim there is something i have to do for maintaining my plugins and vimrc? Or i just type brew install macvim?

A:

It all depends on where you did your configuration. If you did everything in ~/.vim/ you don't have to fear anything.


Q:

com.android.builder.testing.api.DeviceException: com.android.ddmlib.InstallException: INSTALL_FAILED_DEXOPT

i am getting the error while running my app in android emulator
com.android.builder.testing.api.DeviceException: com.android.ddmlib.InstallException: INSTALL_FAILED_DEXOPT

A:

You probably need to allocate more internal memory to your emulator. This can be done by:

Opening Android Virtual Device Manager...
Edit the device you're having a problem with.

3. Show Advanced Settings (see yellow arrows below)

Increase the internal storage to 5120MB

Restart the emulator (cold boot)

A:

By cleaning cache and making more space in android emulator helped me to resolve it.


Q:

What is the meaning of "-er-" in sentence?

I am reading a book in which I see this fragment:

. . . but he has —er— ideas what ideas . . .

What is the meaning of —er— in this sentence?
And what is the — that appears before and after some of those words?

A:

The -er- has the hyphen (-) around it to show the break in the speaker's words.  They stop saying anything that has meaning for a moment, but they are thinking about what they will say to continue the thought.
It means they are stuck for the moment, but are going to continue the sentence as soon as they decide what to say next.


Q:

How does Android decide which layout folder to use?

In my application I have 3 different layout folders:
layout
layout-large
layout-xlarge

I did this according to the available Android device screens, described here. So I thought that the screen size in inches is the only thing that is used to decide which layout folder to use. But recent tests with various 7 inch emulator showed that sometimes the layout and sometimes the layout-large folder is used. So can anybody tell me which other factors are used?

A:

7 inch Android tablets are HDPI and large.
xlarge didn't exist at the time they were made, and although most of them have pixel densities around 160 (MDPI) they present themselves as HDPI  devices because it looks better.
So the 7inch tablets don't quite fit into the resources system properly, because there wasn't really a way to fit them in prior to 3.0 which introduced new screen-size qualifiers.


Q:

More four-dimensional counterexamples

To follow up on A four-dimensional counterexample?, I am probably being dense, but are there examples of spaces which are homotopy equivalent to bundles of surfaces over surfaces (or three-manifolds over the circle, or circle over three-manifold) and yet are not such. Same question if you change "bundle" to "product". In Hillman's book
he seems very careful to sidestep this question and talk about homotopy equivalence only...
I am interested primarily in spaces where the fiber and the base are $K(\pi, 1)$ spaces (so not spheres) and are oriented (if that makes any difference).

A:

Borel's conjecture predicts that anu homotopy equivalence of closed aspherical manifolds is homotopic to a homeomorphism. The conjecture has been proved for many fundamental groups, see e.g.
this paper by Bartels-Lueck.
Basic ingredients are topological surgery, and computations of $L$-groups and $K$-groups.
Surgery works  perfectly in dimensions $\ge 5$, but in dimension $4$ one is limited to fundamental groups of subexponential growth, see
this paper by Kruskal-Quinn.
I am not up to date with L-theory computations but for polycyclic groups the reference is
[Farrell-Jones, The surgery L-groups of poly-(finite or cyclic) groups, Invent. Math. 91 (1988), no. 3, 559–586].
Combining the two ingredients gives Borel's conjecture for closed 4-manifolds homotopy equivalent to an infranil 4-manifold. This includes direct products of two closed surfaces with zero Euler characteristic.
Looking at recent papers by Bartels, Farrell, and Lueck at arxiv will bring you to state of the art on the L-theory computations, in particular, see
this survey by Lueck,
but I am not aware of the result that covers surface bundles specifically, and in any case one is limited to groups of subexponential growth.


Q:

How to get the currently running custom Threads variables

Here is my custom thread class
  public class ThreadEngine extends Thread{
  private int processid;
   public int getProcessid() {
      return processid;
    }
   public void setProcessid(int processid) {
    this.processid = processid;
    }
   public void run(){
    int count=0;
    for(Thread t:Thread.getAllStackTraces().keySet()){
        ThreadEngine t1=(ThreadEngine)t;
         int processtid=t1.getProcessid();
        if(t.getState()==Thread.State.RUNNABLE)count++;
     }
    }

 }

Here i am trying to typecast the currently running threads into my custom thread class but i am getting cast exception.
I want to get processid's of currently running threads.How is it possible?

A:

Couple of easy ways to handle this.
Full working code on online java ide
What are you trying to achieve?
The run() method always runs in the thread were the instance is ThreadEngine.
So you could simply use getProcessid() in the run() method to access the process id.
At any other place, if you want to access the current thread, you could simply use
Thread.currentThread() that returns the current thread.
If you are looking for any thread instead of just current thread, then you should make sure if it is of the current instance type using the instanceof keyword.
I have attached the working code in codiva java online compiler ide.


Q:

titleForHeaderInSection is overlapping the UISearch field

I'm having a problem where the titleForHeaderInSection is overlapping the UISearch field when a user scrolls the table.
I'm using the following code to offset a prior problem I had where the sectionIndexTitlesForTableView was overlapping the Cancel button. Now I have the section titles overlapping the UISearch field. Here's the code I have:

-(void) scrollViewDidScroll:(UIScrollView *)scrollView {
      searchBar.frame = CGRectMake(0,MAX(0,scrollView.contentOffset.y),320,44);

}
thanks for any suggestions.

A:

try clipping the sub views. Refer this similar post for more information


Q:

scroll to specific element on page using jquery

Hello am having a great problem scrolling the page to a specific element on page using jquery or javascript.
I've tried many ways of doing it but i failed in all of them. the website is implemented using the framework library called curtain.js https://github.com/victa/curtain.js.
The ways I have tried include:
1)https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView?redirectlocale=en-US&redirectslug=DOM%2Felement.scrollIntoView
2)How to go to a specific element on page?
3) I even tried the simplest way using  anchor tags but nothing happens.
the only way that worked was scrollTop() as you can see from other links on the page. Unfortunately this doesn't work for me since this fails on different screen sizes.
you can see example of the site at http://pagota.herobo.com
Thanks !

A:

UPDATE
Try this one, if you want a menu and menu links to specific page. It will scroll to your page with curtain effect.
DEMO http://jsfiddle.net/yeyene/mCytP/2/
Add menu outside of ol, then add links with your li page id in href.

Home

About Us

Portfolio

Programs


Q:

Как правильно: "согласно расписания" или "согласно расписанию"?

A:

Предлоги согласно, вопреки, благодаря употребляются с дательным падежом. Согласно (кому? чему?) расписанию. Употребление с родительным падежом - очень распространенная ошибка.

A:

Ошибка-то - она ошибка, но у неё есть вполне основательная причина. Ещё в XIX веке употребление родительного падежа было нормативным. Почему-то у нас это сейчас очень редко вспоминают, полагая такую форму вопиющей безграмотностью.


Q:

Is there a data structure with these characteristics?

I'm looking for a data structure that would allow me to store an M-by-N 2D matrix of values contiguously in memory, such that the distance in memory between any two points approximates the Euclidean distance between those points in the matrix. That is, in a typical row-major representation as a one-dimensional array of M * N elements, the memory distance differs between adjacent cells in the same row (1) and adjacent cells in neighbouring rows (N).
I'd like a data structure that reduces or removes this difference. Really, the name of such a structure is sufficient—I can implement it myself. If answers happen to refer to libraries for this sort of thing, that's also acceptable, but they should be usable with C++.
I have an application that needs to perform fast image convolutions without hardware acceleration, and though I'm aware of the usual optimisation techniques for this sort of thing, I feel a specialised data structure or data ordering could improve performance.

A:

I would guess "no"!  And if the answer happens to be "yes", then it's almost certainly so irregular that it'll be way slower for a convolution-type operation.
EDIT
To qualify my guess, take an example.  Let's say we store a[0][0] first.  We want a[k][0] and a[0][k] to be similar distances, and proportional to k, so we might choose to interleave the storage of first row and first column (i.e. a[0][0], a[1][0], a[0][1], a[2][0], a[0][2], etc.)  But how do we now do the same for e.g. a[1][0]?  All the locations near it in memory are now taken up by stuff that's near a[0][0].
Whilst there are other possibilities than my example, I'd wager that you always end up with this kind of problem.
EDIT
If your data is sparse, then there may be scope to do something clever (re Cubbi's suggestion of R-trees).  However, it'll still require irregular access and pointer chasing, so will be significantly slower than straightforward convolution for any given number of points.

A:

Given the requirement that you want to store the values contiguously in memory, I'd strongly suggest you research space-filling curves, especially Hilbert curves.
To give a bit of context, such curves are sometimes used in database indexes to improve the locality of multidimensional range queries (e.g., "find all items with x/y coordinates in this rectangle"), thereby aiming to reduce the number of distinct pages accessed. A bit similar to the R-trees that have been suggested here already.
Either way, it looks that you're bound to an M*N array of values in memory, so the whole question is about how to arrange the values in that array, I figure. (Unless I misunderstood the question.)
So in fact, such orderings would probably still only change the characteristics of distance distribution.. average distance for any two randomly chosen points from the matrix should not change, so I have to agree with Oli there. Potential benefit depends largely on your specific use case, I suppose.

A:

You might look at space-filling curves, in particular the Z-order curve, which (mostly) preserves spatial locality. It might be computationally expensive to look up indices, however.
If you are using this to try and improve cache performance, you might try a technique called "bricking", which is a little  bit like one or two levels of the space filling curve. Essentially, you subdivide your matrix into nxn tiles, (where nxn fits neatly in your L1 cache). You can also store another level of tiles to fit into a higher level cache. The advantage this has over a space-filling curve is that indices can be fairly quick to compute. One reference is included in the paper here: http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.30.8959


Q:

Delphi 2010 How to do something on form startup without requiring the user to take some action ( Button click, etc..)

How to do something on form startup like :
  RichEdit1.Lines.Add('sorry email@exemple.com is already in our database');

NOT untill the user take some action ( Button click, etc..)
I tried with the code below and it works but i am obliged to click on the button one in order to add that line into the richEdit1 compenent.

A:

If the TRichEdit control has been added at design time to a form, then you can set the properties of the RichEdit control in the form's OnCreate event.
This allows you to set the properties of controls before the user even sees the controls or has a chance to interact with them.
OnCreate is called after the form is created (including child controls) and before it's shown.
To open the OnCreate event for editing in the IDE, you can simply double-click on an empty part of the form.

A:

You can use the OnActivate event of the form to set properties for visual controls. I usually do it as follows:
procedure TForm1.FormActivate(Sender: TObject);
begin
  //Allow this code to run only once
  OnActivate := nil;

  //Set RichEdit Properties
  RichEdit1.Lines.Add('sorry email@exemple.com is already in our database');
end;


Q:

A View Over a XML Data Type Column

I have a table that contains a column of XML Datatype (column name FileContent).  I want to create a view that queries the contents of the XML datatype column so that I no longer have FileContent column but two additional columns called FuelPathwayCode and PhysicalPathwayCode from the underlying XML document.  Is this possible with SQL Server 2008? And, if so, how?  Thanks.
CREATE VIEW vw_LC_UploadXML
AS Select
  UploadFileID,
  Year,
  Quarter,
  CompanyID,
  FileType,
  FileContent,
  FileName,
  Description,
  Success,
  AddBy,
  AddDttm
FROM LC_UploadXML

A:

http://msdn.microsoft.com/en-us/library/bb500166.aspx
Use FileContent.value('(/FuelPathwayCode/@year)[1]', 'int(4)') to retrieve the particular field you are looking for.
This is supported in SQL Server 2008.


Q:

Facebook SDK-PHP : getting the uid of the connected user

I'm trying to get the UID of the connected user with Facebook SDK for PHP, but it doesn't work,  and all other things work properly; it means that the problem is not in the connection to the application.
I tried this code but it is always returning 0 while I'm connected to Facebook; I even tried with other accounts but no solution.
$uid = $facebook->getUser();

A:

$facebook = facebook_get();
    $uid = $facebook->getUser();
    echo $uid;

and here's facebook_get()
function facebook_get()
{
    include('lib/fbapi/facebook.php');
    $config = array();
    $config['appId'] = '...';
    $config['secret'] = '...';
    $facebook = new Facebook($config);
    return $facebook;
}


Q:

Filter a list of tuples based on condition

I have a list like this:
A=[(1,'A'),(2,'H'),(3,'K'),(4,'J')]

Each member of this list is like this: (number, string)
Now if I want to select the members if the number is bigger than 2 and write the string, what should I do?
For example:
selecting the member with a number bigger than 2. the output should be: 'K','J'

A:

Use a list comprehension:
[y for x,y in A if x>2]

Demo:
>>> A=[(1,'A'),(2,'H'),(3,'K'),(4,'J')]
>>> [y for x,y in A if x>2]
['K', 'J']
>>>

A:

try :
In [4]: [x[1] for x in A if x[0] > 2]
Out[4]: ['K', 'J']


Q:

Function doesnt work when variables are first

I got into weird problem, here is my code
$(document).ready(function(){
    $(".switch-content div:first-child").fadeIn();
    $(".switch-content div:first-child").toggleClass("switch-active");
    $(".switch-menu ul li").click(function(){
        var clicked = $(this).index()+1;
        $(this).parent().find("li.switch-active").toggleClass("switch-active");
        $(this).toggleClass("switch-active");
        $(this).parent().parent().parent().find(".switch-content div.switch-active").fadeOut();
        $(this).parent().parent().parent().find(".switch-content div.switch-active").toggleClass("switch-active");
        $(this).parent().parent().parent().find(".switch-content div:nth-child("+clicked+")").delay(200).toggleClass("switch-active");
        $(this).parent().parent().parent().find(".switch-content div:nth-child("+clicked+")").delay(200).fadeIn();
    });

})
var anchor = window.location.hash.substring(1);
var linked = $("#"+anchor).index()+1;

^ this works
When my code is like this, everything works fine, but when I move variables on first spot, my javascript stops working.
var anchor = window.location.hash.substring(1);
var linked = $("#"+anchor).index()+1;
$(document).ready(function(){
    $(".switch-content div:first-child").fadeIn();
    $(".switch-content div:first-child").toggleClass("switch-active");
    $(".switch-menu ul li").click(function(){
        var clicked = $(this).index()+1;
        $(this).parent().find("li.switch-active").toggleClass("switch-active");
        $(this).toggleClass("switch-active");
        $(this).parent().parent().parent().find(".switch-content div.switch-active").fadeOut();
        $(this).parent().parent().parent().find(".switch-content div.switch-active").toggleClass("switch-active");
        $(this).parent().parent().parent().find(".switch-content div:nth-child("+clicked+")").delay(200).toggleClass("switch-active");
        $(this).parent().parent().parent().find(".switch-content div:nth-child("+clicked+")").delay(200).fadeIn();
    });

^ this doesnt work
Does anyone know why? It makes no sense to me. And I know that my code could be simplier, I'm working on it. :)
Thank you and have a nice day

A:

I think it's because it's outside the $(document).ready()
The browser will load that function first when the page loads leaving the variables out of the function which would mean their value would be null.
To get it as a global do:
var Foo = {};

$(document.ready(function() {
    Foo.anchor = window.location.hash.substring(1);
    Foo.linked = $("#"+anchor).index()+1;
    // rest of code
});


Q:

Is this a suitable question? "Can you solve this existential problem for me?"

Is this a suitable question for this SE?

Can you solve this existential problem for me?
Being moral is so easy (about as difficult as hitting capslock) that it seems pointless, yet most people (whatever that means) seem to find it very difficult, so that immoralism for anyone else is also worthless. And yet, I want for almost nothing, and am not in love. Neither do I have any talent for art, or really anything at all.

A:

I suspect the question would be closed because it is too broad and primarily opinion-based, however, I can see why it is an important question. Because of that it could be a motivator for many questions that could be asked here. Each of those questions would be very specific giving someone else an opportunity to provide a brief answer.
To find more specific questions to ask, pick some tags of interest all motivated by this underlying question. Read the questions and answers under those tags, mark some as favorites and up-vote others. Some references in those posts may seem interesting. Read those references. When something puzzles you about what you have read, make a note suggesting a possible question you could ask later citing the source. You may even find while reading some questions that you can answer them. Answer them. Writing that answer may suggest to you another potential question.
From your notes of possible questions find a question you might ask that you are most interested in. Post the question. Accept the best answer if any. If you do not get at least one net up-vote think about how better to phrase your next question. Repeat the process posting no more than one question per day.
How will that process help answer the original question that might be too broad or opinion-based? All it will do is focus your attention on details that might be related to that question. These details are analogous to puzzle pieces that you place one-by-one into a solution of your underlying, motivating question. One day an answer to that motivating question may appear in the arrangement of those pieces.


Q:

LLVM loop optimization bug?

In my application I have the following Objective-C code:
-(void)layoutPages
{
    NSMutableArray* sections = [NSMutableArray array];
    [sections addObject:[[NSAttributedString alloc] initWithString:@"Hello world"]];

    for (NSAttributedString* contentSection in sections) {
        NSLog(@"%@",contentSection);
    }
}

Console output: 2014-04-22 14:11:01.505 MyApp[24784:830b] Hello world{}
If I compile for x86_64 architecture using -Os optimization, LLVM then silently optimizes out the loop variable 'contentSection'. When I use -O0, the bug disappears.
This is the output when I try to print the description of the contentSection variable:
(lldb) po contentSection
error: Couldn't materialize struct: the variable 'contentSection' has no location, it may have been optimized out
Errored out in Execute, couldn't PrepareToExecuteJITExpression

How is that possible? From my point of view a loop variable should never be optimized out when used inside the loop. I have seen that other people have a similar issue with LLVM but not with a loop variable. Could this be a compiler bug?

A:

This is probably a compiler settings issue. First you'll want to check that your run scheme is not in release mode. Go to "Edit scheme..." -> "Run" -> "Info" -> "Build Configuration". Make sure the value is set to "Debug".
If that is not the problem, then make sure your debug build settings don't have compiler optimization turned on. Make sure "Optimization Level" is set to "none" for debug. Also make sure there is no other place where the compiler optimization levels might be set, such as in the "Other C Flags" setting.


Q:

If $\left| x-2\right| < \frac{1}{100}$ Show That $\left| x^2 -4 \right| < \frac{1}{10}$

I am working through a problem involving absolute value inequalities, and I just can't seem to get on the right track. The problem is, if:
$$\left| x-2 \right| < \frac{1}{100} \text{,} $$
show that
$$ \left| x^2-4 \right| < \frac{1}{10}$$
must be true. I thought it might have something to do with $x^2-4$ being a difference of squares with $x-2$ as a factor, but that just lead me in circles. Any pointers or hints would be appreciated! Thank you.

A:

If $|x-2|<\frac{1}{100}$, then $|x| < 2+ \frac {1}{100} <8$
So
$$|x^2-4| = |x-2||x+2| < \frac{1}{100} (|x|+2)<\frac{1}{10}.$$


Q:

How to properly handle data using asynchronous service with silverlight and telerik charts

I have a silverlight application using telerik charts.
In my view I have the chart in xaml.  In the code behind of the view I have something like this:
public partial class MyView : UserControl
{
    private MyViewModel viewModel;

    public MyView()
    {
        InitializeComponent();
        CreateChartMappings();  // Creates the SeriesMappings for my chart
        viewModel = new MyViewModel();
        Chart1.ItemsSource = viewModel.MyChartData;

        DataContext = viewModel;
        Resources.Add("ViewModel", viewModel);

    }
}

In my ViewModel I have this:
public class MyViewModel : INotifyPropertyChanged
{
    private ObservableCollection<ChartData> myChartData;
    public ObservableCollection<ChartData> MyChartData
    {
        get { return myChartData; }
        set { myChartData= value; OnPropertyChanged("MyChartData"); }
    }

    public MyViewModel()
    {
        MyWebServiceClient service = MyWebServiceClient.CreateInstance();

        service.GetChartDataCompleted +=
            new EventHandler<GetChartDataCompletedEventArgs>(GetChartDataCallback);

        service.GetChartDataAsync();
    }

    private void GetChartDataCallback(object sender, GetChartDataCompletedEventArgs e)
    {
        if (e.Error == null)
        {
            MyChartData = e.Result;
        }
    }
}

I know for sure that GetChartData will return the correctly typed data that can be used for the chart and see that GetChartDataCallback does return results in e.Result, but I don't know how to get that data loaded into my chart.
If I do something like Chart1.ItemsSource = viewModel.MyChartData; after I am sure the service returns data then data loads into the chart fine.  For example, if I create a button in my view that calls that line of code it will load the data from the service into the chart.
Also if I replace the asyc calls with a normal method call it will work okay as well, so my problem might have something to do with not handling the asyc call correctly?

A:

There are two potential problems I see with the code you've presented above:

You're not binding the chart's ItemsSource to your view-model object.
There may be cross-thread issues depending on which thread handles the async callback.

When you assign to the MyChartData property in your GetChartDataCallback method, the PropertyChanged event is being fired.  But because you haven't bound anything in the view-layer to it, nothing is listening to this event.  Your chart will not get any new data.
To use binding, you can replace the line
Chart1.ItemsSource = viewModel.MyChartData;

with
Binding binding = new Binding("MyChartData") { Source = viewModel };
Chart1.SetBinding(RadChart.ItemsSourceProperty, binding);

Alternatively, you could set up the binding in XAML.
As for the cross-thread issues, I don't have any code for an async service such as yours to test against.  Instead, I knocked up a simple test application that attempts to update the view-model data in a separate thread.  After making up some data, this application tries to assign this data to a view-model property much like yours above, using the line
ChartData = data;

When I ran this application, this line caused an UnauthorizedAccessException, which mentioned an invalid cross-thread access.
I replaced the line above with
Deployment.Current.Dispatcher.BeginInvoke(() => { ChartData = data; });

This change got rid of the exception and allowed me to see the (made-up) data in the chart.  (You'll need to add a line using System.Windows; if you don't already have one.)


Q:

How to query from a hierarchy in oracle

I work with an Oracle database that has tables for customers, chains and campaigns. Like so (stripped down):
TABLE CUSTOMER
  ACCOUNTNUMBER   VARCHAR2
  CHAIN           VARCHAR2
  CATEGORY        VARCHAR2

TABLE CHAIN
  CODE            VARCHAR2
  PARENTCHAIN     VARCHAR2

TABLE CAMPAIGN
  ID              NUMBER
  DISCOUNT        NUMBER

TABLE CAMPAIGN_ELIGIBILITY
  CAMPAIGNID      NUMBER   --ID of the campaign
  ACCOUNTNUMBER   VARCHAR2 --Customer included in the campaign
  CHAINCODE       VARCHAR2 --Chain included in the campaign
  CUSTCATCODE     VARCHAR2 --Customercategory included in the campaign

A customer can be eligible for a campaign specifically (based on accountnumber), through his defined customergroup or as a member of a chain.
I use this query to find all campaigns that are valid for a given customer:
select * from campaign where id in
(
  select unique campaignid from campaign_eligibility where
    accountnumber=:accountnumber
  union
  select unique campaignid from campaign_eligibility where
    chaincode =
      (select chain from debtable where accountnumber=:accountnumber)
  union
  select unique campaignid from campaign_eligibility where
    custcatcode =
      (select category from customer where accountnumber=:accountnumber)
)

Now, let's say that the customer "Popeye Spinach Empire" is a member of the chain "Spinach Dealers Inc.", which in turn is part of the larger chain "GreenFud R US", which in turn is part of the chain "FoAC". When there's a campaign that targets "GreenFud R US", Popeye is eligible for that campaign. My query will only return campaigns where Popeye has been specifically added, or that targets "Spinach Dealers Inc."
How can I modify my query to include campaigns that a customer is indirectly part of?

A:

WITH    chains AS
        (
        SELECT  code
        FROM    chain c
        START WITH
                c.code IN
                (
                SELECT  chain
                FROM    campaign_eligibility
                WHERE   accountnumber = :acc
                UNION ALL
                SELECT  chain
                FROM    customer c
                JOIN    campaign_eligibility ce
                ON      ce.custcatcode = c.category
                WHERE   accountnumber = :acc
                UNION ALL
                SELECT  chain
                FROM    customer
                WHERE   accountnumber = :acc
                )
        CONNECT BY
                c.code = PRIOR c.parentchain
        ) ch
SELECT  *
FROM    campaign
WHERE   c.id IN
        (
        SELECT  campaignid
        FROM    chains
        JOIN    campaign_eligibility ce
        ON      ce.chaincode = c.code
        )


Q:

How can I read a php file into a string using php?

Lets say I want to use a php script to read the current page's code into a string how would I do that without executing the php contents of the page?
For example using
file_get_contents("test.php");

Will get the contents of test.php but as it does it will execute the code... How can I just get the source code of the file?

A:

file_get_contents() will only execute that file and give you the output as the content if you refer to it as a URL. If you just give a filename, it will attempt to read it from (in your case) the current directory.


Q:

Why DataAdapter is not Disposable

I know there is probably an obvious reason but I can't find it..
I usually use the using statement during DB connection and data reading, but I can't use it on DataAdapter because it doesn't implement IDisposable.
Also: how can it behave after filling a dataset?
Does it close itself the connection?
Only close it or dispose it?
Do I have to dispose the internal connection by myself after the dataset filling? If so, why IDataAdapter doesn't have a related property/method?

A:

DataAdapter doesn't close the connection as you might want to keep using this connection to populate other DataSets.
The exception is when the connection wasn't in open state before Fill method was called (Thanx Richard): https://stackoverflow.com/a/2472886/2258

A:

A DataAdapter instance does not hold references to unmanaged code. It simply acts as a "bridge" between the commands and the datasets.

The DataAdapter serves as a bridge between a DataSet and a data source
  for retrieving and saving data. The DataAdapter provides this bridge
  by mapping Fill, which changes the data in the DataSet to match the
  data in the data source, and Update, which changes the data in the
  data source to match the data in the DataSet.

Source: http://msdn.microsoft.com/en-us/library/system.data.common.dataadapter.aspx

A:

DataAdapter dosn't implement IDisposable because it doesn't have any member variables that need to be handled outside of normal garbage collection.  In other words it doesn't need to implement IDisposable.
If your intrested you can see the source code to the Mono DataAdapter here : http://www.java2v.com/Open-Source/CSharp/2.6.4-mono-.net-core/System.Data/System/Data/Common/DataAdapter.cs.htm
In general if you going to close the connection after using it, go ahead in put the connection in a using scope, but its ok too to have a singleton and have multipal DataAdapters in multipal scopes using the same connection.
Hope this makes sense.


Q:

std::set_terminate for DLL?

I have a DLL that will be loaded by another 3rd party application.
I'm trying to figure out if it's possible for me to catch any/all exceptions generated by my own DLL.
If I was in charge of the application's code, I'd use std::set_terminate within main() to set up a catch-all error handling function. But since my DLL will be inside someone else's application, I can't call std::set_terminate within main().
Is there a way for me to create such an override that just applies my own code, without doing something nasty like couching every single one of my application's functions inside a try/catch block or something?

A:

When designing a DLL, you should ensure that you never let exceptions escape from your entry points. Exceptions that cross module boundaries become tricky, if they work at all, and you are best off avoiding them.
Quoting from C++ Coding Standards: 101 Rules, Guidelines, and Best Practices by Herb Sutter and Andrei Alexandrescu:

Item 62: Don't allow exceptions to propagate across module boundaries.
Don't throw stones into your neighbor's garden: There is no ubiquitous binary standard for C++ exception handling. Don't allow exceptions to propagate between two pieces of code unless you control the compiler and compiler options used to build both sides; otherwise, the modules might not support compatible implementations for exception propagation. Typically, this boils down to: Don't let exceptions propagate across module/subsystem boundaries.

When you're dealing with a DLL, as opposed to a static library, you don't have any guarantees. The third-party application that consumes your DLL is a foreign module (the neighbor's garden). You have no guarantee that the two modules will be compiled with the same compiler and compiler options, so you don't know if they will treat exceptions the same way. In fact, you don't even know if both modules will be written in C++, so letting C++ exceptions propagate is right out. There are ways you can successfully propagate exceptions across module boundaries with Windows's Structured Exception Handling (SEH), but you shouldn't.
Aside from technical and implementation concerns, though, throwing exceptions from a DLL just creates a bad interface. The client application should not have to handle exceptions from your DLL's routines. Exceptions are implementation details: you should handle them internally. If you need to indicate success or failure, return an error code. Those can be trivially handled by any language that may consume your DLL, from C to BASIC to Python.
Your proposed solution is to basically hook up a global, unhandled exception handler that would catch any and all exceptions thrown by your DLL before they cross the module boundary. That doesn't really exist. DLLs don't have a global exception handler. Exceptions propagate by unwinding (walking up) the call stack until they find a suitable handler. If there's no handler, they'll propagate all the way up to the entry point (main), and if not handled there, they'll cause the application to terminate, and the operating system will present a "friendly" dialog. That's why it's easy to install an unhandled exception handler in the application. There's no such equivalent for a DLL, because the DLL doesn't have its own single, central main function. Instead, what it has is a series of entry points: exported functions that are called by the client application. So, your unhandled exception handlers should be in those entry points.
Each entry point would have its own exception handler. You can basically wrap the whole entry point in a big try-catch if you want. That way, all of your internal implementation functions can throw exceptions with reckless abandon, but they'll all be trapped in the entry points before they're allowed to propagate outside of the module.
Think of each entry point (exported function) provided by your DLL as its own main function, since that's basically what it is. The DllMain function (as it's conventionally known on Windows) is altogether different. You are so severely limited in terms of what you're allowed to do there that you should never be calling code that has the possibility of throwing an exception.
As an additional point, you probably don't want to be calling abort or std::terminate from code in a DLL anyway, since that will terminate the entire process, including the client application. When you're a guest in someone else's house, you shouldn't call the demolition company to have their house destroyed. Log your exception internally, but do whatever it takes to maintain a consistent external state and not crash the client application just because you experienced an internal error.


Q:

Print value of UINavigationController's stack, every time it changes

Is it possible to print value of variable in console every time it changes and what is the most convenient way to do it?
EDIT:
I want to track value of UINavigationController's controllers stack

A:

You can use didSet property observer, for example:
var exampleValue: String? {
    didSet {
        if let exampleValue = exampleValue {
            print(exampleValue)
        }
    }
}

A:

For observing the UINavigationController stack, use UINavigationControllerDelegate.
func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) {
     // print the stack now.
}


Q:

mapper function is always needed in a mapreduce program?

Im trying to develop a hadoop mapreduce program to calculate the maximum temperature inside a text file.
The input text file looks like this:
City1 - 10
City2 - 15
City3 - 4
city4 - 20
Im beginner in mapreduce, but I read that with mapper, the output should be the input transformed in meaningful key value pairs. But If I already have a input file like below, I dont need to write a mapper file (because is already with key value pairs)??
City1 10
City2 15
City3 4
city 4 10
I was trying to develop the mapper file but Im not understanding if its really necessary in this case.
Code:
for line in sys.stdin:

    line = line.strip()
    print line

A:

Yes, it is always needed. The mapper is only there to guarantee that the reducer receives sorted and partitioned input.
It's a framework design choice, Hadoop requires your mapper to be set. In your example you can use the standard Mapper / IdentityMapper.


Q:

vb .net shorten an if statement

I'm trying to make this cleaner... I know there's lots of shortcuts for If statements, but I don't know what's best.
If item.RecurrenceId > 0 Then
    xmlTextWriter.WriteElementString("recordtype", "2")
ElseIf IsNothing(item.OngoingEndDate) = False Then
    xmlTextWriter.WriteElementString("recordtype", "1")
Else
    xmlTextWriter.WriteElementString("recordtype", "0")
End If

A:

Shortcuts don't always make for better code. Though short code can be "clean", it may not be as legible as what you have stated.
With that said, I would stick with what you have, as long as it meets your purpose. It's "clean", but more importantly it's clear what outcome you're going for.


Q:

Change body width using javascript

I just came to know that we can find out the screen resolution of our users using screen.width and screen.height etc. But is there any way to have a variable body width. I mean can i set the body width property using jquery or javascript. This is gonna change with the resolution of every user so that my site seems perfect in all of them...
Can anyone help me in having code to set the width(CSS) of my page according to the value obtained through Jscript above.
Thanks

A:

You can set the body with JavaScript...
document.body.style.width = '700px';

...or if you are using jQuery...
$('body').css('width', '700px');

A:

You can use jquery and do it through .css
$('body').css('width', '1000px');

css() documentation.


Q:

Updating weights in logistic regression using gradient descent?

The loss function for logistic regression is $\sigma(z)$=$\frac{1}{1+e^{-z}}$ and $z=\theta^T.x_i$ but in order to make our loss function convex we consider this alternative formula:
$$-\frac{1}{n}\sum_{i=1}^n[y_i.log(h_\theta x_i) + (1-y_i)(1-h_\theta x_i)]$$
If we take derivative of this loss function w.r.t $\theta_i$ then we'd get something like:
$$-\frac{1}{n}\sum_{i=1}^n (h_\theta(x) - y_i)*x_j$$
Now the gradient update step will be,
$$\theta_i := \theta_i -\alpha.-\frac{1}{n}\sum_{i=1}^n (h_\theta(x) - y_i)*x_j$$
My doubt is what is $h_\theta(x)$ here? Is it sigmoid function i.e $\frac{1}{1+e^{-z}}$?  Another doubt is what is $x_j$ term here refer to? Is it our input datapoint?
Is my understanding clear regarding the loss function above. If any mistakes please do correct me? I am following andrew-ng ML course.

A:

My doubt is what is $hθ(x)$ here? Is it sigmoid function i.e $\frac{1}{1+e^{-z}}$?

$h_{\theta}(x)$ is your hypothesis function. Which is given as
$$ h_{\theta}(x) = \frac{1}{1+e^{-\theta^{t}x}} $$
So if you sigmoid function $\sigma(z)$ is given as
$$ \sigma(z) =\frac{1}{1+e^{-z}} $$

Another doubt is what is $xj$ term here refer to? Is it our input
  datapoint?

$x_{j}$ is one of the samples.


Q:

Data consistency between Oracle tables

I have one big table A who has PK (C1, C2, C3) and many other columns, to make the select faster, a smaller table B was created with PK (C1, C2). So we can do a select by joining the two tables to find a row in A.
But the problem now is that it can happen that if data is corrupted in B which results in a joint select returns nothing but we still have a row in A.
Am I doing something wrong with this design and how can I ensure the data in those two tables are consistent?
Thanks a lot.

A:

Standard way - if those tables are in a master-detail relationship - is to create a foreign key constraint which will prevent deleting master if details exist.
If you can fix it now, do it - then create the constraint.
If you can't, then create foreign key constraint using INITIALLY DEFERRED DEFERRABLE option so that current values aren't checked, but future DML will be.
Finally, to fetch data although certain rows don't exist any more, use outer join.


Q:

Data binding in mat-select of angular materials does not work

I'm using angular 6 and angular material for front page of my application, and I have a module called Roles which has a collection of Permissions associated with it, on Roles page, I have an edit button which on clicking retrieves the role by its id and the role has a collection of permissions associated with it, as you can see in image below: when I click on edit button, a pop-up appears, which is an angular material form and among other fields, it has the following field:

    <mat-form-field class="form" floatPlaceholder="never" shouldPlaceholderFloat="false">
     <mat-select [(ngModel)] = "data.permissions" [ngModelOptions]="{standalone: true}" multiple>
       <mat-option *ngFor="let permission of data.allPermissions" [value]="permission.name">
         {{permission.name}}
       </mat-option>
     </mat-select>
    </mat-form-field>

its expected that the permissions array should be pre-populated in mat-select drop-down because i have binded it with [(ngModel)] = "data.permissions", but it does not, as you can see in the second image
.
Any help will be highly appreciated. THANKS!

A:

Are you looking for this?
Change that you need:

First:

Use [compareWith]="compareFn" in HTML and TS  Code:
compareFn(c1,c2): boolean {
  return c1 && c2 ? c1.id === c2.id : c1 === c2;
}

Second:

For mat-option set [value] to  permission like:
[value]="permission"

HTML Code:

    <mat-form-field class="form" floatPlaceholder="never" shouldPlaceholderFloat="false">
        <mat-select [(ngModel)]="data.permissions" [ngModelOptions]="{standalone: true}" multiple [compareWith]="compareFn">
            <mat-option *ngFor="let permission of data.allPermissions" [value]="permission">
                {{permission.name}}
            </mat-option>
        </mat-select>
    </mat-form-field>

Stackblitz


Q:

Change textbox value when click link in jquery div based dynamically

I created HTML where I want if user hit  then 123456789 will fill in textbox dynamically (each-one for different value as in  tags) and the border of that selected div will red. I try to search this method on google but I couldn't find that and I am familiar with Js and Jquery so I cant do this But Stack-overflow is developer friends and here millions of well developers and students who helps everyone. Please help to how i made this function.
My code is given below:

Shiv

123456789

Dummy

1253648595

A:

If i understood correctly,

$(function(){
$('.toggle_contact').click(function(){

 var contactNumber = $(this).data('number');
 $(this).parents('.this_contact').addClass('selected').siblings().removeClass('selected');
 $(this).parents().find('input:text').val(contactNumber);
})
})
.selected{
  background-color:red;
}

Shiv

Dummy

<input type="text" name='name' value="">


Q:

Accessing fullCalendar JSON customData in dayclick callback

Sorry for this most likely simple question. I would like to add some custom JSON data to fullCalendar and use it in my dayClick callback function. More specific I want to access and change elements on customData in dayClick. However I could not figure out how to do that. Is it possible without changing the fullcalendar source code?
Thanks a lot in advance
Jens
$('#calendar').fullCalendar({
    ....
    firstDay: 1,
    customData: { foo: 'bar', more: 'baz' },
    dayClick: function(date, allDay, jsEvent, view) {
        // Within the callback function, this is set to the <td> of the clicked day.
        var t = $(this);
        var foo = customData.foo; // does not work
        customData.more = 'foo'; // does not work

        // Change the day's background color
        if (t.hasClass('badge-important') && foo == 'bar') {
            t.removeClass('badge-important');
        } else {
            t.addClass('badge-important');
        }
    },
});

A:

The problem is that you are not defining a customData variable in any place. The following approach of creating a variable to store your JSON will solve your problem. Check the code below:
var customData = {"foo":"bar"};

$('#calendar').fullCalendar({
....
firstDay: 1,
customData: customData,
dayClick: function(date, allDay, jsEvent, view) {
    // Within the callback function, this is set to the <td> of the clicked day.
    var t = $(this);
    var foo = customData.foo; // will now work
    customData.more = 'foo' // will work too

    // Change the day's background color
    if (t.hasClass('badge-important') && foo == 'bar') {
        t.removeClass('badge-important');
    } else {
        t.addClass('badge-important');
    }
},
});

I hope it helped. Cheers


Q:

What is the proper way to send an HTTP 404 response from an ASP.NET MVC action?

If given the route:
{FeedName}/{ItemPermalink}
ex: /Blog/Hello-World
If the item doesn't exist, I want to return a 404. What is the right way to do this in ASP.NET MVC?

A:

Shooting from the hip (cowboy coding ;-)), I'd suggest something like this:
Controller:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return new HttpNotFoundResult("This doesn't exist");
    }
}

HttpNotFoundResult:
using System;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace YourNamespaceHere
{
    /// An implementation of <see cref="ActionResult" /> that throws an <see cref="HttpException" />.
    public class HttpNotFoundResult : ActionResult
    {
        /// Initializes a new instance of <see cref="HttpNotFoundResult" /> with the specified <paramref name="message"/>.
        /// <param name="message"></param>
        public HttpNotFoundResult(String message)
        {
            this.Message = message;
        }

        /// Initializes a new instance of <see cref="HttpNotFoundResult" /> with an empty message.
        public HttpNotFoundResult()
            : this(String.Empty) { }

        /// Gets or sets the message that will be passed to the thrown <see cref="HttpException" />.
        public String Message { get; set; }

        /// Overrides the base <see cref="ActionResult.ExecuteResult" /> functionality to throw an <see cref="HttpException" />.
        public override void ExecuteResult(ControllerContext context)
        {
            throw new HttpException((Int32)HttpStatusCode.NotFound, this.Message);
        }
    }
}
// By Erik van Brakel, with edits from Daniel Schaffer :)

Using this approach you comply to the framework standards. There already is a HttpUnauthorizedResult in there, so this would simply extend the framework in the eyes of another developer maintaining your code later on (you know, the psycho who knows where you live).
You could use reflector to take a look into the assembly to see how the HttpUnauthorizedResult is achieved, because I don't know if this approach misses anything (it seems too simple almost).

I did use reflector to take a look at the HttpUnauthorizedResult just now. Seems they're setting the StatusCode on the response to 0x191 (401). Although this works for 401, using 404 as the new value I seem to be getting just a blank page in Firefox. Internet Explorer shows a default 404 though (not the ASP.NET version). Using the webdeveloper toolbar I inspected the headers in FF, which DO show a 404 Not Found response. Could be simply something I misconfigured in FF.

This being said, I think Jeff's approach is a fine example of KISS. If you don't really need the verbosity in this sample, his method works fine as well.

A:

We do it like so; this code is found in BaseController
///
/// returns our standard page not found view
///
protected ViewResult PageNotFound()
{
    Response.StatusCode = 404;
    return View("PageNotFound");
}

called like so
public ActionResult ShowUserDetails(int? id)
{
    // make sure we have a valid ID
    if (!id.HasValue) return PageNotFound();

A:

throw new HttpException(404, "Are you sure you're in the right place?");


Q:

How to put some color on image

I have here the circle image, what I want to do is to put some color in specific position.. For example, when I click the button1, the left side of the circle will be filled by red, and when I click the button2, the right side will be filled by as well, and when I click the button1 again, the color will be removed, and so on...
I've done some research about it, and found out 2 ways to do it. First is, to layover the circle with another image. Second is to draw, and use the Graphics class in C#..
Now, my question is, is there another possible way to do it? What is the best way?
P.S: The purpose of this is for the tooth chart. :)

A:

Here's a Resizable, Clickable, UserControl based on qing`s post.  You can click on the regions directly to toggle them, or change them via code.

public partial class ToothChart : UserControl
{

    public ToothChart()
    {
        InitializeComponent();
        this.DoubleBuffered = true;
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        if (this.ParentForm != null)
        {
            this.ParentForm.FormClosing += (s, evt) => { OnHandleDestroyed(new EventArgs()); };
        }
    }

    protected override void OnHandleDestroyed(EventArgs e)
    {
        base.OnHandleDestroyed(e);

        if (this._pathTop != null)
        {
            this._pathTop.Dispose();
            this._pathTop = null;
        }
        if (this._pathRight != null)
        {
            this._pathRight.Dispose();
            this._pathRight = null;
        }
        if (this._pathBottom != null)
        {
            this._pathBottom.Dispose();
            this._pathBottom = null;
        }
        if (this._pathLeft != null)
        {
            this._pathLeft.Dispose();
            this._pathLeft = null;
        }
        if (this._pathCenter != null)
        {
            this._pathCenter.Dispose();
            this._pathCenter = null;
        }
    }

    private GraphicsPath _pathTop = null;
    private GraphicsPath _pathLeft = null;
    private GraphicsPath _pathBottom = null;
    private GraphicsPath _pathRight = null;
    private GraphicsPath _pathCenter = null;

    private bool _TopRegion = false;
    public bool TopRegion
    {
        get
        {
            return _TopRegion;
        }
        set
        {
            if (_TopRegion != value)
            {
                _TopRegion = value;
                this.Invalidate();
            }
        }
    }

    private bool _RightRegion = false;
    public bool RightRegion
    {
        get
        {
            return _RightRegion;
        }
        set
        {
            if (_RightRegion != value)
            {
                _RightRegion = value;
                this.Invalidate();
            }
        }
    }

    private bool _BottomRegion = false;
    public bool BottomRegion
    {
        get
        {
            return _BottomRegion;
        }
        set
        {
            if (_BottomRegion != value)
            {
                _BottomRegion = value;
                this.Invalidate();
            }
        }
    }

    private bool _LeftRegion = false;
    public bool LeftRegion
    {
        get
        {
            return _LeftRegion;
        }
        set
        {
            if (_LeftRegion != value)
            {
                _LeftRegion = value;
                this.Invalidate();
            }
        }
    }

    private bool _CenterRegion = false;
    public bool CenterRegion
    {
        get
        {
            return _CenterRegion;
        }
        set
        {
            if (_CenterRegion != value)
            {
                _CenterRegion = value;
                this.Invalidate();
            }
        }
    }

    protected override void OnSizeChanged(EventArgs e)
    {
        base.OnSizeChanged(e);
        if (this.IsHandleCreated && this._pathTop != null)
        {
            this.UpdateRegions();
        }
    }

    private void UpdateRegions()
    {
        int diameterBig = Math.Min(this.Width, this.Height) - 10;
        int diameterSmall = Math.Min(this.Width, this.Height) / 3;
        if (diameterBig > 0 && diameterSmall > 0)
        {
            Point _centerPoint = new Point(this.Width / 2, this.Height / 2);
            Rectangle rectangle = new Rectangle(_centerPoint.X - diameterBig / 2, _centerPoint.Y - diameterBig / 2, diameterBig, diameterBig);
            Rectangle rectangle2 = new Rectangle(_centerPoint.X - diameterSmall / 2, _centerPoint.Y - diameterSmall / 2, diameterSmall, diameterSmall);

            _pathTop.Reset();
            _pathTop.AddArc(rectangle, 225, 90);
            _pathTop.AddArc(rectangle2, -45, -90);

            _pathLeft.Reset();
            _pathLeft.AddArc(rectangle, 135, 90);
            _pathLeft.AddArc(rectangle2, -135, -90);

            _pathBottom.Reset();
            _pathBottom.AddArc(rectangle, 45, 90);
            _pathBottom.AddArc(rectangle2, -225, -90);

            _pathRight.Reset();
            _pathRight.AddArc(rectangle, -45, 90);
            _pathRight.AddArc(rectangle2, -315, -90);

            _pathCenter.Reset();
            _pathCenter.AddEllipse(rectangle2);

            this.Invalidate();
        }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        if (this.IsHandleCreated)
        {
            if (this._pathTop == null)
            {
                this._pathTop = new GraphicsPath();
                this._pathRight = new GraphicsPath();
                this._pathBottom = new GraphicsPath();
                this._pathLeft = new GraphicsPath();
                this._pathCenter = new GraphicsPath();
                this.UpdateRegions();
            }

            e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
            if (this.TopRegion)
            {
                e.Graphics.FillPath(Brushes.Blue, _pathTop);
            }
            e.Graphics.DrawPath(Pens.Black, _pathTop);

            if (this.RightRegion)
            {
                e.Graphics.FillPath(Brushes.DarkRed, _pathRight);
            }
            e.Graphics.DrawPath(Pens.Black, _pathRight);

            if (this.BottomRegion)
            {
                e.Graphics.FillPath(Brushes.Teal, _pathBottom);
            }
            e.Graphics.DrawPath(Pens.Black, _pathBottom);

            if (this.LeftRegion)
            {
                e.Graphics.FillPath(Brushes.Yellow, _pathLeft);
            }
            e.Graphics.DrawPath(Pens.Black, _pathLeft);

            if (this.CenterRegion)
            {
                e.Graphics.FillPath(Brushes.LightGreen, _pathCenter);
            }
            e.Graphics.DrawPath(Pens.Black, _pathCenter);
        }
    }

    protected override void OnMouseClick(MouseEventArgs e)
    {
        base.OnMouseClick(e);

        Point p = new Point(e.X, e.Y);

        if (this._pathTop.IsVisible(p))
        {
            this.TopRegion = !this.TopRegion;
        }
        else if (this._pathRight.IsVisible(p))
        {
            this.RightRegion = !this.RightRegion;
        }
        else if (this._pathBottom.IsVisible(p))
        {
            this.BottomRegion = !this.BottomRegion;
        }
        else if (this._pathLeft.IsVisible(p))
        {
            this.LeftRegion = !this.LeftRegion;
        }
        else if (this._pathCenter.IsVisible(p))
        {
            this.CenterRegion = !this.CenterRegion;
        }
    }

}


Q:

JOIN, GROUP BY, SUM Issue Mysql

Assuming I have this table
tableA
ID       value
1          5
1          5
3          10
2          4
2          2
1          2

tableB
ID        Name
1         apple
2         carrot
3         banana

If the expected max value of apple is 10, carrot is 5, and banana is 15 the output table would be
table output
ID     Name       value
1      apple      12
2      carrot     6

what SQL statement I need to solve this?
what I have done so far:
SELECT a,ID, b.name , sum(a.valueSUM) AS value FROM tableA a
INNER JOIN tableB b
ON a.id = b.id
GROUP BY id

what options i need on the WHERE clause to pull this off?

A:

The inner subquery groups them normally and then the main query is what deals with limiting the results.
SELECT * FROM
     (select
      b.id,
      b.name as name,
      SUM(a.value) as the_sum
      from tableA a inner join tableB b
      on a.Id = b.id
      group by b.name, b.id
     ) y
where (name = 'apple' and the_sum >= 10) OR
  (name = 'banana' and the_sum >= 15) OR
  (name = 'carrot' and the_sum >= 5)

It seems your sample data has changed, please try this. I thought the ID doesnt have to follow tableA/tableB's id and the id is auto-generated as per the results.
Would be nice if you have another table that sets the threshold per name


Q:

Does RedP+HI reduce all carbon functional groups to alkane?

I've seen the related questions 1 and 2, they're not duplicates
So. when introducing Red P+HI reduction, our teacher said that it is the strongest reducing agent, and it can reduce any functional group i.e. all of these: carboxylic acid,  acid anhydride, ether, amide, acid halide, carbonyl, and nitrile
However, today I stumbled upon a question in my book involving a step in the synthesis of ibuprofen, where they did not reduce the carboxylic acid group even after using RedP+HI. I searched a lot on the internet, and finally came across this paper which confirms this:

paper - notice they've only reduced the alcohol in step (ii)
This now makes me wonder if what I was taught is actually correct. Which brings me to the question:

Does RedP+HI really reduce all carbon functional groups to alkane?

A:

Nope, in general it doesn't. You are correct. See also for example:

A. Aramini, M. R. Sablone, G. Bianchini, A. Amore, M. Fanì, P. Perrone, A. Dolce, M. Allegretti, Tetrahedron 2009, 65 2015–2021. DOI: 10.1016/j.tet.2009.01.005:

M. Dobmeier, J. M. Herrmann, D. Lenoir, B. König, Beilstein J. Org. Chem. 2012, 8, 330–336. DOI: 10.3762/bjoc.8.36 Open access PDF. (This also includes your one as a reference, too.):

If it did, it would be a pretty poor reagent since it would have no functional group tolerance, so not very useful. However, it is not unlikely that under special conditions it might be able to reduce carboxylic groups as well.


Q:

Is it possible to have a git repo inside another git repo

I have a django project managed with git. I am git pushing it to my host. Now, I want to be able to push just one of the directories (inc. all sub dirs) to another git repo. How is it possible, if it is possible at all?
Edit: So I want that directory to be a git repo itself.

A:

You could look at git's support for submodules.  You would add the second repository as a submodule to your main project, e.g. with commands like:
git submodule add git://wherever/blah.git library-code
git commit -m "Added a new submodule called 'library-code'"

When you change into the library-code subdirectory, it's as if the parent repository doesn't exist - you can change origin to use a transport that you can push over and then push as if it were completely independent.
To specify that you want the submodule to be at a particular version, you should change into the submodule and use git checkout to switch to the right version.  Then you change back up to the main repository and stage and commit that new submodule version with:
git add library-code
git commit -m 'Change the submodule version'

The tree of the main repository just stores the version that the submodule should be at, so when you push the main repository, it's not pushing any of the files in the submodule.
In order to split off this subdirectory, while preserving history, you'll need to clone your original repository and user git filter-branch to rewrite the history, as described in this answer:

Detach (move) subdirectory into separate Git repository

Then you can push that to a newly created repository GitHub repository, return to your original project, remove the subdirectory, and replace it with the submodule as described above.
If you're not very familiar with git concepts then this may be difficult for you - I  would recommend reading up on git submodules beforehand.


Q:

Limiting choices to an Generic Inline FK field dependant on the object that the Inline is being related to

I'm trying to limit the choices of a FK field found in a generic inline, depending on what the inline is attached to.
For example I have Article, with a Generic relation Publishing, edited inline with the Article.
I'd like for the PublishingInline to 'know', somehow, that it is currently being edited inline to an Article, and limit the available PublishingTypes to content_type Article.
This is the start that I've made:
class PublishingInlineForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):

        try:
            data = kwargs.pop("data", {})
            if kwargs["instance"]:
                publishing_type_kwargs = {
                    'content_type': kwargs["instance"].content_type, }
                data["publishing_type"] = PublishingType.objects.filter(**publishing_type_kwargs)
                kwargs["data"] = data
        except KeyError:
            pass

        super(PublishingInlineForm, self).__init__(*args, **kwargs)

class PublishingInline(generic.GenericStackedInline):

    form = PublishingInlineForm

    model = get_model('publishing', 'publishing')
    extra = 0

A:

If i understand you correctly formfield_for_foreignkey on your GenericInlineModelAdmin is your friend.
Something along these lines should do it:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
    print self.parent_model # should give you the model the inline is attached to
    if db_field.name == "publishing_type":
        kwargs["queryset"] = ... # here you can filter the selectable publishing types based on your parent model
    return super(PublishingInline, self).formfield_for_foreignkey(db_field, request, **kwargs)


Q:

jQuery insertBefore on each instance unexpected behaviour

I have a bunch of div's with the class 'row', containing two divs 'image' and 'description'
I'm trying to make 'description' insert before 'image' in all instances.
I tried the following code which makes logical sense to me, but the outcome is very unexpected as you can see in the fiddle.
$('.row').each(function(){ //Select each row

    $('.description',this).insertBefore('.image',this);
    // For this row, put this description before this image

});

http://jsfiddle.net/bazzle/ott5tx06/
HTML

        image row 1

        description row 1

        image row 2

        description row 2

        image row 3

        description row 3

CSS
.row div{
    width:45%;
    height:100px;
    display:inline-block;
    margin-bottom:3px;
}
.image{
    background-color:red;
}
.description{
    background-color:green;
}

A:

insertBefore needs an element as its argument.
http://jsfiddle.net/ott5tx06/4/
$('.row').each(function(){ //Select each row

    $('.description',this).insertBefore($('.image',this));
    // For this row, put this description before this image

});


Q:

Word wrap in ggmap labels?

I have some very long labels for points on a map (Avg 35 chars per label).
Is there a "word wrap" of sorts in ggmap annotate (or other labeling function) so the lines are not stretched across the map? I'd like to either limit by number of chars or force a linebreak at a space.
Thanks!

A:

Was able to find a solution here by replacing spaces with the linebreak character "\n"
StackedList <- gsub(" ", "\n", UnStackedList)


Q:

How many XP do I get by killing monsters?

I have some items that gives me +X experience points for each kill, or +X%, but how does this compare to the XP obtained by killing those monsters? I can't see how many points I get when I kill them.

A:

Since patch 2.1.2 the "Monster Kills Grant +X experience" secondary affix is multiplicative with your Bonus Experience %.
Sadly, I don't have any sources, but I've done some extensive testing and I found the following formula for XP per kill:
XP per kill = (Base XP * Monster type + Bonus Experience per Kill) * (1 + Bonus Experience * 0.01) * Multiplier * Pool of Reflection
Basically, the system works as follows: every monster has a certain base XP. For instance, a Risen on level 1 give you 30 XP per kill, but only when you are level 1 as well. Once you start gaining levels, you lose 10% XP for each level that you're higher than the monster you just killed.
When you enter Old Tristram Road at level 1, then all monsters will spawn at level 1. Should you reach level 2, then the monsters will not automatically level with you and you'll start receiving 10% less XP per kill (27 at level 2, 24 at level 3, etc.). Only monsters that spawn from this moment on will be at your level, such as Risen crawling out of the ground or graves, or when you enter a new area.
You don't get more XP when the monster level is higher than your level. I started a level 2 co-op game, had my level 1 character join, made the level 2 character spawn some monsters, made the level 2 character leave and let the level 1 character kill the level 2 monster: it gave the regular, level 2 monster XP.
Anyway, the amount of XP that the white version of a monster gives without any bonus XP modifiers on Normal mode is what we'll call Base XP.
Monster type is a modifier that's only relevant for champions or rares. For champions it's 3, for rares it's 5. Otherwise, it's 1. Minions don't give any extra XP.
When you open your inventory screen, and open the details, you'll see two items under the heading Adventure which contribute to how much XP you're earning: Bonus Experience and Bonus Experience per kill. The first item is split in two separate points, the descriptions are from the game itself:

Experience gains from killing monsters increased by X%. This is Bonus Experience
Multiplier: X. This multiplier is granted in multiplayer games. This is Multiplier.

The second point is not entirely true, as activating a Shrine of Enlightenment will increase this value by 0.25.
The second item is Bonus Experience per Kill. This is a value that is added to Base XP before any kind of multiplication occurs.
The last is Pool of Reflection, which were added in patch 2.0.1. Basically, a Pool of Reflection increases any and all experience earned by 25, or times 1.25. This includes not only XP from a kill, but also XP from bounties, quests or Rifts.
Basically, this value in the formula is 1 if you are not under the effects of a Pool of Reflection, and it's 1.25 if you are under the effects of the Pool.
With the Flawless Royal endgame gems, you can have +41% XP on your helmet, or 82% with a well-rolled Leoric's Crown. Note, that the percentage you can get from gear (Ruby in Helm, Level 70 Hellfire Ring, etc.) is additive with the percentages you get from difficulty.
With the recently added Gem of Ease, you get at least 500 bonus XP per kill and per rank you'll get an another extra 50 XP on top of that. This is additive with the +XP from kill secondary affixes.
Grabbing the above formula, a level 50 Gem of Ease, 3380 bonus XP per kill, a Pool of Reflection and Torment VI, a Risen will yield 597762 XP, as opposed to 369750 XP on just Torment VI alone without any of the modifiers and 462187 with a Pool of Reflection. So in here, the +XP per kill grants you 135575 extra XP, but at the cost of DPS from the Emerald in your weapon and probably some more useful secondary affixes.

A:

In general, from about Normal difficulty Act 2 onwards, a +10% or higher bonus (from putting a Ruby into a socketed helmet) is going to beat the pants off of any +XP bonuses you can find.
The +XP bonus enchant tends to max out around +15 XP, which would mean it would beat a +10% XP enchant if monsters were worth less than 150 XP per kill.  About midway through Act 2, I sampled some of the monsters XP values as I was killing them, by monitoring my current XP to level before and after encounters.  Routinely, the average per-kill was more than 200 XP.  As you progress through the game, the amount of XP per-kill will increase, and easily dwarf the small bonuses you can get from +XP gear.
This doesn't mean that you should not use +XP enchants on other equipment - but especially later in the game, it becomes less and less worth the investment.  Almost always,  if you have a choice between a socketed helm with a good quality ruby, or a non-socketed helm with a +XP enchant, take the helm with the ruby.
Bear in mind that the XP you gain from monsters also depends on your level versus the level of the monsters, and information about monster levels is not readily available in-game.  Thus, the only real way you can say how much the monsters you are fighting are contributing to your XP is to hover over your XP bar before and after killing them, and then do the math based on these values.