Q:

python3, ftplib storlines error

I want to upload an ASCII file. This used to work in Python 2:
ftp = ftplib.FTP('ftp.domain.com')
ftp.login('domain.com',password)
ftp.cwd('subdirectory')
ftp.storlines('STOR ' + 'file.htm', open('file.htm','r'))
ftp.close()

However, in Python 3 it returns this error:
  File "/usr/local/lib/python3.3/ftplib.py", line 497, in storlines
    if buf[-1] in B_CRLF: buf = buf[:-1]
TypeError: Type str doesn't support the buffer API

What am I doing wrong?

A:

I read the documentation:
http://docs.python.org/3/library/ftplib.html#ftplib.FTP.storlines
"Lines are read until EOF from the file object file (opened in binary mode) using its readline() method to provide the data to be stored."
So I just had to open in binary mode:
ftp.storlines('STOR ' + 'file.htm', open('file.htm','rb'))


Q:

HTML List with changing options based on variable?

so this is my first thingy here so apologies if I don't get my question across quite correctly.
So I have a webpage, built on bootstrap, but I want one of the options in my navigation bar to change, based on whether or not the user is logged in.
This is what I've managed to come up with, but it just causes a constant loop of neverending redirects:

Home

****

****

Contact

<?php
if(!empty($_SESSION['user']))
{echo 'Account)';}
else{echo 'Log In)';}
?>

I'm wondering if it's because I call Common again later maybe? Although tbh I probably just have no idea what I am doing :|
Thanks for any help you can provide.

A:

I have solved the problem, thank you for your help :)
Turned out I'd put a (!empty) instead of an (empty) so it would cause a constant loop back and forth between the two pages I was testing this idea with.
Thanks for your help and my apologies.


Q:

record not found on contain model in CakePHP 3

I am using CakePHP 3.4
I am retrieving information of user like
$user = $this->Users->get($id, [
    'contain' => [
        'UserAddresses.States.Countries' => ['conditions' => [
               'UserAddresses.deleted' => false]],
    ],
]);

Here, UserAddresses have user_id column and state_id column and States table have country_id column.
If there is no associated user_address in table, then I gives
record not found error
while removing States.Countries from contain works fine even when record does not exists in UserAddresses

Edit 2 : Relationships

UsersTable.php
$this->hasOne('UserAddresses', [
    'foreignKey' => 'user_id'
]);

UserAddressesTable.php
$this->belongsTo('Users', [
    'foreignKey' => 'user_id',
    'joinType' => 'INNER'
]);
$this->belongsTo('States', [
    'foreignKey' => 'state_id',
    'joinType' => 'INNER'
]);

StatesTable.php
$this->belongsTo('Countries', [
    'foreignKey' => 'country_id',
    'joinType' => 'INNER'
]);
$this->hasMany('UserAddresses', [
    'foreignKey' => 'state_id'
]);

CountriesTable.php
$this->hasMany('States', [
    'foreignKey' => 'country_id'
]);

A:

As Kilian Schuster said, your condition is being applied to Countries. I changed it, try the code bellow:
$user = $this->Users->get($id, [
    'contain' => [
        'UserAddresses' => [
            'conditions' => [
               'UserAddresses.deleted' => false
            ]
        ],
        'UserAddresses.States.Countries'
    ]
]);

Edit: The record not found error could be caused by the Inner join type for Countries in States model if there is no address related to the got user. Change the join type to Left if the relationship is optional.


Q:

When using "tel:" tag, Gives "A potentially dangerous Request.Path value was detected from the client (:). " Error

I keep running into this error in my ELMAH logs. The error states,
System.Web.HttpException (0x80004005): A potentially dangerous Request.Path value was detected from the client (:).

After looking at the stacktrace in the log it appears the error is happening because I am using a
8888888888888 tag.
Is this not a valid HTML5 implementation for a telephone number? How would I be able to fix this?
And what about for "whatsapp:" tags? (see related post)

A:

It looks like you have a dumb browser which is asking the server for a tel: URI when the anchor is clicked. A tel: URI should cause the client machine to dial a local telephone device, and the server is properly warning that the URI was instead requested of the server. It may be that this was a historic attack vector.
So, at one level, it is probably an ignorable error.
It could also be that the browser is trying to be "smart" because the telephone number is not properly specified. According to RFC 3966 the telephone number needs to be a valid E.164 address or a properly formed "local address" and 888-888-8888 is neither. If you are referring to a North American phone then the address is properly +1-888-888-8888 (dashes are optional, the plus sign is not and 1 is the country-code). If you are trying to denote a local address, may Turing help you understanding the specification; note, the RFC says local address SHOULD NOT be used.
If the smart/stupid browser passes back the URI to the server as a novel request if it cannot parse it, it is being too smart/stupid and should just ignore it.
So, at another level, perhaps you should put a +<country code> in your href. If one browser is broken in this way, another will be. It would be a good idea to walk back in the log to see if the page with the malformed URI is being requested by the same requestor shortly before the tel: request comes back in to the server. It would also be good if you can get the UserAgent for the requestor. It would be good to see if this is an attempt to penetrate old servers or an innocent action by an end-user with IE 5 or sumptin.


Q:

String Search with error "Unexpected End of Regular Expression"

I want to search string a in string b = "sed s/xxx/[/"
Code:
a = "data sed s/xxx/[/"
b = r'\ssed s/xxx/[/\b'
re.findall(b,a)

Output Error
unexpected end of regular expression.

A:

The character [ is a regular-expression metacharacter. In order to match it literally, you need to escape it.
r'\ssed s/xxx/\[/'   # backslash-escape it, or
r'\ssed s/xxx/[[]/'  # put it in a character class

The second example also shows what the metacharacter is actually used for.  In regular expressions, [abc] matches a single character out of the enumeration (so either a or b or c); this is called a character class.


Q:

Trying to get my slider to be responsive. Keeps adding a margin to offset between @media queries

http://jsfiddle.net/2RE3f/6/embedded/result/
I'm trying to make a responsive js slider and I can't seem to figure out the break point glitch when going between media queries.
For instance, if you look at my jsFiddle, and set your window to the iPad size (1024px wide for screen size), and then pull out to 1200px wide, the slider breaks and there's a margin being applied to the new grid size (highlighted in red), off-setting the slider. However, if you pull back to the iPad size, then it then slider doesn't apply a margin to the right off-setting it and works normally. If load up the grid at the 1200px width, the slider works normal, but it when you size down to the iPad size, it adds a margin to the right when you hit the right arrow.
For some reason, I can't figure out how and why its adding this padded margin to the grid.
You'll have to use arrow keys (right left, to navigate between two grid galleries). There's more code in the jsFiddle but it doesn't apply to the rwd.
This is the css
@media screen (max-width: 1400px) {
#portfolio img {
    height: 400px;
    width: 400px;
}
#slider ul li {
    width: 1200px;
}
}

@media screen and (max-width: 1030px) {
.uni_con {
    width: 1024px
}
.shell {
    width: 1024px;
}
.container {
    width: 1024px;
}
#portfolio img {
    height: 512px;
    width: 512px;
}
#slider ul li {
    width: 1024px;
}
#slider .caption {
    width: 512px;
    height: 512px;
}
#slider .caption::before {
    width: 514px;
    height: 514px;
    line-height: 508px;
}
#slider .caption::after {
    width: 512px;
}
#slider .caption:hover::before {
    width: 512px;
    height: 512px;
}
#slider .caption:hover::after {
    width: 512px;
}
}

The Jquery
jQuery(function ($) {

var $sl = $('#slider'),
    $ul = $('ul', $sl),
    $li = $('li', $ul),
    slideCount = $li.length,
    c = 0, // current
    slideWidth = $li.width(),
    slideHeight = $li.height(),
    sliderUlWidth = slideCount * slideWidth;

$sl.css({
    width: slideWidth,
    height: slideHeight
});
$ul.css({
    width: sliderUlWidth
});

function move() {
    if (c == slideCount) {
        c = slideCount - 1;
        // fade out #next btn
        $('#next').stop().fadeTo(200, 0.5);
    }
    if (c == slideCount - 1) {
        $('#next').stop().fadeTo(200, 0.5);
        $('#back').fadeTo(200, 1);
    } else if (c < 0) {
        c = 0;
        $('#back').stop().fadeTo(200, 0.5);
    } else {
        $('#next').fadeTo(200, 1);
        $('#back').fadeTo(200, 0.5);
    }
    $ul.stop().animate({
        left: -c * slideWidth
    }, 500);
}

$('#back, #next').click(function () {
    return move(this.id == 'next' ? c++ : c--);
});

$(document).keydown(function (e) {
    var k = e.which;
    if (k == 39 || k == 37) {
        e.preventDefault();
        return move(k == 39 ? c++ : c--);
    }
});

});

On the second LI (using right key), this margin keeps getting added and pushing the grid off from being inline with the container.
Thanks.

A:

seems to be I have found the solution. The reason you were seeing that strange red margin at the right side was that you were controlling the width and height of the slider ul element using your javascript code. On window resize or a change in screen resolution, the media queries were changing other elements sizes, but this (ul sider width and height) remained the same.
I added the code to handle this problem, with comments, here is the jSFiddle:
http://jsfiddle.net/2RE3f/12/embedded/result/
And here is the updated JS Code:
    $(document).ready(function(e) {

jQuery(function ($) {

var $sl = $('#slider'),
    $ul = $('ul', $sl),
    $li = $('li', $ul),
    slideCount = $li.length,
    c = 0; // current

var slideWidth; // global so can be used in move()

// wrap the slider width and height settings in a function
function slider_fit()
{
    slideWidth = $li.width(),
    slideHeight = $li.height(),
    sliderUlWidth = slideCount * slideWidth;

    $ul.css({
        width: sliderUlWidth
    });
    $sl.css({
       width: slideWidth,
       height: slideHeight
    });
}

slider_fit(); // call slider_fit on window load also

// below is the function to make sure window resizing has been done
$(window).resize(function() {
    if(this.resizeTO) clearTimeout(this.resizeTO);
    this.resizeTO = setTimeout(function() {
        $(this).trigger('resizeEnd');
    }, 250);
});

// once window is resized and media queries (if any) have been applied
// we can fit our slider elements to this new size
$(window).bind('resizeEnd', function() {
    slider_fit(); // fit slider widths and heights due to screen size change
    move(); // make adjustments to the left margins of ul
});

function move() {

    //alert(slideWidth);

    if (c == slideCount) {
        c = slideCount - 1;
        // fade out #next btn
        $('#next').stop().fadeTo(200, 0.5);
    }
    if (c == slideCount - 1) {
        $('#next').stop().fadeTo(200, 0.5);
        $('#back').fadeTo(200, 1);
    } else if (c < 0) {
        c = 0;
        $('#back').stop().fadeTo(200, 0.5);
    } else {
        $('#next').fadeTo(200, 1);
        $('#back').fadeTo(200, 0.5);
    }
    $ul.stop().animate({
        left: -c * slideWidth
    }, 500);
}

$('#back, #next').click(function () {
    return move(this.id == 'next' ? c++ : c--);
});

$(document).keydown(function (e) {
    var k = e.which;
    if (k == 39 || k == 37) {
        e.preventDefault();
        return move(k == 39 ? c++ : c--);
    }
});

});
});

I hope this helps :)


Q:

ControlSend to send key input to Notepad window

 ControlSend, Notepad, {b down}{b up}, Untitled - Notepad

I want to send b key input to Notepad window (so that b key would be pressed, when Notepad's window is not active).
No error, no feedback, nothing happens. I found out Notepad's class by using Window Explorer program and the title is the default unsaved document's. What am I doing wrong here? I was trying to find something working that would help solve this problem, but there isn't so much information.

A:

You are confusing Class and ClassNN.
ControlSend requires ClassNN as the second parameter
Notepads default ClassNN is Edit1.
ControlSend, Edit1, {b down}{b up}, Untitled - Notepad


Q:

Two foreign keys referring to one primary key

I'd to create a database that records transactions between two users. A user can transfer points (think of it as money) to another user. user table looks like:
| userID        |    name       |      email       |   balance  |
| ------------- |---------------|------------------|------------|
| 101           | alpha         | alpha@mail.com   |   1000     |
| 102           | bravo         | bravo@mail.com   |    500     |
| 103           | charlie       | charlie@mail.com |   2000     |

And the transaction table should look like:
| transactionID |  from_user    |   to_user        | transfer_amount  |
| ------------- |---------------|------------------|------------------|
|   1           | 101           |       103        |   100            |
|   2           | 102           |       101        |   150            |
|   3           | 102           |       103        |   200            |

I tried to draw a schema with Vertableo which doesn't seem have one to zero or many relationship option. But a user might not send or receive points at all, so the relationship should be one to zero or many. However, this schema on Vertableo throws the error reference name must be unique.

Could someone give hints to draw a schema or provide SQL code?

A:

Example SQL code (create with MySQL Workbench):
CREATE TABLE `test`.`user` (
  `iduser` INT NOT NULL,
  `username` VARCHAR(45) NULL,
  PRIMARY KEY (`iduser`));

CREATE TABLE `test`.`transfer` (
  `transactionID` INT NOT NULL,
  `from_user` INT NULL,
  `to_user` INT NULL,
  `transfer_amount` FLOAT NULL,
  PRIMARY KEY (`transactionID`),
  INDEX `from_user_key_idx` (`from_user` ASC),
  INDEX `to_user_key_idx` (`to_user` ASC),
  CONSTRAINT `from_user_key`
    FOREIGN KEY (`from_user`)
    REFERENCES `test`.`user` (`iduser`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `to_user_key`
    FOREIGN KEY (`to_user`)
    REFERENCES `test`.`user` (`iduser`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);

This works. However if you want to query the 'transfer'-table and want to substitute the IDs for usernames it gets a bit more complicated. Heres an example query:
select a.username as from_user, b.username as to_user, transfer_amount
from transfer
inner join user a
on transfer.from_user = a.iduser
inner join user b
on transfer.to_user = b.iduser;


Q:

Custom layout for sliding menu

I want to group items in my custom sliding menu
like facebook menu items
Can somebody share some pointers/insights?

A:

Possible duplicate of List View with groups in android and group similar rows in listview based on their content
You can have a look here : http://blogingtutorials.blogspot.be/2010/11/android-listview-header-two-or-more-in.html


Q:

Creating asset folder using Google Earth Engine Python API

I am trying to create an asset folder using
ee.data.createFolder()

But I get the error:

AttributeError: module 'ee.data' has no attribute 'createFolder'

How do I create a folder using the python api?

A:

You have to use the ee.data.createAsset() method, like so:
import ee
ee.Initialize()
ee.data.createAsset({'type': 'ImageCollection'}, 'users/[your-username]/test-folder')

Note that the type is different whether you're using the Cloud API or not. From the docs:

Creates an asset from a JSON value.
To create an empty image collection or folder, pass in a "value"
  object   with a "type" key whose value is "ImageCollection" or
  "Folder".   If you are using the Cloud API, use "IMAGE_COLLECTION" or
  "FOLDER".
Args:
      value: An object describing the asset to create or a JSON string
          with the already-serialized value for the new asset.
      opt_path: An optional desired ID, including full path.
      opt_properties: The keys and values of the properties to set
          on the created asset.
Returns:
      A description of the saved asset, including a generated ID.


Q:

Shiny: how to input a list of text strings that are delimited with double-quotes (")

I am running into a problem with text inputs. The default seems to be that the textInput() function outputs the text with "" around it. I am trying to feed multiple words into textInput(), with a "" around each word. For example:
instead of outputting test1,test2,test3 as: "test1,test2,test3",
I want "test1","test2","test3"
I tried using a combination of cat() and paste() with \ to workaround it, but it does not seem that the renderDatatable() function accepts that.
This is what I have tried so far:
    ui<- fluidPage(
    textInput(inputId = "words",
              label = "Enter search terms, separated by commas",
              value = ""),
    titlePanel("List of Claims"),
    fluidRow(
        dataTableOutput(outputId = "table")
    )

)
server <- function(input,output){

    reactivedata <- reactive({
        input$words
    })

    output$table <- renderDataTable({
        inputtext<-function(x) {paste(eval(parse(text=input$words)))}
        claiminfo2$xxtotal <-rowSums(claiminfo2[,inputtext(X)])
        claiminfo3 <- claiminfo2[,c(1,length(claiminfo2))]
        claiminfo4 <- subset(claiminfo3,claiminfo3[,2] >0)
        claiminfo4
    })

}

shinyApp(ui = ui, server = server)

claiminfo2 is a document term matrix with words as column headings. I am trying to have it so that the user inputs words, and then the app searches for those columns by claiminfo2[,c(words)]. However, instead of getting
claiminfo2[,c("word1","word2")], I am getting
claiminfo2[,c("word1 , word2")] which won't work

A:

You can maybe use strsplit in your server.R to create the vector of words to use for subsetting your dataframe. Here is an example (the ui.R is unchanged):
claiminfo2 <- data.frame(a=letters[1:4],b=letters[5:8],d=letters[9:12])
    server <- function(input,output){

            output$table <- renderDataTable({
                    claiminfo2[,unlist(strsplit(input$words,",")),drop=FALSE]

            })

Another options is to use a selectize input, this will give the user suggestions of what columns are in your data frame. Here's an example:
library(shiny)
claiminfo2 <- data.frame(a=letters[1:4],b=letters[5:8],d=letters[9:12])

ui<- fluidPage(
        titlePanel("List of Claims"),
        fluidRow(
                dataTableOutput(outputId = "table")
        ),
        selectInput(inputId = "words",
                       label = "Enter search terms, separated by commas",
                       choices=colnames(claiminfo2), multiple=TRUE, selectize=TRUE)

)
server <- function(input,output){

        output$table <- renderDataTable({
                if(!is.null(input$words)){
                claiminfo2[,unlist(strsplit(input$words,",")),drop=FALSE]
                }

        })

}

shinyApp(ui = ui, server = server)


Q:

Can't insert records from one table to another table in other database

I have an SQL Azure Database Server with 2 databases and I need to insert records from a table of the first database to another table in the other database. Both databases are on the same server with the same security settings/login.
I have tried:
INSERT INTO DatabaseB.dbo.TableB (ColumnA, ColumnB)
SELECT TableA.ColumnA, TableA.ColumnB
FROM DatabaseA.dbo.TableA

When I run the SQL with SSMS I get:
Msg 40515, Level 15, State 1, Line 16
Reference to database and/or server name in 'DatabaseB.dbo.TableB ' is not supported in this version of SQL Server.

A:

Cross-database queries such as the one you're trying to do aren't supported with SQL Database, except for read-only elastic queries. You'd need to execute two separate operations.
Specifics a round T-SQL differences between SQL Server and SQL Database are here.
Info about elastic queries: here.


Q:

style with CSS select arrow

How could i style up my select box like this:

main trouble is that my arrow - is transparent background, but i need gray background select with selecting features...
i do it like so:
.modal.custom .modal-body.full-width .styled-select{
    width: 440px;
    -webkit-appearance: none;
}

.modal.custom .modal-body.full-width .styled-select select{
  width: 480px;
  overflow: hidden;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  background: url(../images/png/v.png) no-repeat center right #eeeeee;
}

but seems that something is bad...
it look like so:

and fiddle example:
http://jsfiddle.net/3sebzwxu/
is it real to do as on first image, so that it would be clickable?

A:

you just need to specify position of the background using percentages as follows
css:
background: url(https://dl.dropboxusercontent.com/u/59666091/v.png) no-repeat 99% 50% #eeeeee;

What this means is the backround position is at 99%of the box's width (so it doesn't stick to the edge) and 50% of it's height (so it's always centered vertically)
Here is a JSfiddle demo : http://jsfiddle.net/3sebzwxu/1/
Hope this helps


Q:

Adding Widget to Wordpress Admin Post/Page Edit Sidebar

I'm trying to find the proper way to add a custom widget to the sidebar on the post/page editor page, specifically, in the sidebar under the 'Page Attributes' section. I've been searching various keywords and coming up short. The Wordpress codex docs are limited, so I'm having any luck there either.
If there is a hook that can be used, what is it?
Else, the Wordpress functions needed to add the new control.
I'm guessing that the meta boxes are only displayed under the post section, so that wouldn't be the area I'm looking to edit.
Also, would using the Widget class be the wrong thing to do?
I'm developing for version 2.8 or higher.

A:

You should pose that question on https://wordpress.stackexchange.com/
In short: Widgets on the editor pages are not widgets, don't use the frontend widget class for them. They are functions (callbacks) you need to register for the editor pages. You can differ between post and page and in later WP versions between the post type as well.
The function to add the meta box to the editor pages is: add_meta_box


Q:

2D linear interpolation in R

I want to do a bilinear interpolation in R but I cant figure out how to do it with akima interp function because I get a matrix half fill with numbers and half with NA. This is an example of my problem:
x = rep(c(1,2,3,6,9,12)/12,5)
y = seq(2709,3820,length = 30)
z = seq(9.2,16.5,length = 30)

inter_lin = interp(x,y,z,xo = seq(min(x),max(x),length=100),
                   yo = seq(min(y), max(y), length=100), linear=T)

I also tried using the function interp.surface.grid form fields but z has to be a matrix with values for all x and y used which I don't have so it doesn't work.
EDIT
This is the y and z vectors I actually have:
y = c(2931.076,2901.935,2868.635,2804.006,2760.297,2709.114,2983.466,2969.436,2954.808,2928.802,2915.815,2903.867,
      3043.365,3051.140,3057.960,3079.230,3103.015,3127.245,3118.090,3156.223,3194.574,3291.021,3380.687,3472.676,
      3195.631,3260.866,3331.776,3502.477,3658.052,3829.511)

z = c(10.280984,9.733925, 10.176117, 10.644877, 10.950297, 11.737252, 10.442495, 10.170472, 10.590579, 11.153778 ,11.501962,
  12.066833,11.000000, 11.025000, 11.450000, 12.125000, 12.550000, 12.875000, 12.142495, 11.870472, 12.390579, 13.053778,
  13.501962,14.066833,13.005984, 12.458925, 13.051117, 13.694877, 14.150297, 14.937252)

A:

Set linear = FALSE and extrap = TRUE.
x = rep(c(1,2,3,6,9,12)/12,5)
y = seq(2709,3820,length = 30)
z = seq(9.2,16.5,length = 30)

inter_lin = interp(x,y,z,xo = seq(min(x),max(x),length=100),
                   yo = seq(min(y), max(y), length=100), linear=FALSE, extrap = TRUE)

I think the problem is interpolating values on the boundary and this ripples inwards from the edges. By allowing extrapolation – which is not possible with linear interpolation – this issue is avoided.

Edit
If the interpolation domain is restricted to the region where there is data, results are just peachy.
library(akima)
library(spatialkernel)
library(fields)

# Create grid
grd <- expand.grid(x = seq(min(x),max(x),length=100), y = seq(min(y), max(y), length=100))

# Find points in convex hull
mask <- pinpoly(cbind(x, y)[chull(x, y),], as.matrix(grd))

# Crop grid to convex hull
grd <- grd[mask == 2,]

# Interpolate to points in convex hull
res <- interpp(x, y, z, xo = grd$x, yo = grd$y)

# Plot results
quilt.plot(res$x, res$y, res$z)


Q:

Prepared Statement and Bind in lagom framework?

Q1. What is prepared statement?
for eg below:
var userStatmt: PreparedStatement = _

for {
      insert <- cassandraSession.prepare(
        "INSERT INTO usertable(id, name) VALUES(?, ?)")
    } yield {
      userStatmt = insert
      Done
    }

Does prepared statement means that the words are stored because below if not stored how will name in the below will be known
"SELECT * FROM usertable WHERE name = '$name'"

Q2. If so , why bind is used for?
for example :
val userBindStatement: BoundStatement = userStatmt.bind()
userBindStatement.setString("id", user.id)
userBindStatement.setString("name", user.name)

Could you please explain, I have just started lagom and found this in Lagom Readside and I am also new to microservices and also there are limited resources on this topics.

A:

Prepared statements are an optimisation that means the statement doesn't need to be sent to the server and parsed each time it's executed. In order for this to work, any parts of the statement that are dynamic (ie parameters) are replaced with placeholders (ie ?), which then need to be bound to actual values when the statement is executed.
This by the way is nothing specific to Lagom, it's specific to Cassandra (and even then, the same concept is used in many databases, especially relational databases). You can read more about it as it applies to Cassandra here:
https://docs.datastax.com/en/developer/java-driver/3.0/manual/statements/prepared/
And the general concept of prepared statements is described here:
https://en.m.wikipedia.org/wiki/Prepared_statement


Q:

Ignoring `eclipse.refreshLocal` task, which is not available outside of Eclipse

For developers' convenience, all Ant tasks in our codebase feature a eclipse.refreshLocal task which tells Eclipse to automagically refresh the workspace after running the Ant task.
This is because too many people have fallen in the trap of not pressing F5 manually to refresh the file system, so that once we discovered the magic task no one will be surely returning to the olf F5-ing.
But now we are deploying Bamboo. I don't want to build separate scripts for Bamboo. I would like Bamboo to just ignore that eclipse.refreshLocal task because it is not run in the same VM as Eclipse.
Any idea on how to accomplish?

A:

Solved with a trick. I am telling my coworkers to:

Update their Eclipse Ant runtime and set a custom variable INECLIPSE = true from Eclipse Ant options
Add the following to top of all of their build.xmls: xmlns:if="ant:if" xmlns:unless="ant:unless"
Use <eclipse.refreshLocal depth="infinite" resource="/" if:set="INECLIPSE" /> in all Ant tasks
Don't bother Bamboo

Chuck happily said OK to my last build


Q:

Relationship between FEM solutions of PDE with different spatial resolutions

I use FEM to simulate deformations of elastic objects for animation applications in computer graphics. The governing equation is generally with the form:
$$
\mathbf{M}\ddot{\mathbf{u}} +\mathbf{C}\dot{\mathbf{u}}+\mathbf{K}\mathbf{u}=\mathbf{f}
$$
where $\mathbf{M}$ is the mass matrix, $\mathbf{C}$ is the damping matrix, $\mathbf{K}$ is the stiffness matrix, and $\mathbf{u}$ is the displacement to be solved for.
I'm trying to solve this time-dependent equation using FEM with very coarse spatial resolutions, mainly to save computational time. As far as I know, the FEM solution converges to the exact solution as spatial resolution goes to infinity. What I'm trying to figure out is: what is the relationship between FEM solutions using different spatial resolutions besides that they converge to the same exact solution?
What I'm hoping to achieve is to get coarse solution as the downsampling of fine solution, since fine solution is closer to exact solution. Is this even possible?

A:

It doesn't generally work this way. You want to compare $u_H$ and $u_h$ computed on coarse and fine meshes $T_H$ and $T_h$. It is generally not true that $u_H=I_H u_h$ where $I_H$ is the interpolation to the coarse mesh. Nor is it generally true that $u_H=P_H u_h$ for some projection operator (though that is indeed the case for elliptic problems if you could integrate coefficients exactly), but even if it were, it would not yield an easily understandable relationship. In general, you don't even know that $u_h$ is more accurate than $u_H$ (in the sense that $\|u-u_h\| < \|u-u_H\|$) on coarse meshes, as convergence only exists in the limit and not for a particular choice of $h,H$.
So, in essence, there is not very much you can say about the solutions on different meshes.


Q:

Strange crash when starting notification

Please don't mark this as a duplicate of some generic null pointer exception question, as you can see, the exception isn't directly in my code, it is deep within the Android notification classes.
I've never actually reproduced this myself, I only get it on Crashlytics. Happens on Android 7 and 8 across several manufacturers. It seems similar to Android.app.Notification.extras null but there is no answer there and their stacktrace is slightly different. Here is the exception:
 java.lang.NullPointerException: Attempt to read from field 'android.os.Bundle android.app.Notification.extras' on a null object reference
           at android.app.Notification.addFieldsFromContext(Notification.java:2439)
           at android.app.Notification.addFieldsFromContext(Notification.java:2432)
           at android.app.NotificationManager.notifyAsUser(NotificationManager.java:300)
           at android.app.NotificationManager.notify(NotificationManager.java:289)
           at android.app.NotificationManager.notify(NotificationManager.java:273)
           at mypackageMyService.notify(MyService.java:812)
           at mypackageMyService.createNotificationAfterCheckOfStatus(MyService.java:1040)
           at mypackageMyService.onStartCommand(MyService.java:173)
           at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3474)
           at android.app.ActivityThread.-wrap20(Unknown Source)
           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1692)
           at android.os.Handler.dispatchMessage(Handler.java:106)
           at android.os.Looper.loop(Looper.java:164)
           at android.app.ActivityThread.main(ActivityThread.java:6494)
           at java.lang.reflect.Method.invoke(Method.java)
           at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

And here is my code:
Intent intent = new Intent(this, SomeClass.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, PENDING_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_stat_notification_icon)
                .setOngoing(true)
                .setAutoCancel(false)
                .setContentIntent(pendingIntent)
                .setPriority(NotificationCompat.PRIORITY_LOW);
builder.setContentText(getString(R.string.please_wait));
if (oreoOrHigher) {
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationChannel notificationChannel = notificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_ID);
            if (notificationChannel == null) {

      /* Create or update. */
                CharSequence channelName = getString(R.string.my_channel_label);
                int importance = NotificationManager.IMPORTANCE_LOW;
                notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, importance);
                notificationChannel.enableLights(false);
                notificationChannel.enableVibration(false);
                notificationManager.createNotificationChannel(notificationChannel);
            }
            builder.setChannelId(NOTIFICATION_CHANNEL_ID);
}
builder.setOngoing(false);
//fake extra to see if it fixes null pointer
Bundle fakeExtra = new Bundle();
fakeExtra.putString("test", "test");
builder.addExtras(fakeExtra);
Notification notification = builder.build();
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notification);
startForeground(NOTIFICATION_ID, notification);

I even tried adding a fake extra bundle and that didn't help.
What am I doing wrong?
Thanks.
Edit: It has been pointed out that builder.build() is probably returning null. I still haven't been able to reproduce that but it would make a bit of sense given the message of the exception. I just don't know why the build() method would fail to create a notification object.

A:

Try to replace this with getApplicationContext() when creating a notification:
NotificationCompat.Builder builder = NotificationCompat.Builder(getApplicationContext(), NOTIFICATION_CHANNEL_ID)

Your notification is not null, as you can see in stacktrace you have successful calls to the notification instance. But the exception is in Notification.addFieldsFromContext, so looks like Bundle of Context is null.


Q:

How do you build a query to get a series of nodes and their field values filtered by field values?

Hopefully someone with Drupal 7 experience can point me in the right direction.
I'm creating a custom module to query some nodes and group and sort them by their field values.
I tried to use Views but it seems that it's not possible to get the results in the format I need so I've decide to query the database directly and build my own output.
What's the easiest way to query nodes in Drupal 7 as I notice there is a table for every field now which would seem to make any query that I have to write extremely complex?
Are there any methods to query node data and filter/group the results or can it only be done using raw SQL.
If the latter can you show me an example query that includes Drupal 7 Field values?

A:

I second Jeremy's suggestion of trying harder with views. However, if you absolutely must write your query directly in code, you'll want to use EntityFieldQuery.
For example, to get a count of all nodes with a text field value of 'foo':
// Get field information
$field = field_info_field('field_name');
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'NODE TYPE')
  ->fieldCondition($field, 'value', 'foo')
  ->count();

$count = $query->execute();

If you don't want a count, but results instead, you would leave off the count part, and fetch results:
foreach ($query->execute() as $entity_type => $entities) {
  foreach ($entities as $entity_id => $entity) {
  ...
  }
}

The Commerce Guys also have a good blog post detailing a simple use case.


Q:

Qt, use of "&" in tr

I'm going through the Qt5 Application tutorial. In the creation of actions, I keep seeing the usage of "&" like the follwoing:
newAct = new QAction(QIcon(":/images/new.png"), tr("&New"), this)
...
openAct = new QAction(QIcon(":/images/open.png"), tr("&Open..."), this);
...
enter code exitAct = new QAction(tr("E&xit"), this);
...

I can't seem to find why these "&" are used, the Qt documentations on tr uses these notations without explaining what they are for. Further, when I deleted the "&" symbol, the resulting application doesn't seem to change at all.

A:

As far as tr is concerned & is just another character in the string and has no special meaning.
However it does have a special meaning to QAction: It sets the following character as the entry's shortcut within a menu, so when you have the "File" menu open, pressing the n key will activate the "New" entry, x will active "Exit" and so on. Depending on the OS, the character after the & may also be underlined (on Windows it's only underlined when you press the Alt key).

A:

& is used to indicate a character that should be used for the Alt-key shortcut for a given menu item. Assuming these actions are being put into a menu named &File, pressing Alt-F, then N would activate the New action.


Q:

MVC 5 Select list - user input

I am using the following to generate a dropdownlist of provinces based on the country selection:
  <select id="Province" name="Province"  class="form-control  input-sm">
    @{
       string[] provinces = ViewBag.ProvincesForSelectedCountry;
       string selectedProvinceName = null;
     }
    @{
       if (Model != null && !String.IsNullOrEmpty(Model.Province))
       {
          selectedProvinceName = Model.Province;
       }
       else
       {
          selectedProvinceName = ConfigData.DefaultProvinceName;
       }
     }
    @foreach (var anEntry in provinces)
    {
       string selectedTextMark = anEntry == selectedProvinceName
          ? "selected=\"selected\""
          : String.Empty;
       <option value="@(anEntry)" @(selectedTextMark)>@(anEntry)</option>
    }
  </select>

The challenge is I don't have a list of provinces (states) for other countries! Is there a way to allow for the user to type in the name of the province? Like a combobox.

A:

I had to do it using Knockout-Kendo combobox, here is the solution:
Controller:
   public ActionResult Index()
        {
            ViewBag.CountryID = new SelectList(db.Countries, "ID", "Name", "34");
.....

   public JsonResult GetState(int? id)
        {
            if (id == null)
            {   id = 34;  }
            var data =   db.States.Where(x => x.CountryID == id)
                    .Select( x =>
                            new
                            {
                                ID = x.ID,
                                Name = x.Name
                            }).ToList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

In the View:
@Html.DropDownList("Country", ViewBag.CountryID as SelectList, "Select...",
 new { onchange = "UpdateProvinces();" })
<input data-bind="kendoComboBox: { dataTextField: 'Name', dataValueField: 'ID',
 data: choices, value: selectedChoice }" />

Here is the JavaScript:
function UpdateProvinces() {
        var countryId = $("#Country  option:selected").val();
        $.getJSON("/Home/GetState/" + countryId,
            null,
            function (data) {
                objVM.choices(data);
            });
    }
    function ItemViewModel(arg) {
        arg = 34;
        var self = this;
        this.choices = ko.observableArray([]),
            $.ajax({
                type: "GET",
                url: '@Url.Action("GetState", "Home")',
                contentType: "application/json; charset=utf-8",
                data: { id: arg },
                dataType: "json",
                success: function (data) {
                    self.choices(data);
                },
                error: function (err) {
                    alert(err.status + " : " + err.statusText);
                }
            });
        var selectedChoice = {
            ID: self.ID,
            Name: self.Name
        };
        self.selectedChoice = ko.observable();
    }
    var objVM = new ItemViewModel();
    ko.applyBindings(objVM);

Edit:
Another alternative is to use Telerik MVC UI Combobox http://demos.telerik.com/aspnet-mvc/combobox/cascadingcombobox


Q:

Server side timer after meteor collection is updated

I'm currently developping a simple realtime multiplayer game and i'm stuck with the timer logic.
When there are enough players in a game, the status of the game is set to "STARTED" and from there i want to start a 10 seconds timer and show it to all the clients.
My idea is to use collection hooks and call a setTimeout after the collection update. But I don't really know how to do it and if it is the best solution.
Also maybe should I use cron instead of timers?

A:

I would use the following logic :

before.update hook on your collection to update the status to Started using collection hooks
set a datetime in the hook for the date when players were enough => save this data in your Game Collection
Game.before.update(function (userId, doc, fieldNames, modifier, options) {
    if (modifier && modifier.$set && modifier.$set.nb_of_players > 10) {
        modifier.$set.status = "Started";
        modifier.$set.startingTime = new Date();
    }
});

use a helper to compute dynamically the time to show on your client, here a basic working example of reactive time display, that you need to improve to get a countdown:
Template.Home.helpers({
    time: function () {
        return Template.instance().date.get();
    },
});

Template.Home.onCreated(function () {
    var self = Template.instance();
    self.date = new ReactiveVar();
    Meteor.setInterval(function () {
        self.date.set(new Date());
    }, 1);

});

use a setTimeout to actually do something 10 seconds later - this should be called after setting the game to started. Either in an autorun checking the value, or in the callback function of the Meteor.call you use :
Meteor.setTimeout(function(){
    Meteor.call("launchAction", {data:data}, function (error, result) {
        if (error){
            console.error(error);
        } else {

        }
    });
}, 10);

I also recommend using momentjs to actually manipulate dates and times


Q:

NSError not being populated

Several times before I used the method...
NSURLResponse *response;
NSError *error;

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

to send/receive data synchronously when in an NSOperation and it has worked.
I'm working on a new project (new API, new server) now and the error just isn't being populated.
I'm using Charles proxy to snoop the network traffic and I can see "Response Code 500 Internal Server Error" coming back from the failed request in Charles but in the app the error object is always nil.
Like I said, I've used this loads before and the error is always populated if an error occurs.
Is there something on the server side that I can point out to the server side dev? He's adamant that I must be doing something wrong. The only thing I don't understand is that Charles is picking up response code 500 from it.
N.B. The problem is not that the error is occurring. The problem is that when it does occur the NSError object is not reporting it back to me. Just to clear it up in case anyone tells me to ask the server dev to fix the error. :-)

A:

Your error object is not populated because the request succeeded from NSURLConnection's perspective -- that is, it was able to send data to the server and receive a response.
For protocol-specific errors, you need to inspect the NSURLResponse you get back. In this case, cast the response to NSHTTPURLResponse and invoke -statusCode.


Q:

solve (limit) integral expression into numerical values in Matlab

My expression (after final evaluation) turned out to be a very complicated integral expression. It involves inverse of a function, within function.
I am using symbolic function to solve this. Unfortunately i could not get the answer in terms of expression that I need. Can someone guide me with that ?
Following is my code;
    dn=2;
    pfa = .1;
    dref = 1;

    syms x z
    lo_x_lim = erfinv(pfa-1)*sqrt(2);
    hi_x_lim = inf;

    lo_z_lim = 0
    hi_z_lim = dn

    %% Expression

    Q(x,z) = .5 +.5*erf(x/sqrt(2))
    Qinv_ = erfinv(Q - pfa/2) %Note that this need to be changed
    f_step_2 = (Qinv_ - x)/(1-z/dref)
    f_step_3 = Q(f_step_2,0)

    g(x,z) = 2*z/dn^2
    h(x,z) = exp(-x^2/2)

    %combining three equations to form one
    fin = f_step_3*g*h

    % Doing double integral wrt x and z in two steps
    %integrate wrt x
    int_x = int(fin,x,-0.2,hi_x_lim)

    %integrate wrt z

    int_z = int(int_x,z,lo_z_lim,hi_z_lim)

Following is the final answer that I am getting. (Note that I need it in terms floating-point format)
int_z =

int(int((z*exp(-x^2/2)*(erf((2^(1/2)*(x - erfinv(erf((2^(1/2)*x)/2)/2 + 9/20)))/(2*(z - 1)))/2 + 1/2))/2, x, -.2, Inf), z, 0, 2)

A:

Symbolic computations typically strive to maintain as exact an answer as possible.  For a definite integral, this means the engine needs to find the anti-derivative of the integrand and then evaluate it at the integration bounds.  If it cannot find the anti-derivative, the engine may throw an error/warning or, in the case of the Matlab Symbolic Toolbox and some other engines,  "it just returns int(f)".  However, you can force int to return a numerical approximation to the definite integral using double.  Changing the final line to
int_z = double(int(int_x,z,lo_z_lim,hi_z_lim));

will produce a numerical approximation.  However, due to the complexities of the integrand, it takes a fairly long time.  As I repeatedly like to soapbox about, if you're in search of a number, you probably want to use numbers at the end.  Consider the direct numerical approximation using integral2:
fin_num   = matlabFunction(fin,'Vars',[x,z]);
int_z_num = integral2(fin_num,-0.2,hi_x_lim,lo_z_lim,hi_z_lim);

Running the modified code outputs
int_z =
    0.6957
Elapsed time is 841.910756 seconds.
int_z_num =
    0.6957
Elapsed time is 0.219571 seconds.


Q:

Function $\mathbb{R}\to\mathbb{R}$ that is continuous and bounded, but not uniformly continuous

I found an example of a function $f: \mathbb{R}\to\mathbb{R}$ that is continuous and bounded, but is not uniformly continuous. It is $\sin(x^2)$. I think it's not uniformly continuous because the derivative is bigger and bigger as $x$ increases. But I don't know how to prove this is uniformly continuous. Is $\sin(x^2)$ uniformly continuous then? if it isn't, can you guys think of any other examples? thanks

A:

To prove that $f(x)=\sin(x^2)$ is not uniformly continuous, let $\epsilon=\frac{1}{2}$. You want to show that for every $\delta\gt 0$ there exists $x$ and $y$ (which may depend on $\delta$) such that $|x-y|\lt \delta$, but $|f(x)-f(y)|\geq \frac{1}{2}$. Suggestion: try to pick a $y$ where $f(y)=0$, and a very nearby $x$ where $f(1)=\pm 1$. You want $y^2=n\pi$ for some integer $n$, and $x^2$ to be $\frac{1}{2}\pi$ away.  If you cannot produce a pair explicitly, maybe you can show that you can pick them as close as you want anyway, provided $x$ and $y$ are large enough (which agrees with your observation that the derivative is unbounded).


Q:

How do you swap the caps lock key  to control key in lxde?

I know it is easy to this in Gnome, but how can I do it in LXDE?

A:

If you are the only person using the machine then the easiest option is to include the following line in the keyboard section of your XF86Config-4 file.
  Option          "XkbOptions"    "ctrl:swapcaps"

These ensures that the swap is done automatically whenever X starts.
(Reference: http://www.manicai.net/comp/swap-caps-ctrl.html)


Q:

Angular2 - serious issues with checkboxes

First of all I'm just really disappointed how undocumented is the whole checkbox section. This is causing me some serious issues. I'd like to provide an array of strings that user can click and the selected strings get stored to a property. If then user decides to EDIT the current item, he can uncheck and check some other values and updates the values in the array. Sounds simple? It's a nightmare.
This is what I've come up with: https://plnkr.co/edit/FECAKFDRyMn8CyV4SpqD?p=preview
The steps are as follows: write a new name, select English and German and press "Add new". Then select "James" and uncheck "English" and press "Update" and you'll see that all languages have been removed. I have no idea if I'm even approaching correctly to this issue of checkboxes, there just isn't any documentation.
Code:
    import { Component } from '@angular/core';

const LANG: any[] = [
  {label: 'English'},
  {label: 'German'},
  {label: 'Italian'}
]

class Person {
  constructor(public name:string; public speaking: string[]) {}
}

@Component({
  selector: 'app-root',
  templateUrl: './src/app/app.component.html',
  styleUrls: ['./src/app/app.component.css']
})
export class AppComponent {
  title = 'app works!';
  people: Person[];
  person: Person = new Person('', []);
  languages: string[] = LANG;

  constructor() {
    let person1 = new Person('James', [Object.assign({}, LANG[0]), Object.assign({}, LANG[2])]);
    let person2 = new Person('Frank', [Object.assign({}, LANG[1]));
    this.people = [person1, person2];
  }

  AddNew(): void {
    this.person.speaking = this.languages.filter(x => x.selected === true);
    this.people.push(this.person);
    this.person = new Person('', []);
  }

  Reset(): void {
    this.person = new Person('', []);
  }

  Update(): void {
    this.person.speaking = this.languages.filter(x => x.selected === true);
  }

  Edit(name: string): void {
    this.person = this.people.find(x => x.name === name);
  }

  checkCondition(current: any): boolean {
    return (this.person.speaking.find((x: any) => x.label === current.label) !== undefined);
  }

}

HTML:

{{title}}

<form #form>
  <input type="text" [(ngModel)]="person.name" name="name" placeholder="insert name" />

  Languages:

        <input type="checkbox" [(ngModel)]="language.selected" name="languages" [checked]="checkCondition(language)" />{{language.label}}

    {{languages |json}}

  <button (click)="Update()">Update</button> |
  <button (click)="AddNew(); form.reset()">Add new</button> |
  <button (click)="Reset(); form.reset()">Reset form</button>
</form>

    {{one.name}}, speaking: {{one.speaking | json}} | Edit

A:

I managed to solve the issue by approaching a bit different. Thanks anyway for your input.
Sample HTML code:

    <input type="checkbox"
      [checked]="checkCondition(language.label)"
      (change)="updateCheckedOptions(language, $event)" />
      {{language.label}}

The solution can be found here: https://plnkr.co/edit/OXXbt8jxZHzjB3jVYC0o?p=preview


Q:

How to resolve 401 Unauthorized failures on intranet pages with IIS and Active Directory

I'm attempting allow/restrict website intranet users access based on Active Directory permissions.
I thought we'd reached our objective (authentication without domain sign-on prompt) until I discovered that pages (or even text files) accessed via our popular browsers Chrome/IE11/Firefox result in three requests for the same asset, two which of which fail with a 401 response code.
Capturing this with Charles Proxy it would look as such:

HTTP/1.1 401 Unauthorized
HTTP Error 401. The requested resource requires user authentication
HTTP/1.1 401 Unauthorized
401 - Unauthorized: Access is denied due to invalid credentials
HTTP/1.1 200 OK

The specifics of these requests/responses can be seen here:
http://pastebin.com/raw.php?i=3iBiGqHc
These happen in rapid succession, as if the browser is attempting retires. The resolution isn't sticky, and the browser will continue to request files in triplicate.
Are we missing a configuration setting somewhere?
PHP 5.6.9, IIS 7.5, Windows Server 2008 R2 SE SP1

A:

I think this is just how it works.
The 401 response is what tells the browser to provide credentials in scenarios other than mutual certificate authentication over TLS.


Q:

Finesse Class into Class

public abstract class AbstractRESTClientService<E extends IDable<String>>
    implements GenericService<E, String> {

    private Class<E> classType;
    private Class<E[]> classArray;
    private String controllerPath;

    public AbstractRESTClientService(final Class<E> classType,
        final Class<E[]> classArray,
        final String controllerPath) {
            this.classType = classType;
            this.classArray = classArray;
            this.controllerPath = controllerPath;
            this.webService = new GenericWebClientService<E>();
        }

    // ... other methods
}

Is there a way to manipulate classType into classArray so that I don't need to pass in classArray as a parameter?

A:

I hate to think this is the best way to do it, but here's how I've handled it.
public abstract class AbstractRESTClientService<E extends IDable<String>>
    implements GenericService<E, String> {

private Class<E> classType;
private Class<E[]> classArray;
private String controllerPath;

@SuppressWarnings("unchecked")
public AbstractRESTClientService(final Class<E[]> classArray,
    final String controllerPath) {
        this.classType = (Class<E>) classArray.getComponentType();
        this.classArray = classArray;
        this.controllerPath = controllerPath;
        this.webService = new GenericWebClientService<E>();
    }

    // ... other methods
}


Q:

Some questions about Fractals and software

Ever since I read this article on math.SE I have been amazed by the wonder of fractals.
I have been trying to learn what are fractals and how to write an equation for one, and I am truly confused, I actually have a few questions I want to ask:

I know the Famous Mandelbrot Fractal is made by the equation $Z_{i+1}=Z_i+C$ where Z and C are complex numbers, but how are other Fractals made? because I dont know any other examples of equations of fractals
I know that fractals have different dimensions, what exactly does a 4-dimensional Fractal mean?
Are there any softwares that I can use to explore the wonder of fractals?
If I wanted to make my own fractal, how would I write an equation for it?

Thanks in Advance

A:

I know the Famous Mandelbrot Fractal is made by the equation Zi+1=Zi+C where Z and C are complex numbers, but how are other Fractals made?

So, you already know the Mandelbrot equation (function, whatever):
$P_c(z)=z^2+c$
Creating a fractal is slightly more than just an equation however.
Though you might already know this, here is the process which is used to graph the Mandelbrot fractal:
First off, we need to determine our graph size. Since the Mandelbrot set all happens roughly within x of$-2 \space to \frac{1}{2}$ and y of $-1\space to\space  1$, we'll just have a graph with the size of $xMin = -2, xMax = 2, yMin = -2, and yMin = 2$. It might be a little stretched/compressed...

Next, we loop through all the points, incrementing with a relatively small value: My calculator (a ti-84 silver plus) automatically sets it at 0.0425531914. Then, for every increment, we create a value $c$ which equals $X+Yi$, X and Y being the x and y coordinates of the current "point"(increment in the form of $(x,y)$).
Before we do anything more, we first create another value $z$ which equals $c$.
Then we insert this new variable $z$ into the "equation" which has already been mentioned: $z^2+c$.
Now, to put this into perspective, let's take the first point, $(-2,-2)$ which hasn't had any incrementation yet. Then we would have $c=-2-2i$ and $z=-2-2i$. With both variables inserted into the equation this is $(-2-2i)^2+(-2-2i)$. Calculated, this equals just $6i-2$  (don't know why? Sorry, I can't go into the details, just remember that $i^2=-1$. Or please correct me if I am wrong).
However, this isn't all... Oh no. Before we go on to the next point, we first reiterate this equation again and again - the more we do it, the more accuate the final image. For this example (with my slow calculator) I will only be doing 15 iterations. How do we reiterate? Well, first off, you need to remember that $z=z^2+c$, so for the next iteration, we would have the equation $(6i-2)^2+(-2-2i)$ (because $z$ is now the outcome of the previous calculation). And so we go on.
But what is this all for? Well, if after all these iterations, $|z|$ is still $\le 2$, note the absolute value bars..., then that tells us that we want to plot a black point at the current screen point. If, on the other hand, $z$ is greater than 2 (note: iterations are stopped when it does pass 2), then we plot a different color for the point, depending on how many iterations it took for it to become greater than 2. In my case however, since I have a black or nothing screen, I will only plot something if $|z|\le2$. Otherwise I leave the point (pixel) blank. So my final outcome will be something along the following lines:

EDIT: You can see how sloppy that looks. Here is the same thing but with 25 iterations:
Ahh! Much nicer (end edit).
So that is how the fractals are drawn (sorry if I went into too much detail). For the math and process behind how other fractals are drawn, first off, view this list of fractals on wikipedia, and then follow the individual links. You will find that some, like the Julia set (which is very closely related to the Mandelbrot set), use roughly the same way of drawing the fractal. Others, like the Koch snowflake and even simpler, the Cantor set, are drawn very differently! If more detail is wanted, then Google how to plot/draw a specific fractal! :)

I know that fractals have different dimensions, what exactly does a 4-dimensional Fractal mean?

First, as a quick example, here is a 3 dimensional version of the Mandelbrot set, which is called the Mandelbulb:
Image from wikipedia link

Now, think about it. First, second and third dimensional objects are the only things that our minds can accurately imagine (I am suddenly reminded of flatland). Since the third dimension uses width length and height, what other extra dimension could there be? Some have imagined it as time, others as other things. So, really, we cannot accurately portray a 4 dimensional object, much less a fractal!
However, in theory, it is feasible!
From this very interesting link:

Complex numbers can be extended to a four-tuple value with one real and three imaginary units. These are called Quaternions and can be visualized as a four dimensional space. When using the Julia equation with Quaternions we can define a 4D dimensional object. It becomes a lot trickier to visualize however.

An image of what a Julia set might look like in 4D from the aforementioned link:

Are there any softwares that I can use to explore the wonder of fractals?
Yes, there are a number of them! A small list can be found here, but I will go ahead and recommend the first on that list: Xaos. Takes a minute or two to install and has 25 preset fractals to explore! Zooming animations can also be recorded.

If I wanted to make my own fractal, how would I write an equation for it?

Hmm, there is no set way to make an equation. Playing around with random equations? Sure! The previously mentioned Xaos can take user formulas. Or there is a smaller online app which can do something related..
However, if you really wanted to know how to be the next Benoit Mandelbrot and find a world famous fractal... I'm sorry, there is no way to answer such a question. But these nice tools will help you experiment with anything you may come up with...

Enjoy the wonderful world of fractals!


Q:

Javascript Read Object Array

I have jquery code from which I'm fetching the data report based on weekdays.
What I want is to read an array object returned by ajax.  Here is the script :
<script>
export default {
    data() {
        return {
            currentcohortgraphdata: [{"Monday":"0","Tuesday":"0","Wednesday":"0","Thursday":"0","Friday":"0","Saturday":"0","Sunday":"0"}],
        }
    },
    mounted() {

    },
    methods: {
        loadCohortAttendancies() {
            this.$Progress.start();
            axios.get("api/loadCohortAttendancies").then(({data}) => (this.currentcohortgraphdata = data));
            this.$Progress.finish();
            var result = this.currentcohortgraphdata;

            result.forEach(function (e) {
                if (e.Monday > 0) {
                    alert(e.Thursday);
                }
            });
        }
    },
    created() {
        this.loadCohortAttendancies();
    },
    mounted() {

    }
}

When I run above script from ajax request axios.get("api/loadCohortAttendancies").then(({data}) => (this.currentcohortgraphdata = data)); The results returned from the request is [{"Monday":"12","Tuesday":"10","Wednesday":"3","Thursday":"5","Friday":"4","Saturday":"1","Sunday":"9"}]
. But unfortunately when I run the script I dont get result from the alert(e.Thursday); part of the script, can anyone point where I'm getting wrong? Thanks in advance

A:

What is happening is that you are running your code before your request is done, and it results in running your forEach with default values

currentcohortgraphdata:
  [{"Monday":"0","Tuesday":"0","Wednesday":"0","Thursday":"0","Friday":"0","Saturday":"0","Sunday":"0"}],

Simply move ur code inside .then block
axios.get("api/loadCohortAttendancies").then(({data}) => {
     this.currentcohortgraphdata = data
     this.$Progress.finish();
     var result = this.currentcohortgraphdata;

     result.forEach(function (e) {
         if (e.Monday > 0) {
             alert(e.Thursday);
         }
     });
});

Alternatively, you can use async/await syntax:
methods: {
  async loadCohortAttendancies() {
    this.$Progress.start();
    const { data } = await axios.get("api/loadCohortAttendancies");
    this.currentcohortgraphdata = data;
    this.$Progress.finish();
    const result = this.currentcohortgraphdata;

    result.forEach(function (e) {
      if (e.Monday > 0) {
        alert(e.Thursday);
      }
    });
  }
},


Q:

output and call array from class function (rollingcurl)

Excuse my English, please.
I use Rollingcurl to crawl various pages.
Rollingcurl: https://github.com/LionsAd/rolling-curl
My class:
<?php

class Imdb
{

    private $release;
    public function __construct()
    {
        $this->release = "";
    }

    // SEARCH
    public static function most_popular($response, $info)
    {

        $doc = new DOMDocument();

        libxml_use_internal_errors(true); //disable libxml errors

        if (!empty($response)) {
            //if any html is actually returned

            $doc->loadHTML($response);
            libxml_clear_errors(); //remove errors for yucky html

            $xpath = new DOMXPath($doc);

            //get all the h2's with an id
            $row   = $xpath->query("//div[contains(@class, 'lister-item-image') and contains(@class, 'float-left')]/a/@href");
            $nexts = $xpath->query("//a[contains(@class, 'lister-page-next') and contains(@class, 'next-page')]");
            $names = $xpath->query('//img[@class="loadlate"]');

            // NEXT URL - ONE TIME
            $Count    = 0;
            $next_url = "";
            foreach ($nexts as $next) {

                $Count++;
                if ($Count == 1) {
                    /*echo "Next URL: " . $next->getAttribute('href') . "
";*/

                    $next_link = $next->getAttribute('href');
                }
            }

            // RELEASE NAME
            $rls_name = "";
            foreach ($names as $name) {
                $rls_name .= $name->getAttribute('alt');
            }

            // IMDB TT0000000 RLEASE
            if ($row->length > 0) {
                $link = "";
                foreach ($row as $row) {
                    $tt_info .= @get_match('/tt\\d{7}/is', $doc->saveHtml($row), 0);
                }
            }

        }
        $array = array(
            $next_link,
            $rls_name,
            $tt_info,
        );
        return ($array);
    }
}

Output/Return:
$array = array(
    $next_link,
    $rls_name,
    $tt_info,
);
return ($array);

Call:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

function get_match($regex, $content, $pos = 1)
{
    /* do your job */
    preg_match($regex, $content, $matches);
    /* return our result */
    return $matches[intval($pos)];
}

require "RollingCurl.php";
require "imdb_class.php";
$imdb = new Imdb;

if (isset($_GET['action']) || isset($_POST['action'])) {
    $action = (isset($_GET['action'])) ? $_GET['action'] : $_POST['action'];
} else {
    $action = "";
}

echo "  2222

";

if ($action == "most_popular") {

    $popular = '&num_votes=1000,&production_status=released&groups=top_1000&sort=moviemeter,asc&count=40&start=1';

    if (isset($_GET['date'])) {
        $link = "https://www.imdb.com/search/title?title_type=feature,tv_movie&release_date=,".$_GET['date'].$popular;
    } else {
        $link = "https://www.imdb.com/search/title?title_type=feature,tv_movie&release_date=,2018".$popular;
    }

    $urls            = array($link);
    $rc              = new RollingCurl([$imdb, 'most_popular']); //[$imdb, 'most_popular']
    $rc->window_size = 20;
    foreach ($urls as $url) {
        $request = new RollingCurlRequest($url);
        $rc->add($request);
    }
    $stream = $rc->execute();
}

If I output everything as "echo" in the class, everything is also displayed. However, I want to call everything individually.
If I now try to output it like this, it doesn't work.
$stream[0]
$stream[1]
$stream[3]

Does anyone have any idea how this might work?
Thank you very much in advance.

A:

RollingCurl doesn't do anything with the return value of the callback, and doesn't return it to the caller. $rc->execute() just returns true when there's a callback function. If you want to save anything, you need to do it in the callback function itself.
You should make most_popular a non-static function, and give it a property $results that you initialize to [] in the constructor.. Then it can do:
$this->results[] = $array;

After you do
$rc->execute();

you can do:
foreach ($imdb->results as $result) {
    echo "Release name: $result[1]
TT Info: $result[2]
";
}

It would be better if you put the data you extracted from the document in arrays rather than concatenated strings, e.g.
$this->$rls_names = [];
foreach ($names as $name) {
    $this->$rls_names[] = $name->getAttribute('alt');
}

$this->$tt_infos = [];
foreach ($rows as $row) {
    $this->$tt_infos[] = @get_match('/tt\\d{7}/is', $doc->saveHtml($row), 0);
}

$this->next_link = $next[0]->getAttribute('href'); // no need for a loop to get the first element of an array


Q:

How to store objects data into database from OOP application efficiently and easily?

I design an objected oriented application using C# with database back end, for some time I was building same application using procedural way in which I feel storing data to database is little bit easier using simple SQL statement.
I my application I want to store the objects attribute to database, for example for an item object
    Class Item {
 private string itemId;

private string itemname;

private Invoice inv;  //assume Invoice object

//method

public bool storetodb() {

//..something like this
}
}

The problem is I feel a little bit complex when storing and retrieving object data to database. When I searched on some resource also they use like collection class to map between object on the application and relational database. Even I have searched SO but I couldn't find any related information. One source I got was

http://www.codeproject.com/KB/database/AONETOOP.aspx  ..... The author uses collection to store and retrieve data
I hear also about ORM technology although I have never tried it.

So what is good practice for designing these types of applications?
can you give any links, article,  recommended book or response for tackling these types of problem.
Thanks
Update
It seems ORM tools mainly nhibernate is most promising from your suggestion.
Thanks all of for your help, I will consider ORM

A:

You should invest some time to investigate one or two ORMs. If you're working with .NET 4.0, you should give the new implementation of Entity Framework a try. Another widely used ORM is NHibernate, which is a .NET version of Java's famous Hibernate ORM. However, from my own standing, ensure that you encapsulate the whole ORM into your Data Access Layer (DAL) so you can use native ADO.NET if the ORM ever hits the wall.
Another option are EAV CR databases. However, it's not the easiest way to learn how to live with. (I did that more than five years.)


Q:

In Specflow can I run one test as a step of another?

TL;DR; How can I create a specflow test that calls another test as its first step?
Given I already have one specflow test
And I want to run another test that goes deeper than the first test
Then I create a second test that runs the first test as its first step
And I add additional steps to test the deeper functionality

Sorry, little bit of specflow humor there.
eg I have a test that creates a sale already:
Given I want to create a sales order
And I open the sales order page
And I click the add new order button
Then a new sales order is created

And I want to have another test that tests adding a sales line
And another test that tests completing the sale
And another test that cancels the sale
And .. so on
All of those tests would start with the same first four steps as the simple test, which breaks the DRY principle.  So how can I do it so that the first step of the 2nd test just runs the first test? eg something like:
Given I have run the create sales order test  // right here it just runs the first test
And I add a sales order line
Then the order total is updated

If every test starts off with the same first four lines, and later on I realize that I need to change the simple create sale test, then I will also need to go and find and fix everywhere else that repeats those four lines.
EDIT: Note that this should also be able to work across features. eg The simple test above is defined in the sales feature.  But I would also have a credits feature, and that would require creating a sale each time in order to be able to credit it:
Given I want to credit a sale
And I run the create sales order test
And I complete the the sale
And I click the credit button
Then the sale is credited

A:

As noted already you can use a background for this (and that's probably the best option in most situations), but you can also create a step which calls the other steps.
[Binding]
public class MySteps: Steps //Inheriting this base class is vital or the methods used below won't be available
{
    [Given("I have created an order")]
    public void CreateOrder()
    {
         Given("I want to create a sales order");
         Given("I open the sales order page");
         Given("I click the add new order button");
         Then("a new sales order is created");
    }
}

which you can then use in your scenario:
Scenario: I add another sale
    Given I have created an order
    When I add a sales order line
    Then the order total is updated

This has the advantage that this composite step can be used anywhere in the scenario and not just as a starting point. This step can then be reused across multiple features if you need

A:

Use a Background:
Background:
    Given I want to create a sales order
    And I open the sales order page
    And I click the add new order button
    Then a new sales order is created

Scenario: I add another sale
    When I add a sales order line
    Then the order total is updated

Scenario: I add cancel a sale
    When I cancel a sale
    Then the order total is updated to 0

etc.

A:

You don't need to run actual steps to create a sales order. Just implement a step definition that does this for you as a one-liner.
First, the fictional SalesOrder class:
public class SalesOrder
{
    public double Amount { get; set; }
    public string Description { get; set; }
}

Then the step definitions
using TechTalk.SpecFlow;
using TechTalk.SpecFlow.Assist;

[Binding]
public class SalesOrderSteps
{
    [Given("I have already created a Sales Order")]
    public void GivenIHaveAlreadyCreatedASalesOrder()
    {
        var order = new SalesOrder()
        {
            // .. set default properties
        };

        // Save to scenario context so subsequent steps can access it
        ScenarioContext.Current.Set<SalesOrder>(order);

        using (var db = new DatabaseContext())
        {
            db.SalesOrders.Add(order);
            db.SaveChanges();
        }
    }

    [Given("I have already created a Sales Order with the following attributes:")]
    public void GivenIHaveAlreadyCreatedASalesOrderWithTheFollowingAttributes(Table table)
    {
        var order = table.CreateInstance<SalesOrder>();

        // Save to scenario context so subsequent steps can access it
        ScenarioContext.Current.Set<SalesOrder>(order);

        using (var db = new DatabaseContext())
        {
            db.SalesOrders.Add(order);
            db.SaveChanges();
        }
    }
}

Now you can create Sales orders as a one-liner and optionally include some custom attributes:
Scenario: Something
    Given I have already created a Sales Order

Scenario: Something else
    Given I have already created a Sales Order with the following attributes:
        | Field       | Value             |
        | Amount      | 25.99             |
        | Description | Just a test order |

If you need to access that SalesOrder object in other step definitions without querying for it in the database, use ScenarioContext.Current.Get<SalesOrder>() to retrieve that object from the scenario context.


Q:

Conditional Formatting - how to set range for "one condition per row"?

I thought I understood Conditional Formatting, but I'm having trouble applying it.
I have a table like this:
J   F   M   A   M   J   J   A   S   O   N   D
317 876 781 735 490 790 569 922 976 923 259 270
440 734 788 729 337 876 641 735 892 906 463 872
773 863 537 538 389 988 404 599 459 976 235 891
772 134 845 218 669 414 352 276 965 677 723 342
343 283 251 703 420 430 355 485 537 723 838 199
354 846 503 448 196 249 237 503 309 291 432 807
259 126 213 254 577 688 195 681 658 407 637 827
293 333 562 242 504 335 276 675 173 592 388 418

And I'd just like to highlight, via Green Fill, the Max() in each row.
I highlighted my range, keeping the top left (317) as my active cell. Then I tried this formula:
=max($A2:$L2), but this just highlights my entire table:

If I highlight row 2, use =Max($A2:$L2), then the whole row gets highlighted...I've even tried using the Top 10 default rule, changing to top 1, but no avail.
What I can do, is use the Top 1, on a single row, then paste that formatting down.  However, I'd like to get a single formula, if possible, so I can avoid having hundreds of CF formats in the "CF rules box".
Thanks for any ideas. I'm sure it is a simple fix, I'm just overthinking.

A:

I think the formula you're looking for is:
=A2=MAX($A2:$L2)

This compares the value of the cell to the max value of the row.  When equal, the formula evaluates to TRUE.


Q:

Javascript: Create object methods/properties by looping over an array

What I'm really looking for is code like the following:
var painter = {}; // An object to hold methods
var colors = ['blue', 'red', 'green', 'yellow']; // The names of methods to be defined
colors.forEach( function(color) {
    painter.defineMethod(color, function(){ console.log(color); });
});

painter.blue() // writes blue
painter.red() // writes red
etc.

the painter.defineMethod() is the key.
I have to define several (upwards of 40) methods to an object and they are all basically the same, with minor but predictable changes that really all call another method. For example:
painter.blue = function(tool) {
   painter.draw('blue', tool); // Would paint blue with a brush or pencil or whatever.
}

Is something like this possible, or am I stuck defining all these properties explicitly? Is there any performance benefit to one way or the other?
What would be easy in a language that has variable variables or magic methods is proving difficult (or impossible) in Javascript. Though I admit that javascript is not my forte.
Thanks!

A:

Your instinct is correct, you can indeed automate this:
colors.forEach( function(color) {
    painter[color] = function(tool) {
        painter.draw(color, tool);
    };
});

There are two things at work here:

In JavaScript, you can access (get or set) a property either using dot notation and a property name literal (obj.foo), or by using brackets notation and a property name string (obj["foo"]). In the latter case, the string can be the result of any expression, including a variable lookup. So painter[color] = ... assigns to a property whose name comes from the color argument.
Then we're using the fact that the function we're creating is a closure over the call to the iteration function we give forEach, and so we can use the color argument in that function. Even though the call to the iteration function returns, because we created a function within the call and kept a reference to it, that function keeps a reference to the context (it's a closure over the context), and so we can rely on the color argument being there. More about closures (on my blog): Closures are not complicated

But since painter.draw takes the color as its first argument and the tool as its second, there's a second way you could do it if you like, though: You can "curry" the color argument into the method using Function#bind (an ES5 feature that can be shimmed on the increasingly-small number of old engines that don't have it) on painter.draw:
colors.forEach( function(color) {
    painter[color] = painter.draw.bind(painter, color);
});

Function#bind returns a function that, when called, calls the original function with the given this value (painter in the example above) and any further arguments you supply to bind, followed by any arguments given to the original. A simple example may make that clearer:

function func(a, b) {
  snippet.log("this.name = " + this.name);
  snippet.log("a = " + a);
  snippet.log("b = " + b);
}

var o1 = {
  name: "o1"
};
var o2 = {
  name: "o2"
};

var o1boundfoo = func.bind(o1, "foo");
var o2boundbar = func.bind(o2, "bar");

o1boundfoo("nifty"); // Shows:
                     // this.name = o1
                     // a = foo
                     // b = nifty

o2boundbar("nifty"); // Shows:
                     // this.name = o2
                     // a = bar
                     // b = nifty
<!-- Temporary snippet object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>


Q:

Get value from CheckBoxPreference when it is changed

I'm trying to create Preference Screen with a Checkbox control.
 <CheckBoxPreference android:summaryOn="@string/mySummaryOn"
  android:summaryOff="@string/mySummaryOff"
  android:key="myCB"
  android:title="my checkbox"/>

I want to get this Boolean value when ever its getting changed.
In my Application i have done as below implementing OnSharedPreferenceChangeListener
public boolean cbValue;
 @Override
    public void onCreate() {
        // The following line triggers the initialization of ACRA
        ACRA.init(this);
        prefs=PreferenceManager.getDefaultSharedPreferences(this);
        prefs.registerOnSharedPreferenceChangeListener(this);
        super.onCreate();
    }

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
        String key) {
    // TODO Auto-generated method stub
    //FacebookStatus=prefs.getBoolean("myCB", true);
    Toast.makeText(getBaseContext(), "Shared Preference Changes ",Toast.LENGTH_LONG ).show();
}

onSharedPreferenceChanged method is not at all called even when i toggle check box in pref screen.
If i need to get value from Shared preference each time when value is changed wat should i do?

A:

Instead of using OnSharedPreferenceChangeListener:
Add to your preference activity's onCreate method following line: Preference myCheckbox = findPreference("myCB")
Then apply a listener to myCheckbox object: myCheckbox.setOnPreferenceChangeListener(myCheckboxListener)
Code of the listener (as a class field):
private OnPreferenceChangeListener myCheckboxListener = new OnPreferenceChangeListener() {

    public boolean onPreferenceChange(Preference preference, Object newValue) {
        // Read new value from Object newValue here
        return true;
    }
};


Q:

Execute external command

I do not know whether it is a Scala or Play! question. I want to execute some external command from my Play application, get the output from the command and show a report to user based on the command output. Can anyone help?
For example, when I enter my-command from shell it shows output like below, which I want to capture and show in web:
Id    Name   IP
====================
1     A      x.y.z.a
2     B      p.q.r.s

Please, do not worry about format and parsing of the output. Functionally, I am looking something like PHP exec. I know about java Runtime.getRuntime().exec("command") but is there any Scala/Play version to serve the purpose?

A:

You have to import the process packages of scala first. The method !! does what you need, it executes the statement and captures the text output.
import scala.sys.process._
val cmd = "uname -a" // Your command
val output = cmd.!! // Captures the output

A:

scala> import scala.sys.process._
scala> Process("cat temp.txt")!

This assumes there is a temp file in your home directory. ! is for actual execution of the command. See scala.sys.process for more info.


Q:

why we are using "var app = angular.module('myApp', []);" this? especially i need to know about square brackets in this line?

<!DOCTYPE html>

First Name: <input type="text" ng-model="firstName">

Last Name: <input type="text" ng-model="lastName">

Full Name: {{firstName + " " + lastName}}

why we are using "var app = angular.module('myApp', []);" this? especially i need to know about square brackets in this line???

A:

The first argument is the module name myApp. The second argument is an array of module names that this module depends on. Empty square brackets denotes that this module does not have any dependencies.
var app = angular.module('myApp', []);


Q:

git: abandon changes to current checked out version

I checked out an earlier version of my project, using:
$ git checkout fd4a4a1

The response was:
Note: checking out 'fd4a4a1'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b new_branch_name

HEAD is now at fd4a4a1... <original commit message>

I copied a chunk of code, but made no changes. I now want to return to the current branch. However, when I run...
git checkout myCurrentBranch

... git complains:
error: Your local changes to the following files would be overwritten by checkout:
    app/.meteor/packages
    app/meteo4j.js
Please, commit your changes or stash them before you can switch branches.
Aborting

I don't care about these changes. If they were made, it happened unintentionally. Is it possible to force git to ignore these changes and to checkout my current branch, without changing my history in any way?

A:

Is it possible to force git to ignore these changes and to checkout my current branch, without changing my history in any way?

Yes, use git checkout -f <branchname> to "force" the checkout to happen, regardless of whether it will clobber any uncommitted changes.


Q:

Submission of Scala code to a cluster

Is it possible to run some akka code on the oracle grid engine with the use of multiple nodes?
So if I use the actor-model, which is a "message-passing model", is it possible to use Scala and the akka framework to run my code on a distributed memory system like a cluster or a grid?
If so, is there something similar like mpirun in mpi -c, to run my program on different nodes? Can you give a submission example using oracle grid engine?
how do I know inside scala on which node am I and to how many nodes the job has been submitted?
Is it possible to communicate with other nodes through the actor-model?

A:

mpirun or (mpiexec on some systems) can run any kind of executables (even if they don't use MPI). I currently use it to launch java and scala codes on clusters. It may be tricky to pass arguments to the executable when calling mpirun so you could use an intermediate script.
We use Torque/Maui scripts which are not compatible with GridEngine, but here is a script my colleague is currently using:
#!/bin/bash
#PBS -l walltime=24:00:00
#PBS -l nodes=10:ppn=1
#PBS -l pmem=45gb
#PBS -q spc
# Find the list of nodes in the cluster
id=$PBS_JOBID
nodes_fn="${id}.nodes"
# Config file
config_fn="human_stability_article.conf"
# Java command to call
java_cmd="java -Xmx10g -cp akka/:EvoProteo-assembly-0.0.2.jar ch.unige.distrib.BuildTree ${nodes_fn} ${config_fn} ${id}"
# Create a small script to pass properly the parameters
aktor_fn="./${id}_aktor.sh"
echo -e "${java_cmd}" >> $aktor_fn
# Copy the machine file to the proper location
rm -f $nodes_fn
cp $PBS_NODEFILE $nodes_fn
# Launch the script on 10 notes
mpirun -np 10 sh $aktor_fn > "${id}_human_stability_out.txt"


Q:

Does $\sum^{\infty}_{n=1}xe^{-nx}$ converge uniformly on $[0,\infty)$?

I was trying to solve this problem with a friend but we got stuck.
TRIAL
We claimed that the series does not converge uniformly which implies that it is not uniformly Cauchy, i.e., $\exists\,\epsilon_0>0$ such that $\forall\,k\in \Bbb{N},\,\exists\,n_k,m_k\geq k,\;\exists \,x_k\subset [0,\infty)$ such that
\begin{align}\left|s_{n_k}(x_k)- s_{m_k}(x_k)\right|\geq \epsilon_0\end{align}
Now, let $k\in \Bbb{N}$ be given. Take $n_k=k,\,m_k=k+1,\;x_k=\frac{1}{k+1}\subset [0,\infty)$ and $\epsilon_0 \overset{?}{=}.$ Then,
\begin{align}\left|s_{n_k}(x_k)- s_{m_k}(x_k)\right|&=\left| \sum^{n_k}_{i=1}x_k e^{-i x_k}-\sum^{m_k}_{i=1}x_k e^{-i x_k}\right|\\&=\left| x_k e^{-(k+1) x_k}\right|\\&=\left| \frac{1}{k+1} e^{-(k+1) \frac{1}{k+1}}\right|\\&=\left| \frac{1}{k+1} e^{-1}\right|\end{align}
I'm stuck at this point. Can anyone help out? Thanks!

A:

Analysis
First write down the truncate of the series: for $x>0, m, p \in \mathbb N^*$, we have
$$
\sum_{m+1}^{m+p} x \mathrm e^{-nx} = \mathrm e^{-(m+1)x} x\sum_0^{p-1} \mathrm e^{-nx} = \mathrm e^{-(m+1)x} x \frac {1-\mathrm e^{-px}}{1- \mathrm e^{-x}}.
$$
Now clearly we could take $x =1/(m+1)$, then the sum becomes
$$
\mathrm e^{-1} \cdot \frac 1{m+1} \cdot \frac {1 - \exp(-p/(m+1))} {1 - \exp(1/(m+1))}.
$$
For brevity, we could let $p = m+1$.
Now note that
$$
\lim_m \frac {\dfrac 1 {m+1}}{1 - \exp\left(-\dfrac 1 {m+1}\right)} = 1 >1/2
$$
so for sufficiently large $m$, the sum is greater than
$$
\mathrm e^{-1} (1-\mathrm e^{-1}) \cdot \frac 12.
$$
The proof
In other words, first take $m \in \mathbb N^*$ such that
$$
\frac {1/(m+1)} {1 - \exp(-1/(m+1))} > \frac 12,
$$
then the sum
$$
\left.\sum_{m+1}^{2m+2} xe^{-nx}\right|_{x=(m+1)^{-1}} = \mathrm e^{-1} (1-\mathrm e^{-1})\cdot \frac {1/(m+1)} {1 - \exp(1/(m+1))} > \mathrm e^{-1} (1-\mathrm e^{-1}) \cdot \frac 12 =:\varepsilon_0.
$$
Alternative
We know that $xe^{-nx}$ is continuous on $[0,+\infty)$, thus if the series converges uniformly, then the sum must be continuous $[0,+\infty)$. However the sum is [suppose your sum is started from $n =0$]
$$
S(x)=
\begin{cases}
0, & x = 0,\\
\dfrac x {1- \mathrm e^{-x}}, & x >0,
\end{cases}
$$
then $S(0^+) = 1 \neq 0$, i.e. $S$ is not continuous on $[0, +\infty )$, hence the series cannot converge uniformly.


Q:

How many spells can a wizard have in 4e, and how do they work?

Sorry, I'm just a bit confused on this. I'm making a half-elf wizard for my first campaign and though I really want to play a wizard, I'm a bit confused on the spellbook mechanic.
I'm also a bit confused on how at-will powers work, in a way...
So basically, how many spells can I have and which ones can I use per day now, at level 1?
How many will I have in the future as I level up?
And how often can I use at-will powers? As much as I want?
EDIT: Despite the link leading me to the other question on how human wizards work, I still don't fully understand the system, though... From reading the handbook a bit more, what I've gathered so far is that I have access to all my at-will spells, all encounters, and 1 daily at the start plus 2 more per level where I learn a daily/utility power, though I can only prepare 1 one of those 2?

A:

Let's review the basic numbers first, before we get into how Wizards break them: at level 1, every character picks 2 at-wills, 1 encounter power, and 1 daily. At level 2, they pick up a utility power too.
At-will powers
So, you have to choose two at-wills, right?
But there's something else first. Some classes have feature powers, and the Wizard's are their four cantrips. You get these automatically. You already have four at-wills, just by being a Wizard.
These do not count toward the 2 you pick. So pick two more Wizard Attack 1 at-wills.
Notice that the Cantrips have no level mentioned. Neither do Racial powers. This is your hint that it's an automatic feature that you get in addition to however many at-wills/encounters/dailies/utilities you get at your level. (The Paladin also has four class feature powers, but two of those are encounter powers.)
Total level 1 at-wills: 6. And then some racial features might give you more.
Encounter powers
1 at first level. Gain encounter powers the same as any other class.
A lot of races also give you an encounter power, but like I mentioned about the at-wills: this comes in addition to whatever single encounter power you pick, and doesn't count toward your limit of 1.
The Spellbook: Dailies and Utilities
This is where Wizards have some novelty, and where they get a bit complicated.
Every class has a notion that they have X powers and they have them available every day. Wizards break this mold and do things very differently.
When the Wizard might learn a daily or utility power — including their first-level daily and second-level utility — instead, the Wizard picks two dailies, or two utilities. They write these two down in their spellbook. Then as the feature says...

After an extended rest, you can prepare a number of daily and utility spells according to what you can cast per day for your level. You can’t prepare the same spell twice.

You pick a bunch, and these are your daily and utility powers for the day. So you know twice as many daily powers and twice as many utility powers as any other class. But at the beginning of your adventuring day, you pick the same amount as anyone else, and those are your dailies and utilities for the day.
So at level 2, instead of the usual 1 daily and 1 utility, you'll have twice that many - 2 dailies and 2 utility powers - written in your spellbook. But after you rest, you'll pick 1 of those dailies and 1 of those utility powers, and you'll have those available to use for the day. So on any given day, you still have access to the same amount of daily and utility powers as any other character - but uniquely, Wizards can change the powers they have access to day-to-day between those in their spellbook.
At a level where you might be alotted 3 daily powers, you'll have 6 in your spellbook, and pick any 3 of those 6 at the beginning of an adventuring day. Etc.
Rituals
You also get to start with some rituals written in your spellbook. This is separate to your powers entirely, and a different casting system every player character shares. You just get to start off knowing some rituals, where others will have to find them or buy them.


Q:

Rows are selected differently on document load and on function call

I was working on my own filter for datatables. To make a long story short, it gets a date value placed in one of the columns and checks it against the current date, and if its value is inferior to our current date then the entire row is deleted. This works perfectly but only on document load. I've tried to trigger my code with a button but it changes the behaviour of my code: instead of identifying rows according to its place in the original data source (in this case the table is written in html directly), it identifies rows according to its place in the current view.
Here is a working jsfiddle: http://jsfiddle.net/c18mzcox/
In order to check what I'm saying just click the "hide finished" button and check which rows are being deleted (index 0 and 6 from the current view, which is wrong). Then, edit the javascript part and delete the button in line 22 and its corresponding ending in line 75. Refresh and see how this time the rows being deleted are different (index 0 and 6 from the original file, which is what I need). Without any button attached it works as it should. But attaching a button to the code changes the behaviour of row selection...
Here is my code:
$(document).ready( function () {

$.fn.dataTable.moment('D[ / ]M[ / ]YYYY');
var table = $('#table_id').DataTable({

    "language": {
        "url": "http://cdn.datatables.net/plug-ins/3cfcc339e89/i18n/Spanish.json"
    },

    "order": [[ 1, "desc" ]],

    dom: 'TC<"clear">lfrtip',

    oTableTools: {
        sSwfPath: "http://cdn.datatables.net/tabletools/2.2.3/swf/copy_csv_xls_pdf.swf"
    }

});
    //If you delete this button it behaves as it should...
    $('#btnToggleFinish').click(function(){
        //Getting the current date
        var d = new Date();
        var day = d.getDate();
        var month = d.getMonth();
        var year = d.getFullYear();
        var actualDateObj = new Date();
        actualDateObj.setDate(day);
        actualDateObj.setMonth(month);
        actualDateObj.setYear(year);

        //Selecting the column with the dates
        var idx = table.column(2).data();
        //Getting the amount of rows for the loop
        var rowCount = table.data().length;

            for (var i = 0; rowCount > i; i++)
            {
                //Getting the date values from the table
                var myDay = idx[i].substring(0,2);
                var myMonth = idx[i].substring (5,7);
                var myYear = idx[i].substring (10,14);
                var tableDateObj = new Date();
                tableDateObj.setDate(myDay);
                tableDateObj.setMonth(myMonth-1);
                tableDateObj.setYear(myYear);

                if (actualDateObj > tableDateObj) {
                    table.row(i).nodes().to$().addClass('deleteMe');
                }
            }
        table.rows('.deleteMe').remove().draw();
    });
});

What am I doing wrong here? Thank you very much!

A:

This is not a proper answer to the problem, but somewhat it worked for me. Inside the code of the button which activates my filter, I've put a table.destroy(); and just after that I've put once again the constructor of the table before doing all the checks. Now it works as intended. This is not optimised and it does not work 100% because the table is not properly populated again if you want to undo the changes applied by the filter, but there it goes.
$(document).ready( function () {

$.fn.dataTable.moment('D[ / ]M[ / ]YYYY');
var table = $('#table_id').DataTable({

    "language": {
        "url": "http://cdn.datatables.net/plug-ins/3cfcc339e89/i18n/Spanish.json"
    },

    "order": [[ 1, "desc" ]],

    dom: 'TC<"clear">lfrtip',

    oTableTools: {
        sSwfPath: "http://cdn.datatables.net/tabletools/2.2.3/swf/copy_csv_xls_pdf.swf"
    }

});

    var hided = false;

    $('#btnToggleFinish').click(function(){

        if (hided == false){

            $(this).html(' Show');
            hided = true;

            table.destroy();

            table = $('#table_id').DataTable({

                "language": {
                    "url": "http://cdn.datatables.net/plug-ins/3cfcc339e89/i18n/Spanish.json"
                },

                "order": [[ 1, "desc" ]],

                dom: 'TC<"clear">lfrtip',

                oTableTools: {
                    sSwfPath: "http://cdn.datatables.net/tabletools/2.2.3/swf/copy_csv_xls_pdf.swf"
                }

            });

            var d = new Date();
            var day = d.getDate();
            var month = d.getMonth();
            var year = d.getFullYear();

            var actualDateObj = new Date();
            actualDateObj.setDate(day);
            actualDateObj.setMonth(month);
            actualDateObj.setYear(year);

            var idx = table.column(2).data();

            var rowCount = table.data().length;

                for (var i = 0; rowCount > i; i++)
                {

                    var myDay = idx[i].substring(0,2);
                    var myMonth = idx[i].substring (5,7);
                    var myYear = idx[i].substring (10,14);

                    var tableDateObj = new Date();
                    tableDateObj.setDate(myDay);
                    tableDateObj.setMonth(myMonth-1);
                    tableDateObj.setYear(myYear);

                    if (actualDateObj > tableDateObj) {

                        table.row(i).nodes().to$().addClass('deleteMe');
                    }

                }
            table.rows('.deleteMe').remove().draw();

        }

        else{
            $(this).html(' Hide');
            hided = false;
            table.destroy();
            table = $('#table_id').DataTable({

                "language": {
                    "url": "http://cdn.datatables.net/plug-ins/3cfcc339e89/i18n/Spanish.json"
                },

                "order": [[ 1, "desc" ]],

                dom: 'TC<"clear">lfrtip',

                oTableTools: {
                    sSwfPath: "http://cdn.datatables.net/tabletools/2.2.3/swf/copy_csv_xls_pdf.swf"
                }

            });
        }

    });
});