Pan Segue Calls viewDidLoad Loop

My pan gesture programmatically fakes a button press. If you press the actual button, the VC's viewDidLoad runs again once, stops, and is fine. But when I use the pan-gesture to programmatically fake the button press, the viewDidLoad runs about seven times, then stops.

The right-edge gesture triggers the "tomorrow" state which loads a handful of times. At that point, a left-edge gesture triggers the "today" state. That also loads 4-5 times.

Any ideas? Some code below, if needed.

Pan gesture added in viewDidLoad:

    //Adds edge gesture depending on VC state
    if curMainList == "Today" {
        let panLeftEdgeGesture_MainVC = UIScreenEdgePanGestureRecognizer(target: self, action: "panLeftEdge_toLifeList:")
        panLeftEdgeGesture_MainVC.edges = .Left
        view.addGestureRecognizer(panLeftEdgeGesture_MainVC)

        let panRightEdgeGesture_MainVC = UIScreenEdgePanGestureRecognizer(target: self, action: "panFromRightEdgeAction:")
        panRightEdgeGesture_MainVC.edges = .Right
        view.addGestureRecognizer(panRightEdgeGesture_MainVC)

        self.footer_LeftBtn.addTarget(self, action: "LeftFooterBtnPress", forControlEvents: UIControlEvents.TouchUpInside)
    }
    else {
        let panLeftEdgeGesture = UIScreenEdgePanGestureRecognizer(target: self, action: "panFromLeftEdgeAction:")
        panLeftEdgeGesture.edges = .Left
        view.addGestureRecognizer(panLeftEdgeGesture)
    }

Gesture's triggered:

//Gestures visible when view is 'Today'
func panLeftEdge_toLifeList(sender: UIScreenEdgePanGestureRecognizer) {
    dispatch_async(dispatch_get_main_queue()) { () -> Void in
        self.performSegueWithIdentifier("segueToLifeLists", sender: nil)
    }
}

func panFromRightEdgeAction(sender: UIScreenEdgePanGestureRecognizer) {
    //self.tomHdrBtnPress(tomorrowHdr)
    tomorrowHdr.sendActionsForControlEvents(UIControlEvents.TouchUpInside)
}

//Gesture added when viewing 'Tomorrow' list
func panFromLeftEdgeAction(sender: UIScreenEdgePanGestureRecognizer) {
    //self.todayHdrBtnPress(todayHdr)
    todayHdr.sendActionsForControlEvents(UIControlEvents.TouchUpInside)
}

@IBAction func todayHdrBtnPress(sender: AnyObject) {
    UIView.animateWithDuration(0.75, animations: {
        //Header changes
        self.hdrBox.backgroundColor = UIColor(red: 46/255.0, green: 173/255.0, blue: 11/255.0, alpha: 1.0)
        self.footer_RightArrow.hidden = false
        self.footer_RightBtn.hidden = false
        }
        , completion: nil
    )
    curMainList = "TodayTask"
    currentListEntity = curMainList
    viewDidLoad()
}

@IBAction func tomHdrBtnPress(sender: AnyObject) {
    UIView.animateWithDuration(0.75, animations: {
        //Header changes
        self.hdrBox.backgroundColor = UIColor(red: 49/255.0, green: 82/255.0, blue: 171/255.0, alpha: 1.0)
        self.footer_LeftBtn.addTarget(self, action: "LeftFooterBtnPress", forControlEvents: UIControlEvents.TouchUpInside)
        }
        , completion: nil
    )
    curMainList = "TomTask"
    currentListEntity = curMainList
    viewDidLoad()
}


Setup tips for installing a new SQL Server Database

For cost savings, we're moving from an managed SQL Server DB to a dedicated db on our own server.

What configuration checklist would you perform to ensure maximum security and reliability?


strange collision detection behavior in javascript 'game engine.'

If you play with the 'game' I've set up for a moment, you'll observe that the avatar falls right through the second platform when jumping onto it. I simply cannot fathom why this is. I understand that this is probably more code than should be posted, but I'm at my wits end, and maybe someone could quickly see what I'm doing wrong.
The 'game' in question. Just use the arrow keys for run and jump.

http://jsfiddle.net/QGB69/

//RequestAnimationFrame shim.

window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;

//Initializing canvas and world

var canvas = document.getElementById('viewport');
var ctx = canvas.getContext('2d');
var keysDown = [];
var currentPlatform = 0;

//some helpful variables

var canvasHeight = $('#viewport').height();
var canvasWidth = $('#viewport').width();

//Add keycodes to 'keysDown' array

$(document).keydown(function (e) {
    if ($.inArray(e.which, keysDown) === -1) {
        keysDown.push(e.keyCode);
    }
});

//Remove keycodes from 'keysDown' array

$(document).keyup(function (e) {
    if ($.inArray(e.which, keysDown) > -1) {
        keysDown = $.grep(keysDown, function (n, i) {
            return n !== e.which;
        });
    }
});

//Avatar object, lots of attributes, great import!

var avatar = {};

avatar.xPos = 50;
avatar.yPos = 50;
avatar.accl = 0.55;
avatar.decel = 0.85;
avatar.jReduction = 1.25;
avatar.direction = null;
avatar.stopping = false;
avatar.avatarHeight = 50;
avatar.avatarWidth = 25;
avatar.fallTime = 0;
avatar.isGrounded = false;
avatar.isJumping = false;
avatar.endJump = false;
avatar.jump = 18;
avatar.j = avatar.jump;
avatar.jStrength = 0.55;
avatar.speed = 13;
avatar.prevXPos = 0;
avatar.xDelta = 0;
avatar.xVelocity = 0;
avatar.yVelocity = 0;
avatar.yBottom = 0;
avatar.xAlignment = 0;

avatar.collDetect = function (args) {

    avatar.yBottom = avatar.yPos + avatar.avatarHeight;
    avatar.xPosRight = avatar.xPos + avatar.avatarWidth;

    for (i = 0; i < arguments.length; i++) {
        if (avatar.yBottom > arguments[i].boxTop) {
            if (avatar.xPos > arguments[i].xPos) {
                if (avatar.direction === 'left' && avatar.xDelta > avatar.xPos - arguments[i].xPosRight) {
                    avatar.xPos = arguments[i].xPosRight;
                    avatar.xStop();
                } else if (avatar.direction === 'left' && avatar.xPos <= arguments[i].xPosRight) {
                    avatar.xPos = arguments[i].xPosRight;
                    avatar.xStop();
                }
            } else if (avatar.xPos < arguments[i].xPos) {
                if (avatar.direction === 'right' && avatar.xDelta > arguments[i].xPos - avatar.xPosRight) {
                    avatar.xPos = arguments[i].xPos - avatar.avatarWidth;
                    avatar.xStop();
                } else if (avatar.direction === 'right' && avatar.xPos >= arguments[i].xPos) {
                    avatar.xPos = arguments[i].xPos - avatar.avatarWidth;
                    avatar.xStop();
                }
            }
        }

        if (avatar.xPos > arguments[i].xPos - avatar.avatarWidth && avatar.xPos < arguments[i].xPos + arguments[i].boxWidth) {
            currentPlatform = arguments[i].boxHeight;
        } else {
            currentPlatform = 0;
        }
    }
};

avatar.xStop = function () {
    avatar.xVelocity = 0;
    avatar.xDelta = 0;
    avatar.stopping = false;
    avatar.direction = null;
};

//First obstacle. Good luck gettin' over this one, avatar!

function Box(xPos, boxWidth, boxHeight, boxColor) {
    this.xPos = xPos;
    this.boxWidth = boxWidth;
    this.boxHeight = boxHeight;
    this.boxColor = boxColor;
    this.xPosRight = xPos + boxWidth;
    this.boxTop = canvasHeight - boxHeight;
}

function renderBoxes(n) {
    for (i = 0; i < arguments.length; i++) {
        ctx.fillStyle = arguments[i].boxColor;
        ctx.fillRect(arguments[i].xPos,
        canvasHeight - arguments[i].boxHeight,
        arguments[i].boxWidth,
        arguments[i].boxHeight);
    }
}

var box1 = new Box(100, 50, 100, 'gray');
var box2 = new Box(300, 50, 125, 'green');

//physics object. Properties of the world

var physx = {};
physx.gravity = 1;
physx.colliding = false;
physx.fallTimeModifier = 0.5;

//Big movement function. The action's in here!

function moveIt() {

    //Jump!

    if ($.inArray(38, keysDown) > -1) {

        if (avatar.j > 0) {
            avatar.isGrounded = false;
            avatar.isJumping = true;
            avatar.yPos -= avatar.j;
            avatar.yVelocity = avatar.j;
            avatar.j -= avatar.jStrength;
        } else if (avatar.j <= 0) {
            avatar.isJumping = false;
        }
    }

    //End Jump, initiated when the user lets off the jump key mid-jump.

    if (avatar.endJump === true) {

        if (avatar.j > 0) {
            avatar.j -= avatar.jReduction;
            avatar.yPos -= avatar.j;
        } else if (avatar.j <= 0) {
            avatar.isJumping = false;
            avatar.endJump = false;
        }

    }

    $(document).keyup(function (e) {
        if (e.which === 38 && avatar.isJumping === true) {
            avatar.endJump = true;
        }
    });

    //Accounting for deceleration when avatar stops.

    if (avatar.stopping === true) {

        if ((avatar.xVelocity - avatar.decel) <= 0) {
            avatar.xStop();
            return;
        }

        if (avatar.direction === 'right') {
            avatar.xPos += avatar.xVelocity;
            avatar.xVelocity -= avatar.decel;
            avatar.xDelta = avatar.xVelocity;
        }

        if (avatar.direction === 'left') {
            avatar.xPos -= avatar.xVelocity;
            avatar.xVelocity -= avatar.decel;
            avatar.xDelta = avatar.xVelocity
        }
    }

    //Correcting glitchy stopping behavior when conflicting left/right keycodes present in 'keysDown' array

    if ($.inArray(37, keysDown) > -1 && $.inArray(39, keysDown) > -1) {
        avatar.stopping = true;
    }

    //right

    if ($.inArray(39, keysDown) > -1) {

        if (avatar.stopping === false) {
            avatar.direction = 'right';
            if (avatar.xVelocity >= avatar.speed) {
                avatar.xPos += avatar.speed;
                avatar.xDelta = avatar.speed;
            } else {
                avatar.xPos += avatar.xVelocity;
                avatar.xVelocity += avatar.accl;
                avatar.xDelta = avatar.xVelocity;
            }
        }
    }

    //left

    if ($.inArray(37, keysDown) > -1) {

        if (avatar.stopping === false) {
            avatar.direction = 'left';
            if (avatar.xVelocity >= avatar.speed) {
                avatar.xPos -= avatar.speed;
                avatar.xDelta = avatar.speed;
            } else {
                avatar.xPos -= avatar.xVelocity;
                avatar.xVelocity += avatar.accl;
                avatar.xDeta = avatar.xVelocity;
            }
        }
    }

    //Set avatar.isStopping to true when

    $(document).keyup(function (e) {
        if (e.which === 39 || e.which === 37) {
            avatar.stopping = true;
        }
    });
}

//Gravity function. Keep him on the dang ground!

function grav() {

    if (avatar.isJumping) {
        return;
    }

    if (avatar.yPos >= (canvasHeight - currentPlatform) - avatar.avatarHeight) {
        avatar.isGrounded = true;
        avatar.fallTime = 0;
    } else {
        if ((avatar.fallTime * physx.gravity) > (((canvasHeight - currentPlatform) - avatar.avatarHeight) - avatar.yPos)) {
            avatar.yPos = (canvasHeight - currentPlatform) - avatar.avatarHeight;
            avatar.isGrounded = true;
            avatar.j = avatar.jump;
            avatar.fallTime = 0;
        } else {
            avatar.yPos += avatar.fallTime * physx.gravity;
            avatar.fallTime += physx.fallTimeModifier;
        }
    }
}

//Render the dang thing, ya dingus!

function render() {

    ctx.clearRect(0, 0, canvasWidth, canvasHeight);
    renderBoxes(box1, box2);
    avatar.collDetect(box2, box1);
    grav();
    ctx.fillStyle = 'red';
    ctx.fillRect(avatar.xPos,
    avatar.yPos,
    avatar.avatarWidth,
    avatar.avatarHeight);
    moveIt();

Thank you!


Dynamically load a JavaScript file

How can you reliably and dynamically load a JavaScript file?  This will can be used to implement a module or component that when 'initialized' the component will dynamically load all needed JavaScript library scripts on demand.

The client that uses the component isn't required to load all the library script files (and manually insert <script> tags into their web page) that implement this component - just the 'main' component script file.

How do mainstream JavaScript libraries accomplish this (Prototype, jQuery, etc)?  Do these tools merge multiple JavaScript files into a single redistributable 'build' version of a script file?  Or do they do any dynamic loading of ancillary 'library' scripts?

An addition to this question: is there a way to handle the event after a dynamically included JavaScript file is loaded?  Prototype has document.observe for document-wide events. Example:

document.observe("dom:loaded", function() {
  // initially hide all containers for tab content
  $$('div.tabcontent').invoke('hide');
});

What are the available events for a script element?


Rounded corners are not working in IE9

Possible Duplicate:

  ie9 border radius

Rounded corners are not working for me in IE9.

Here is my CSS:

-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
-khtml-border-radius: 5px;

Why are they not working?


Web API Post with Class Inheritence Not Working

I've been trying to get this to work for a long time, and haven't figured it out.

Web API Post Method

public BaseLowerItem Post([FromBody] BaseLowerItem value)
{
    return value;
}

What I'm Doing...

WP7 app posts a Json-serialized YearSending to the web api.

Problem:
Web API's Post gets a NULL value! It doesn't get the YearSending. If I changed the Post to Post(YearSending value), then it works like normal.

Classes

[DataContract, KnownType(typeof(YearSending))]
public class BaseLowerItem
{
    [DataMember]
    public long Id { get; set; }
}

[DataContract]
public class YearSending : BaseLowerItem
{
    [DataMember]
    public string Name { get; set; }
}

How do I tell it to get the right value? I already have the KnownType in the BaseLowerItem class as you can see.


bind() error : Cannot assign requested address

bind () error : Cannot assign requested address.

new_socket= socket(AF_INET, SOCK_DGRAM, 0);

localIP = "128.1.1.64";

memset(&socket_data, 0, sizeof(socket_data));

// Fill the socket structure
socket_data.sin_family      = AF_INET;
socket_data.sin_addr.s_addr = inet_addr(localIP);
socket_data.sin_port        = htons(PortNumber);

bind( new_socket, (struct sockaddr*) &socket_data, sizeof(socket_data))

Does any one know why the bind() is failing?


Java - How to make a variable that can be used anywhere?

I want to make a variable that I can use inside my method to change that variable outside my method. As a visual: (I imported the scanner class by the way)

public static void main(String[] args) {

    int quitVar = 1;
    Scanner scan = new Scanner(System.in);

    class IWantToQuit {
        public void quit() {
            quitVar++; //This is the problem area.
        }
    }
    IWantToQuit quiter = new IWantToQuit();
    while (quitVar == 1) {
        System.out.println("HELLO");
    System.out.println("Type QUIT to quit.");
    choice = scan.next();
    if (choice.equals("QUIT")) {
        quiter.quit();
    }

For some reason, it says that the local variable quitVar is accessed by the inner class but it needs to be declared and I have declared it. Any help is appreciated.


Link to Page Anchor pad top

I have a sticky navigation on the top of my page and i also have one as the right column.

My problem is that when i link the side navigation to an anchor it scrolls the page to that anchor and puts it behind the top navigation.

Is there anyway that i can have it so it scrolls the page to 100px above the actual anchor so it isn't behind the top sticky navigation?

I am using bootstrap with affix-top on the top navigation and data-spy="scroll" and alsoaffix` on the right column navigation

bold

Since i am using the data-spy="scroll" this affects the way that the scrollspy works since the anchor goes behind the top navigation before it changes the spy on the side navigation.

This is why i ant to have an offset on my anchor.


Alternate to iisreset

I have multiple sites on production server, some time one of site go down when heavy utility ended, which need iisreset, but iisreset cause all site down in resetting the iis. I want to reset the one site only, not all application pool. How i can reset my particular site of application pool.


Print regression tables with multiple standard errors

I would like to print two types of standard errors for each coefficient (e.g., robust and not) in the same regression table. For example:

# Simulate some data
dat <- data.frame(y=runif(100), matrix(rnorm(200), 100, 2))
fit <- lm(y ~ X1 + X2, data=dat)

# Compute robust SE
library(sandwich)
cov1        <- vcovHC(fit, type="HC")
robust.se  <- sqrt(diag(cov1))

# print regression table in latex
library(stargazer)
stargazer(fit)

How to add the robust SE as an additional row below each coefficient in the square brackets?

Something like:

    Model 1

X1 0.012
   (0.14)
   [0.21]

X2 0.72
   (0.64)
   [0.88]


RestSharp - Passing Token into GET call

I'm using OAuth2.0 to obtain a token which must be passed alongside the GET call.

I've built the POST method to obtain a token.

How can I use this token in a GET method to pass it alongside the call that I'm making?

Would the following work or is there another attribute that I should be using?

request.Method = "GET";
request.AddParameter= ("token", TokenVariableStoringValueFromPOST);


ADF Security disable RichCommandButton for Application Role

I am using Oracle ADF with JDeveloper 11g release 1, I'm crazy to configure application roles for the various groups. Let me explain, I have the following situation and I'm looking for some ideas: I want to enable the commit (RichCommandButton) Enterprise only certain role, what should I do? I decided to do an if statement in BackingBean get method in the page, correct? What is the proper way to proceed?


Display the saved data in my dropdown list

Hello I have a dropdown list which I display all the data that I have in my database in a specific table.
Now I want to display first a data from another table of my database, to be more specific I want to display first in my dropdown list the column specialty from the table doctor.
How can I do that?

Below is the code in order to display the data from another table in my database:

    <label id="Specialty">Specialty:</label>
    <select id="SelectSpecialty" name="specialty">
    <?php
  $sql = mysql_query("SELECT name FROM specialties");
  while ($row = mysql_fetch_array($sql)){
    echo "<option value='".$row['name']."'>".$row['name']."</option>";
  }
?>

PS: I want to display both datas from the two tables in the dropdown list


pandas groupby not working for 3 columns

I am trying to calculate Sum of column d in group by result of column a,b,c.

Although I have 2 different values in column c but still it is not coming as part of same group resulting sum is not calculated properly.

Please suggest.
Code I am using is :

s  = df.groupby(['a','b','c'])['d'].sum()

a    b    c    d

1    ab  123   1

1    ab  123   2

Output should be :

1    ab  123   3

But output is coming as

1    ab  123   1

         123   2

df.dtypes

a int64

b object

c object

d float64


Error with multiple self-invoking functions in one script: a case for a semicolon

In certain circumstances, having more than one self-invoking function in a single JavaScript file provokes an error. Getting the second function to return a value averts the error.

I have a barebones HTML file...

<script src="two.js"></script>
<script src="one.js"></script>

... using these scripts:

// two.js
(function () {
  console.log('1/2')
})()

(function () {
  console.log('2/2')
})()

// one.js
(function () {
  console.log('1/1')
})()

When I open the file in Chrome, I get this output:

1/2 two.js:2
Uncaught TypeError: undefined is not a function two.js:6
1/1

Other browsers complain in their own way. In other words, having two self-invoking functions in the same script causes a problem. Having one self-invoking function per script works fine. If I comment out the second function script two.js, there is no problem.

However, if I get the second function to return a value, then there is no problem either. Everything works fine if I change two.js to this:

(function () {
  console.log('1/2')
})()

foo = (function () {
  console.log('2/2')
  return 'bar'
})()

Why does the first version fail and the second succeed?


send get or post php data to server on button click android

I want pass post or get data from android on button click to php server, without using browser.
for eg
http://localhost:81/anis/car.php?name=xyz
is data i want to pass on button click. without using browser.


Visual Studio emulator failed to Start due to Server execution failure

I have tried the following for the past four days

Repaired Microsoft Visual Studio Emulator for Android

Repaired Windows Phone 8.1 Emulators

Removed of all existing virtual Switches

Ran XdeClenup.exe

Disabled Network Sharing on Ethernet

No luck yet. i still get error that;

The emulator was unable to verify that Virtual machine is running.(checked my vmms service and its on and running)

Something happened while starting a virtual machine 'VS Emulator 5" Inch Kit Kat(4.4) XXHDPI Phone' virtual Machine ID(.......)

'VS Emulator 5" Inch Kit Kat(4.4) XXHDPI Phone' failed to start worker process: Server Execution failed (0x80080005). Virtual Machine ID (........) Error message Image

My Ram size is 4gb, OS is Windows 8.1 Pro

Thanks for any help.


python:replace characters in file under condition

I am trying to handle a file output.dat by substituting values that exceed 1 with 1.
E.g if the file contains numbers like:

1
2
3
4

I want it the output to be:

1
1
1
1


jQuery (with Django): Appending URL to List with click event

When I add something to the 'patient_medications' list from the medicines list, I want to be able to delete it with the class click event for 'medication-on'.  The click event works for medications that are generated from the original code, but my additions do not delete when clicked.  What am I doing wrong?  Is something wrong with this line?

$('#patient_medications').append('<li><a href="#" class="medication-on" data-cost='+cost+'>'+med_name+'</a></li>');

The link is added but clicking does not cause the event.

I would also appreciate any guidance on the best way to do something like this with a very large amount of medications, say, generate the urls for all medicines from a search box or have a cool widget to select some based on user input.

Thank you.

<ul id='patient_medications'>
{% for med in patient.medications.all %}
       <li><a href="#" class="medication-on" data-cost="{{med.m_cost}}">{{med.name}}</a></li>
{% endfor %}
</ul>
</div>
<h4>Total Cost (30-day supply):</h4>
<div id="costs">
{{sum.m_cost__sum}}
</div>
<h3>Available Medications:</h3>
{% for m in medications %}
    <li><a href="#" class="medication-link" data-cost="{{m.m_cost}}">{{m.name}}</a></li>
{% endfor %}
</div>
<script type="text/javascript">
$('.medication-on').click(function() {
    var link = $(this);
    var cost = link.data("cost");
    var costs = $('#costs');
    var cur_cost = parseFloat(costs.html());
    var result = cur_cost - cost;
    costs.html(result);
    $(this).parent().remove();
    $(this).remove();
});
$('.medication-link').click(function() {
    event.preventDefault();
    var link = $(this);
    var med_name = link.html();
    var cost = link.data("cost");
    $('#patient_medications').append('<li><a href="#" class="medication-on" data-cost='+cost+'>'+med_name+'</a></li>');
    var costs = $('#costs');
    var cur_cost = parseFloat(costs.html());
    var result = cur_cost + cost;
    costs.html(result);
});

</script>
{% endblock %}


XSLT last position within attribute

I need to check whether a node with certain attribute is the last in the loop, and accordingly insert and ampersand before the last node. I tried using the

<xsl:if test="position() = last()">

doesn't seem to take into consideration the attribute value.

Here's the XML

<creators and-others="no">
            <creator type="personal">Roche, R.L.</creator>
            <creator type="personal">Moulin, D.</creator>
            <creator type="personal">James, K.</creator>
            <creator type="affiliation">CEA Centre d'Etudes Nucleaires de Saclay, 91 - Gif-sur-  zYvette (France). Dept. d'Etudes Mecaniques et Thermiques</creator>
</creators>

I need the output as, Roche, R.L., Moulin, D., & James, K.

Also, is there a way, to get the count of values for the "creator" node, with attribute "personal" ?


sql: updating comma separator values

I am looking for answer where i can directly update the comma separated values without splitting the comma values.

For Example:

old value   new value
123     111
234     222
345     333
456     444

Current

id  value
1   123,345
2   123
3   345,456,234

Expected

id  value
1   111,333
2   111
3   333,444,222

I have already used logic of splitting the comma values then updating the new values and then at last using coalesce to club all the new values with comma separator.
Since my count is too big this logic is taking lots of time for execution.

Can anyone please suggest me better solution for this?


Maximize efficiency of SQL SELECT statement

Assum that we have a vary large table. for example - 3000 rows of data.
And we need to select all the rows that thire field status < 4.
We know that the relevance rows will be maximum from 2 months ago (of curse that each row has a date column).

does this query is the most efficient ??

SELECT * FROM database.tableName WHERE status<4

AND DATE< '".date()-5259486."' ;

(date() - php , 5259486 - two months.)...


postgres multiple on conflicts in one upsert statement

I have two unique constraints on the same table, and I want to do an upsert statement on that table.

Is it possible to specify the two conflicts in the upsert? I saw this: How to upsert in Postgres on conflict on one of 2 columns?

but my issue is slightly more involved because one of the unique constraints is a subset of the other unique constraint. I.e.

unique_constraint_1 = (col_1)
unqiue_constraint_2 = (col_1, col_2)

INSERT INTO table (col_1, col_2, col_3) VALUES (val_1, val_2, val_3) ON CONFLICT (what do I put here to account for both constraints?) DO NOTHING;

thanks!


Android Drawables: outofmemoryerror VERSUS "cannot draw recycled bitmaps" error

I've read a ton of posts about both these errors and can't seem to find a solution that works for me.
I have a basic listview activity of animals. When you click on an item in the list, it opens the AnimalViewActivity and displays a simple png image inside an ImageView.

Here's where I set the image for the ImageView:

public void getImage() {

    String imageName = myService.yourAnimals.get(key).getType();
    System.out.println(imageName);

    Resources res = getResources();
    int resourceId = res.getIdentifier(imageName, "drawable", getPackageName() );
    Drawable drawable = res.getDrawable( resourceId );
    image.setImageDrawable( drawable );
}

Then when I leave AnimalViewActivity to return to the listview activity, I do this:

@Override
protected void onDestroy() {
    super.onDestroy();
    //((BitmapDrawable)image.getDrawable()).getBitmap().recycle();
    image.getDrawable().setCallback(null);
    //System.gc();
    System.out.println("Destroy image!");
}

If I uncomment the recycle() line, I get the  "cannot draw recycled bitmaps" error.
If I leave it how it is, I get the  outofmemoryerror for bitmapfactory.

java.lang.IllegalArgumentException: Cannot draw recycled bitmap
OR
java.lang.OutOfMemoryError
android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)

Either one of these errors occur after I've opened the ViewAnimalActivity about 20 times and the app crashes.
The only thing that seems to work forever is System.gc() , but I know that is not a good solution.

I'm testing it in android4.1, but the minSDK is set to android3.0

I read that the javaVM error for bitmap recycling was fixed in 3.0?

For some reason, garbage collection is not happening fast enough without explicitly calling the gc. These images are small, mostly between 100-300kB.

Any ideas?

EDIT:
It seems happier with

image.setImageDrawable( null );

I think I tried this before when I still had it set on Android2.2, but Android3.0 is happy with it so far.


Why does this error occur?

I am getting this error

Argument "\\x{61}" isn't numeric in numeric comparison (<=>)

from

#!/usr/bin/perl

use JSON::PP;
use utf8;
use strict;
use warnings;
use Data::Dumper;

my $json = JSON::PP->new->allow_nonref;
$json = $json->utf8;

my $data = {
        12 => {
                a => 1,
                b => 2,
        },
        1 => {
                    x => 3,
        },
        2 => {
                z => 4,
        }
};

my $json_string = $json->sort_by(sub { $JSON::PP::a <=> $JSON::PP::b })->encode($data);

It is suppose to encode the hash to a json string, and then numeric sort the keys 12 1 2.

If the problem can be solved with another JSON parser, then that would be perfectly fine =)

What's wrong?


How to use "this" in a thread!

I am trying to call my static function using a separate thread, I have in my function something like this->listBox1->Items->Add(s);. The compiler shows that I can't use this inside a static function. I tried to make my function non-static (i.e remove static keyword) but when I did that, again the compiler shows two errors which are:

Error  2   error C3350: 'System::Threading::ThreadStart' : a delegate constructor expects 2 argument(s)    c:\users\ahmed\documents\visual studio 2010\projects\testscan\testscan\Form1.h  116

Error  1   error C2276: '&' : illegal operation on bound member function expression    c:\users\ahmed\documents\visual studio 2010\projects\testscan\testscan\Form1.h  116

Edit:

The function:

void ScanMyDir(String^ SourceDir)
{
    array <String^> ^fileEntries = Directory::GetFiles(SourceDir);
    for each (String^ fileName in fileEntries)
        this->Form1->listBox1->Items->Add(fileName);

    array<String^> ^SubDirEntries = Directory::GetDirectories(SourceDir);
    for each (String^ subdir in SubDirEntries)
        if ((File::GetAttributes(subdir) & FileAttributes::ReparsePoint)!= FileAttributes::ReparsePoint)
            ScanMyDir(subdir);
}

Way to call it:

void button1_Click(System::Object^  sender, System::EventArgs^  e) {
    Thread ^thr1 = gcnew Thread(gcnew ParameterizedThreadStart(this,&Form1::ScanMyDir));
    thr1->Start("c:\\");
}

Modification on Form load:

void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
    System::Windows::Forms::Control::CheckForIllegalCrossThreadCalls = false;
}

The new errors :(  :

Error  5   error C3352: 'void testScan::Form1::ScanMyDir(System::String ^)' : the specified function does not match the delegate type 'void (System::Object ^)'    c:\users\ahmed\documents\visual studio 2010\projects\testscan\testscan\Form1.h  117

Error  1   error C2273: 'function-style cast' : illegal as right side of '->' operator c:\users\ahmed\documents\visual studio 2010\projects\testscan\testscan\Form1.h  105

Error  2   error C2227: left of '->listBox1' must point to class/struct/union/generic type c:\users\ahmed\documents\visual studio 2010\projects\testscan\testscan\Form1.h  105

Error  3   error C2227: left of '->Items' must point to class/struct/union/generic type    c:\users\ahmed\documents\visual studio 2010\projects\testscan\testscan\Form1.h  105

Error  4   error C2227: left of '->Add' must point to class/struct/union/generic type  c:\users\ahmed\documents\visual studio 2010\projects\testscan\testscan\Form1.h  105


Limiting the number of trials in combination Ruby

The following code calculates all the results of 5C4 (5 combination 4) as a string:

a = ['1', '2', '3', '4', '5']
result_array = a.combination(4).map(&:join).to_a

Is there a method I can use to limit the number of combination trials, similarly to the itertools module in Python?


How to separate last three numbers and a string from the rest of the text in excel

I have:

Column 1

Here is line one abc 1 3 100
Here is another line jkmr 5-20 230 3
Other line three rjleer 44 10 22

and want to turn it into:

So far I have this:

=RIGHT(A1,LEN(C1)-FIND("*",SUBSTITUTE(A1," ","*",LEN(A1)-LEN(SUBSTITUTE(A1," ",""))-3)))

that separates the last four strings. Then I can separate them on spaces. But how can I remove these last four strings from from the text?


UIPopoverController arrow not the same white as my UINavigationBar

So the problem that I have is my UIPopoverController's arrow is a different color to my UINavigationBar color. If you look at the image there is a slight shadow on the white and you can see it is not the same white:

This only happens on iOS 8 and not on 7, on 7 it's working as expected.

- (UIPopoverController *)showPopoverController:(UIViewController *)controller fromBarButtonItem:(UIBarButtonItem *)view
{
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
    UIPopoverController *popoverController = [[UIPopoverController alloc] initWithContentViewController:navController];

    //  controller.view.frame = CGRectMake(0, 0, 320, 400);

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

    appDelegate.popoverController = popoverController;
    CGSize size = CGSizeMake(controller.view.frame.size.width, controller.view.frame.size.height + 44.0);
    [navController setPreferredContentSize:size];
    [popoverController setPopoverContentSize:size];
    [popoverController presentPopoverFromBarButtonItem:view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    [navController.navigationBar setBarTintColor:[UIColor whiteColor]];
    [popoverController setBackgroundColor:[UIColor whiteColor]];

    return popoverController;
}


How add domain from iPage to Web app hosted on iis in server 2008?

I want to connect my web app  hosted on IIS in server 2008 with domain from iPage
I do not know how I can connect with domain and open my web app from browser using my domain.


Making Text field empty when clicking on it (Prototype Framework of javascript)

Thats my input field. I want to make value of it empty when I click it. How can I do this by using prototype framework of javascript ?

<input name="ctl0$txtSearch" type="text" value="Quick Search" id="ctl0_txtSearch" class="MainSearchBar" />

Thanks in advance,

Actually I am using PRADO. So the html tag to create input is

   <com:TTextBox Id="txtSearch" Text="Quick Search"  CssClass="MainSearchBar"  />

And it has no onclick attr to handle javascript.


How can I retrieve information for only a specific type of activity from the Pivotal Tracker API?

I am getting JSON information from the Pivotal Tracker API, and I need to get certain info, instead of all the raw data. To do this, I used JSON.parse() to convert the JSON to a Ruby array of hashes.

Now, I need to iterate through this array and only return the relevant hashes.

For example, I just want to return the primary_resources hash that has a nested hash of:

"story_type" => "feature"

To do this, I wrote this code (response.body is the data returned from the GET request):

@data = response.body
parsed = JSON.parse(@data)
puts parsed['primary_resources']['story_type']['feature']

When I run the script, I get this error:

no implicit conversion of String into Integer (TypeError)

It seems that it is iterating through an array of hashes and looking for an integer number of the array (like array[3] or array[0]), but that doesn't help me. I need to return all the hashes that have a nested hash :kind => story in the primary resources hash.

I also tried to do this:

parsed.each do |entry|
  puts entry['primary_resources']['story_Type']['feature']
end

and I got the same error.

Here is my full code:

require 'json'
require 'net/http'
require 'open-uri'
require 'openssl'
require 'active_support'

prompt = '> '
puts "What is the id of the Project you want to get data from?"
print prompt
project_id = STDIN.gets.chomp()
puts "What is the beginning date you want to return from? ex: 2014-07-02"
print prompt
date1 = STDIN.gets.chomp()
puts "What is the end date you want to return from? ex: 2014-07-16"
print prompt
date2 = STDIN.gets.chomp()

def scope(project_id, date1, date2)
  uri = URI.parse("https://www.pivotaltracker.com/services/v5/projects/#{project_id}/activity?occurred_after=#{date1}T01:00:15Z&occurred_before=#{date2}T01:00:15Z&fields=primary_resources")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  request = Net::HTTP::Get.new(uri.request_uri)
  request.add_field("X-TrackerToken", "*****************")
  response = http.request(request)
  @data = response.body
  parsed = JSON.parse(@data)
  puts parsed['primary_resources']['story_type']['feature']
  # parsed.each do |entry|
    # puts entry['primary_resources']['kind']['story']
  # end

  # puts parsed['primary_resources'].select { |r| r['story_type'].eql? 'feature' }
end

scope(project_id, date1, date2)

Here is some of the JSON response, without parsing (full response is too long, and really just the same response for like 15 other user stories):

What is the id of the Project you want to get data from?
> 961142
What is the beginning date you want to return from? ex: 2014-07-02
> 2014-07-02
What is the end date you want to return from? ex: 2014-07-16
> 2014-07-03
[
   {
    "primary_resources": [
      {
        "kind": "story",
        "id": 74313670,
        "name": "User can make an image fit inside the grid when viewing image detail and save it to case template. BUILD 146",
        "story_type": "bug",
        "url": "https://www.pivotaltracker.com/story/show/74313670"
      }
    ],
    "guid": "961142_3419",
    "project_version": 3419
  },

Here is some of the JSON response, after parsing (only showing first story for same reason as above):

What is the id of the Project you want to get data from?
> 961142
What is the beginning date you want to return from? ex: 2014-07-02
> 2014-07-02
What is the end date you want to return from? ex: 2014-07-16
> 2014-07-03
{"primary_resources"=>[{"kind"=>"story", "id"=>74313670, "name"=>"User can make an image fit inside the grid when viewing image detail and save it to case template. BUILD 146", "story_type"=>"bug", "url"=>"https://www.pivotaltracker.com/story/show/74313670"}], "guid"=>"961142_3419", "project_version"=>3419}

How can I iterate through this array of hashes and return only the ones of "story_type"=>"feature" ?


How to auto-format javascript to align multiple lines with require() statements

I am using js-beautify from einars, and I am trying to
configure the options to achieve the following format:

var a                   = require("lib-a"),
    alongvariable       = require("another-lib-a");

or

var a                   = require("lib-a");
var alongvariable       = require("another-lib-a");

Does a combination of option would allow to produce this layout ?


instanceID return nil in real device but wasn't nil in simulator in ios

I using fcm for push notification.
I develop completely FCM on my project and i follow step by step of tutorial of firebase
(my language is objective - c)
my device token is generated, but instanceID not generated !! in other words refreshToken Method not called ever !.
now when i run my project in simulator instanceID was generated. but when i run my project in real Device instanceID return null !!
my time & date in real device is up to date but still not working !! it's log of my console when run project in simulator :

log for simulator.

and this log when run my project in a real device :

2017-04-12 16:53:44.504 pin-Go[1031] <Notice> [Firebase/Analytics][I-ACS023012] Firebase Analytics enabled
2017-04-12 16:53:44.546831+0430 pin-Go[1031:175957] APNs token retrieved: <f73de751 b71d59b8 f1e3b83a 826646ba d6338e7c a1a062be 4adda159 83cb5fa5>
2017-04-12 16:53:44.804239+0430 pin-Go[1031:175957] animating is complited ..
2017-04-12 16:53:44.804639+0430 pin-Go[1031:175957] animating is complited.
2017-04-12 16:53:45.124628+0430 pin-Go[1031:175957] animating1 ...
2017-04-12 16:53:45.751638+0430 pin-Go[1031:175957] Connected to FCM.
2017-04-12 16:53:45.755046+0430 pin-Go[1031:175957] InstanceID token: (null)

and my code is Exactly like this code : https://github.com/firebase/quickstart-ios/blob/master/messaging/MessagingExample/AppDelegate.m

and my log don't show any error for that ...
anyone can help me pls ??

Edit : That is my code :

  #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
    @import UserNotifications;
    #endif
    @import GoogleMaps;
    @import GooglePlaces;
    #import "AfzayeshMojodiViewController.h"
    #import "ChangeInfoViewController.h"
    #import "MasirMontakhaViewController.h"
    @import Firebase;

    // Implement UNUserNotificationCenterDelegate to receive display notification via APNS for devices
    // running iOS 10 and above. Implement FIRMessagingDelegate to receive data message via FCM for
    // devices running iOS 10 and above.
    #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
    @interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
    @end
    #endif
    // Copied from Apple's header in case it is missing in some cases (e.g. pre-Xcode 8 builds).
    #ifndef NSFoundationVersionNumber_iOS_9_x_Max
    #define NSFoundationVersionNumber_iOS_9_x_Max 1299
    #endif

    @implementation AppDelegate
    NSString *const kGCMMessageIDKey = @"gcm.message_id";

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        self.urlStrWebService = [[NSString alloc] init];

        //Start of GCM
        // [START configure_firebase]
        [FIRApp configure];

        if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
            UIUserNotificationType allNotificationTypes =
            (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
            UIUserNotificationSettings *settings =
            [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
            [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        } else {
            // iOS 10 or later
    #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
            // For iOS 10 display notification (sent via APNS)
            [UNUserNotificationCenter currentNotificationCenter].delegate = self;
            UNAuthorizationOptions authOptions =
            UNAuthorizationOptionAlert
            | UNAuthorizationOptionSound
            | UNAuthorizationOptionBadge;
            [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
            }];

            // For iOS 10 data message (sent via FCM)
            [FIRMessaging messaging].remoteMessageDelegate = self;
    #endif
        }

        [[UIApplication sharedApplication] registerForRemoteNotifications];
  return YES;
}

//start implementing notification reciver :

//// [START receive_message]
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification

    // Print message ID.
    if (userInfo[kGCMMessageIDKey]) {
        NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
    }

    // Print full message.
    NSLog(@"%@", userInfo);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification

    // Print message ID.
    if (userInfo[kGCMMessageIDKey]) {
        NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
    }

    // Print full message.
    NSLog(@"%@", userInfo);

    completionHandler(UIBackgroundFetchResultNewData);
}
// [END receive_message]

// [START ios_10_message_handling]
// Receive displayed notifications for iOS 10 devices.
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// Handle incoming notification messages while app is in the foreground.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    // Print message ID.
    NSDictionary *userInfo = notification.request.content.userInfo;
    if (userInfo[kGCMMessageIDKey]) {
        NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
    }

    // Print full message.
    NSLog(@"%@", userInfo);

    // Change this to your preferred presentation option
    completionHandler(UNNotificationPresentationOptionNone);
}

// Handle notification messages after display notification is tapped by the user.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)())completionHandler {
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    if (userInfo[kGCMMessageIDKey]) {
        NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
    }

    // Print full message.
    NSLog(@"%@", userInfo);

    completionHandler();
}
#endif
// [END ios_10_message_handling]

// [START ios_10_data_message_handling]
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// Receive data message on iOS 10 devices while app is in the foreground.
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
    // Print full message
    NSLog(@"%@", remoteMessage.appData);
}
#endif
// [END ios_10_data_message_handling]

// [START refresh_token]
- (void)tokenRefreshNotification:(NSNotification *)notification {
    // Note that this callback will be fired everytime a new token is generated, including the first
    // time. So if you need to retrieve the token as soon as it is available this is where that
    // should be done.
    NSString *refreshedToken = [[FIRInstanceID instanceID] token];
    NSLog(@"InstanceID token: %@", refreshedToken);

    // Connect to FCM since connection may have failed when attempted before having a token.
    [self connectToFcm];

    // TODO: If necessary send token to application server.
}
// [END refresh_token]

// [START connect_to_fcm]
- (void)connectToFcm {
//    // Won't connect since there is no token
//    if (![[FIRInstanceID instanceID] token]) {
//        return;
//    }

    // Disconnect previous FCM connection if it exists.
    [[FIRMessaging messaging] disconnect];

    [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
        if (error != nil) {
            NSLog(@"Unable to connect to FCM. %@", error);
        } else {
            NSLog(@"Connected to FCM.");
            NSString *refreshedToken = [[FIRInstanceID instanceID] token];
            NSLog(@"InstanceID token: %@", refreshedToken);
        }
    }];
}
// [END connect_to_fcm]

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"Unable to register for remote notifications: %@", error);
}

// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
// the InstanceID token.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"APNs token retrieved: %@", deviceToken);

    // With swizzling disabled you must set the APNs token here.
     [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
    [self connectToFcm];
}

// [START connect_on_active]
- (void)applicationDidBecomeActive:(UIApplication *)application {
    [self connectToFcm];
}
// [END connect_on_active]

// [START disconnect_from_fcm]
- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[FIRMessaging messaging] disconnect];
    NSLog(@"Disconnected from FCM");
}
// [END disconnect_from_fcm]

//end of implement notification.


Error in .Net Web Service running on IIS 6

I am trying to run a web service build in .Net on IIS 6 server.
But it is giving an Error while starting Web Service

ERROR

Server Error in ' /9448' Application

Configuration Error

Description :  "An error occurred during the processing of configuration file required to service this request.Please review the
  specific details below and modify your configuration file
  appropriately.

Parse Error Message :An error occurred loading the configuration file: Access to the path
  "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Config\machine.config"
  is denied.

Source Error:

[No relevant source lines]

Source File : C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Config\machine.config
  Line: 0

Version Information : Microsoft.NET Framework Version v2.0.50727.3625; ASP.Net Version : v2.0.50727.3625

The user under which it is running have full Administrator Rights

While it was working fine previously

What could be the problem?


Google DirectoryAPI adding wrong email

Google's Directory API incorrectly adding the personal gmail address to a google group when I use the api to insert a non-gmail address. This only happens for a subset of addresses for several domains @indiana.edu, @arizona.edu... (I assume it is connected to the organizations own use of GoogleApps).

I can reproduce the issue using the Google-Api-Explorer, without any code, but I noticed the issue using google-api-php-client.

$gData = $this->service->members->insert($groupEmail,$gMember);

I have filed a ticket with Google. Has anyone encountered this issue, or can you shed light into how a personal gmail account is linked to an @organizatio.edu account in GoogleApps.


Mapping any OS's global input events to another input events with Java

I couldn't come up with a better title, so allow me to elaborate:

There are programs such as JoyToKey, that allowed the user to map button inputs on any joystick to any key event and mouse event. To be frank, I do not know the real underlying implementation here, but it is like either JoyToKey "ubiquitously" sends these mapped inputs to whatever application the user is focusing, or it simply invokes global input events.

So the thing is this, in Java application, if we want to listen to any keyboard or mouse input, we can easily to do that with the KeyListener and MouseListener classes, but what I am talking here is if I want to create a Java application that listens to all of the user's specified inputs, (be it from joystick, touch screen, or whatever) regardless of which application has focus at the time and map these inputs to other inputs and macro. For instance, if I want to perform Hadoken in Street Fighter, I tell the program "hey, if I press 'P' or 'Joystick 1 Button 10', invoke the following keyboard events respectively 'down arrow' in the first (1/60) millisecond, 'down+right arrow' in the next (1/60) millisecond, 'right arrow' in the next (1/60) millisecond and finally 'Z' in the next (1/60) millisecond".

So what I am looking for here is different from JoyToKey in the following aspect:

I am looking for how to write a JoyToKey-like program in Java.

not limited to Joystick only. Allows user to map all sort of hardware inputs to any other hardware input as well.

Due to the nature of Java and we are invoking the OS directly, I am concern about the cross-platform capability. The underlying mechanism of each OS might be a little different, but anyway, is this possible in Java? If so, which Java's API should I be looking for? Are there some hardware-specific problems to be aware of?


Jackson JsonNode and Java Streams to return Optional Empty

So I have a json input, something like this:

{
    "a":"something",
    "b":"something2"
}

This input can come in 2 other forms:

{
    "a":"something",
    "b":""
}

And

{
    "a":"something"
}

I have a input class like this that I store it in:

public class Foo {
    private String a;
    private Optional<String> b;
}

In the latter 2 cases I want to store b as Optional.empty(). I have figured out how to do that in the 3rd case with this line of code:

Optional.ofNullable(inputNode.get("b")).map(node -> node.asText())

This works well for the 3rd case. It returns Optional.empty. But not so much for the 2nd case because b ends up just being an empty string. I tried to use .reduce before and after the .map but for some reason it won't let me use that anywhere.

And idea how to achieve what I want?


CSS - How to insure that a input will be in the middle of a specific area

I'm having a simple row with three utf-8 arrows

<div id="container">
  <div id="one">&#9660;</div>
  <div id="two">&#9650;</div>
  <div id="three">&#9660;</div>
</div>

So what I am trying to do is to have the arrows in the same row, but I want them to be in the middle of their height and their width - no matter what text size value they will get.

I've tried the next CSS code -

#container{
display: inline-block;
height: 80px;
width: 100%;
}

#one{
float:left;
width: 20%;
font-size: 90px;
}

#two{
float:left;
width: 20%;
font-size: 50px;
}

#three{
float:left;
width: 20%;
font-size: 60px;

}

As you can understand it sure don't work, any ideas what can I do?
Thanks for any kind of help


one to one result in mysql Query

I have two table:

career

career_details

Table "career" contain fields (careerID,job_code)

Table "career_details" contain fields (id, careerID, name)

Let the values be [(1,code1),(2,code2)]--- career(table)

Let the values be

[

 ('1','1','codename1'),
   ('2','1','codename11'),
   ('3','2','codename22'),
   ('4','2','codename222')

]

-- career_details(table)

Now if I write the query("SELECT * FROM career c LEFT JOIN career_details cd ON c.career_id=cd.career_id WHERE 1"), then it will give the result 4 rows but I need the result 2 rows only i.e

[(1,code1,1,1,codename1),(2,code2,3,2,codename22)]


Remove white space between two divs

How to remove the white space between the header and wrapper divs.

Here is a DEMO fiddle.
Here is the HTML code :

 <div id="container">
    <div id="header">
        <div id="logo">
        </div>
        <div id="login">
            <h3>
                CLIENT LOGIN</h3>
            Username
            <input type='text' name='username' id='username'>
            <input type='button' name='login' value='Login' id='btnLogin'>
            <br />
            Password:
            <input type='password' name='password' id='password'>
            <input type='button' name='register' value='Register' id='btnRegister'>
        </div>
        <div id="navigation">
            <ul>
                <li class="active"><a href="#">Home</a></li>
                <li><a href="#">Profile</a></li>
                <li><a href="#">Contact</a></li>
                <li><a href="#">Group</a></li>
                <li><a href="#">Seminar</a></li>
            </ul>
        </div>
    </div>
    <div id="wrapper">
        <div id="contents">
            <div id="welcome">
                <h3>
                    Welcome to Somara</h3>
                <p>
                    It is a long established fact that a reader will be distracted by the readable content
                    of a page when looking at its layout.</p>
                <p>
                    There are many variations of passages of Lorem Ipsum available.</p>
            </div>
        </div>
    </div>
    <div id="footer">
    </div>
</div>

Here is the CSS code:

    body
{
    width:100%;
    margin:0px;
}

#header
{
    width: 100%;
    background-color: #2c2520;
    min-height: 200px;
}
#login
{
    float: right;
    color: white;
}
#logo
{
    background-image: url('../img/logo.png');
    min-height: 191px;
    min-width: 230px;
    float: left;
    background-repeat: no-repeat;
}
#navigation
{
    padding-top: 158px;
    margin-right: -200px;
    float: right;
}
#navigation li
{
    display: inline;
    min-width: 100px;
    padding: 5px 5px 5px 5px;
}

#navigation a
{
    text-decoration: none;
    font-family: Tahoma, calibri;
    font-size: 15px;
    color: #f8f8f8;
}
.active
{
    background-color: #afaba5;
    color: black;
}

.inactive
{
    color: white;
    background-color: #392f2b;
}

#contents
{
    width: 950px;
    margin: 0px;
    min-height: 700px;

}

#wrapper
{
    width: 100%;
    margin: 0 auto;
    background-color: #39302b;
}

#intro1
{
    min-width: 30%;
    max-width: 35%;
    min-height: 250px;
    float: left;
    padding: 10px;
    padding-right: 50px;
    padding-left: 50px;
    color: #cdcdcd;
}

#welcome
{

}

#welcome h3, p
{
    font-family: Myriad Pro;
    color: white;
    text-align: center;
    font-weight: normal;
}

#welcome p
{
    color: #cdcdcd;
    font-size: 20px;
}


From which api should i ask permissions?

Hey I am trying to ask for storage access permission and I notice that in my other phone which has android 5.0 the permission ask crashes the app. what should I do to ask permission without crashing the app in this android version and from which android version should I do it?

this is the code for asking permission:

  int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 0;
    if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
        != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (shouldShowRequestPermissionRationale(
            Manifest.permission.READ_EXTERNAL_STORAGE)) {
        // Explain to the user why we need to read the contacts
    }

    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
            MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

    // MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
    // app-defined int constant that should be quite unique

    return;
}


Looping over descending values in Stata using forvalues

So this works as expected:

. forvalues i = 1(1)3 {
  2. di `i'
  3. }

1

    2

    3

And this doesn't:

. forvalues i = 3(1)1 {
  2. di `i'
  3. }
           <--- that's an empty line that returns from the above loop.

If I want to produce

3
2
1

do I really need to get this belabored?

. forvalues i = 1(1)3 {
  2. di 3+1-`i'
  3. }

Why?


GitHub API: finding number of stars,commits and releases

I'm making Android app that use GitHud API. The target -- make list with repositories info of githubuser. I use GET /users/:username/repos. But there no all info I need. Maybe someone know how can I get this info for the list of repositories.


Navigation Timing API. What's going on between domContentLoadedEventStart and domContentLoadedEventEnd?

W3C specifies a list of event and their corresponding timings that user agents must return if they want to support the Navigation Timing API.

A list you can see here: http://www.w3.org/TR/navigation-timing/#process

Understanding which process relates to which events is pretty straight forward in most cases. But one thing that eludes me is what is going on between domContentLoadedEventStart and domContentLoadedEventEnd.

Here is what I have understood so far and base my reflections on:

domLoading // The UA starts parsing the document.

domInteractive // The UA has finished parsing the document. Users
can interact with the page.

domContentLoaded // The document has been completely loaded and
parsed and deferred scripts, if any, have executed. (Async scripts,
if any, might or might not have executed???)

domComplete // The DOM Tree is completely built. Async scripts, if
any, have executed.

loadEventEnd // The UA has a fully completed page. All resources,
like images, swf, etc, have loaded.

One should be able to deduce what happens after phase #3 (domContentLoaded) by understanding what triggered event #4 (domComplete) but did not trigger previous events.

So one would think that “Async scripts, if any, have executed” means that asynchronous scripts get executed after phase #3 but before event #4. But according to my tests, this is not what happens, unless my test is wrong. (I tried to replicate my test on JSFiddle, but I can’t make the defered/async script work since there is no way to add attribute on external scripts.)

So my question is: What process(es) takes place between domContentLoadedEventStart and domContentLoadedEventEnd?


Depth-first search algorithm implementation

The following C++ Depth-first search program won't compile.

#include <iostream>
using namespace std;

class Stack
{

private:
      const int size=20;
      int *st;
      int top;
public :
      Stack(){
    st =new int[size];
    top=-1;

      }
      ~Stack(){
          delete[] st;
          top=-1;
      }
      void push(int j){
          st[++top]=j;
              }
      int pop(){
          return st[top--];
      }
      int peek(){

          return st[top];

      }
       bool empthy(){
           return (top==-1);

       }
};
class Vertex{
public:
    char  label;
    bool visited;
public:
    Vertex(){

    }
    Vertex(char lab){
        label=lab;
        visited=false;

    }
    };
class Graph{
private:
      const int maxvertex=20;
      Vertex* vertexlist;
      int **adj;
        int nverts;
        Stack *stack;
public:
    Graph(){
    vertexlist=new Vertex[maxvertex];
    adj=new int*[maxvertex];
     for (int i=0;i<20;i++)
          adj[i]=new int[maxvertex];
     nverts=0;
      for (int i=0;i<maxvertex;i++){
           for (int j=0;j<maxvertex;j++){
               adj[i][j]=0;
           }
           }

         stack=new Stack();
    }
    void add(char lab){

        vertexlist[nverts++]=new Vertex(lab);
    }1

};
int main(){

    return 0;
}

Here are the compilation errors I am getting:

>   6   IntelliSense: no operator "=" matches these
> operands  c:\users\datuashvili\documents\visual studio
> 2010\projects\dfs\dfs\dfs.cpp 76  23  DFS     7   IntelliSense: expected a
> declaration   c:\users\datuashvili\documents\visual studio
> 2010\projects\dfs\dfs\dfs.cpp 77  3   DFS Error   1   error C2864:
> 'Stack::size' : only static const integral data members can be
> initialized within a class    c:\users\datuashvili\documents\visual
> studio 2010\projects\dfs\dfs\dfs.cpp  8   1   DFS Error   3   error C2864:
> 'Graph::maxvertex' : only static const integral data members can be
> initialized within a class    c:\users\datuashvili\documents\visual
> studio 2010\projects\dfs\dfs\dfs.cpp  54  1   DFS Error   2   error C2758:
> 'Stack::size' : must be initialized in constructor base/member
> initializer list  c:\users\datuashvili\documents\visual studio
> 2010\projects\dfs\dfs\dfs.cpp 12  1   DFS Error   4   error C2758:
> 'Graph::maxvertex' : must be initialized in constructor base/member
> initializer list  c:\users\datuashvili\documents\visual studio
> 2010\projects\dfs\dfs\dfs.cpp 60  1   DFS Error   5   error C2679: binary '='
> : no operator found which takes a right-hand operand of type 'Vertex
> *' (or there is no acceptable conversion) c:\users\datuashvili\documents\visual studio
> 2010\projects\dfs\dfs\dfs.cpp 76  1   DFS


Adobe air 3.0 ANE for Android, null ExtensionContext?

I've been working with the vibration example from Adobe for Air 3.0's native extensions on Android.

I have the ANE compiled and the .apk packaged.

The problem I'm having is the actionscript library is getting a null ExtensionContext.

I tried creating the .apk with adt -package -target apk-debug so that I can see the actionscript traces in logcat and that's where I'm finding the null error.

extContext = ExtensionContext.createExtensionContext("com.adobe.Vibration", null);

extContext is null and crashes on the following .call() method.

All of the source is stock from the examples, I haven't changed anything.

Does anyone have any experience with getting one of Adobe's ANE examples working on a windows machine? Most of the examples are for Mac.


How to multiply 4 number in assembly language using 8bit and Shift.
I am able to multiply 2 but how to multiply 4 number
Eg 2 4 5 6

this is code of two digit multiplication :

[org 0x100]
multiplicand: db 13
multiplier: db 5
result: db 0
mov cl, 4
mov bl, [multiplicand]
mov dl, [multiplier]
checkbit: shr dl, 1
jnc skip
add [result], bl
skip: shl bl, 1
dec cl
jnz checkbit
mov ax, 0x4c00
int 0x21


ASP.NET Webapplication avoid page reload for culture language change

I'm trying to make a multilanguage ASP.NET web Application. At the beginning of the Application I'm setting up cookies and after that I'm calling InitializeCulture() to initiate the culture. The data for the page is stored in global resources and gets written in the aspx file like this: <%$ Resources:Main,lang %>

It is actually working but there is still a problem: After a click on a languagechange button the coockie and the culture changes but not the content of the page. I always have to reload the whole page to get the content of the right global.resx.

In PageLoad im calling this:

            setLanguageCookie(); //<- TO SET A COOKIE IF NULL
            InitializeCulture();

InitializeCulture() looks like this:

        string sprache = "en-US";

        if (Request.Cookies["sprache"] != null)
        {
            sprache = Request.Cookies["sprache"].Value;
        }

        Thread.CurrentThread.CurrentCulture =
          CultureInfo.GetCultureInfo(sprache);

        Thread.CurrentThread.CurrentUICulture =
          CultureInfo.GetCultureInfo(sprache);

There are 3 Language buttons. Their code behind look like this:

protected void lang_en_Click(object sender, EventArgs e)
        {
            Request.Cookies["sprache"] = "en-US";
            Session["Language"] = "en";
        }

Can someone give me a hint where I am mistaking? O is there even a better way to do that??


How can Perl's system() print the command that it's running?

In Perl, you can execute system commands using system() or `` (backticks). You can even capture the output of the command into a variable. However, this hides the program execution in the background so that the person executing your script can't see it.

Normally this is useful but sometimes I want to see what is going on behind the scenes. How do you make it so the commands executed are printed to the terminal, and those programs' output printed to the terminal? This would be the .bat equivalent of "@echo on".


AutoMapper for a list scenario only seems to repeat mapping the first object in the list

I am developing an MVC 3 application and am using AutoMapper to move data between my ViewModels and my entities.  I have a scenario where I need to move data between two lists.  For some strange reason, AutoMapper seems to only copy the first object from the source object and then seems to copy the same object n times over to the destination list.  For example, say you have 2 lists, source contains six entity items and destination contains 0 items as it was just instantiated.  The item at position source[0] get copied over to the destination and then source[0] is copied repeatedly for the same number of items there are in the source List, in this case 6.  I don't understand what could be the cause of this.

Here is the AutoMapper configuration file:

public static class AutoMapperConfigurator
{
    public static void Configure()
    {
        Mapper.CreateMap<User, UserModel>();
        Mapper.CreateMap<Posting, PostingModel>();
    }
}

Here is the Global.asax file setting

protected void Application_Start()
{
    AutoMapperConfigurator.Configure();
}

Here is the location where I am calling the Map method

userSearchModel.UserList = Mapper.Map<IList<User>, IList<UserModel>>(userEntities);


json.net limit maxdepth when serializing

We're using Asp.Net WebAPI with Entity Framework (with lazy loading) and using Json.net for serializing the data to json before returning the data to the client.

We are experiencing intermittent sudden spikes in memory usage which we suspect might originate with json.net not recognizing reference loops when serializing data (since Entity Framework might be doing some lazy loading voodoo with proxy classes which goes under the radar of json.net)

I thought I'd limit how deep Json.net was allowed to go to serialize data (at least then we'd get a sensible exception when this happens so we could fix it in the data model), but I soon discovered that the MaxDepth property of JsonSerializerSettings only kicks in when DEserializing objects.

Is there any known way of imposing a limit on json.net when serializing?


Unable to locate an element with the xpath expression

Unable to locate the below xpath in selenium webdriver.

it doesn't contain id and also tried with css selector but no change

Xpathe:- /html/body/div/div/ng:view/div/div/div[2]/div/div[3]/div/nav/div[2]/div/ul/li[2]/a

css selector:-html body.ng-scope
 div div.container ng:view.row div.ng-scope
div.container
div.tabbable
div.tab-content
div.tab-pane
div.ng-scope nav.navbar
div.collapse
div.nav ul.dropdown-menu li a.ng-binding.

Please let me know if any one faced this type of issue.


How to get different languages for current location?

How to get current location in different language.Do we need to add some libraries?I need to find the current address in arabic language? I think there is google maps in arabic format.Similarily is there any way to get current address in arabic lamguage??

public static final String GOOGLE_GEOCODER = "http://maps.googleapis.com/maps/api/geocode/json?latlng=";

public static String getAddressFromGPSData(double lat, double longi) {
    HttpRetriever agent = new HttpRetriever();
    String request = GOOGLE_GEOCODER + lat + ","
            + longi + "&sensor=true";
    // Log.d("GeoCoder", request);
    String response = agent.retrieve(request);
    String formattedAddress = "";
    if (response != null) {
        Log.d("GeoCoder", response);
        try {
            JSONObject parentObject = new JSONObject(response);
            JSONArray arrayOfAddressResults = parentObject
                    .getJSONArray("results");
            JSONObject addressItem = arrayOfAddressResults.getJSONObject(0);
            formattedAddress = addressItem.getString("formatted_address");
        } catch (JSONException e) {

            e.printStackTrace();
        }

    }

    // Log.d("GeoCoder", response);
    return formattedAddress;
}


Adding Adobe Edge Scripts into Rails Asset Pipeline

This is likely a simple case of bringing external scripts with dependencies into Rails.

I'm trying to get my Adobe Edge generated Animations to work within my Rails app and the first step is to include all of Adobe Edge's generated js files, but so far I'm just getting a bunch of 404 Not Found Errors for all of the Edge files I've included in the Application.js file.

Here's my Application.js file

//= require jquery
//= require jquery_ujs
//= require underscore
//= require backbone
//= require california_internet
//= require hero_edgePreload
//= require edge_includes/edge.1.5.0.min
//= require hero_edge
//= require hero_edgeActions

Here is how Edge's Preloader.js is trying to find some of the files...

aLoader=[{load:"edge_includes/jquery-1.7.1.min.js"},{load:"edge_includes/edge.1.5.0.min.js"},{load:"hero_edge.js"},{load:"hero_edgeActions.js"}]


can't get css style's working on input type tel/number only

I'm having some real problems getting input type=tel or input type=number to work on every mobile device. It looks fine on Samsgung s7, iphone 6, hell even an LG K500K. But won't work on my HTC M9 or a Samsung Note. I've checked versions of androids and it seems fine one is using 6.0.1 and the other is on 6.0. I've tried using both a class and also input[type=tel/number] and even just input on it's own :( i looked around online for hours and couldn't find one person who's experiencing this same incosistency. Does anybody have any advice


MySQL is not working after resizing EC2 instance

I have configured separate MySQL Production server as EC2- m2.xlarge. This is ubuntu server.MySQL is working perfectly from 3 years on this instance.

But now I thought of downgrading a server because of less usage. When I stepped ahead to downgrade the server as m1.medium or m1.small using steps given by AWS , I was able to resize it and started it with reassigning my original elastic IP, I found MySQL is now connecting from anywhere.

I troubleshooted to connect MYSQL after resize as follows.

1. connected with ssh login on same instance and used command-line to connect.

2. Tried from outside(workbench) with same configuration..

3. Checked security groups assigned to instance. those are also in place..

4. But when I again resize instance with original (m2.xlarge), It works .

Still no success. any thing I missed after resizing process?


Hello i have array and i want to explode 1 item into it and i want to check if variable not null or null and gives me that error

Initializer for conditional binding must have Optional type, not 'String' Variable Error

My codes here.

 var myStringArrctakesf = itemListcomming.components(separatedBy: ",")

    if let commingtel = myStringArrctakesf[11] {

 //notnull
    } else {

//null
    }

I want if myStringArrctakesf[11] is null dont crash app and if not null show variable.

Thanks


How can I call functions in different orders in PHP?

I am making a way to organize user into groups and need a way to check them. For example I have a method to check gender, which return true if there is no gender imbalance and false if there is. I also have similar methods to check age distribution and to check genders. For each of these methods I have a method which makes an optimized array of groups.

I.e. i have a method which optimizes groups based on gender. I would only call one of these methods if the respective check returns false. The problem I am running into is that when I optimize the groups based on a specific criterion i.e. gender, there is a chance that the new optimized groups have messed up another check criterion.

For example, if I check age, gender and skill level (my third check) and I find that there is an imbalance in age, proceed to optimize the groups with respect to age, then I could potentially mess up gender or skill level distributions. My solution to this problem was that If I could find a way call all variations of the check methods and break if a check all method returned true (all checks return true, all groups have good balances of age, gender and skill level).

Ex:
Let A, B and C be check methods and optimize_A, optimize_B, optimize_C be the make optimized group methods. I need some way loop through the check methods 3! times (because there are 3 check methods and I need to run ABC, ACB, BAC, BCA, CAB, CBA). OR I could do a while loop and break if the method check all () returns true (all checks return true, all have good distributions) and break once I have run the all the combinations of the check methods.

Could anyone help me with this problem? Please bear in mind I am a novice programmer and have never done anything like this before. Thanks

Edit:

How could I do something like this JavaScript code snippet in php?

var arr = [check1, check2, check3],
    rand = Math.floor(Math.random() * arr.length),
    func = arr[rand];
func();

Here is my attempt:

<?php

$checks_to_run = array('check_gender','check_age','check_skill_level');
$rand = floor(rand(0, count($checks_to_run) - 1));
$func = $checks_to_run[$rand];
echo $this->.$func.($tmp); // $tmp is an array of groups

?>


Javascript Prompt inside loop

for (var j=0; j<2; j++){
listno=prompt("Enter Item Code","0");
listno = parseInt(listno);

if (listno > 0) {
    PRODUCT_WANT.push(PRODUCT_LIST[listno]);
    WANT_PRICE.push(PRICE_LIST[listno]);
}

else {
alert('Invalid Product Code');
}
if (quantno > 0) {
    quantno=prompt("Enter Quantity","0");
    quantno = parseInt(quantno);
    quantity.push(quantno);
}

else {
alert('Invalid Quantity');
}
}

The loop works but I don't want to have to set the loop count I want to be able  to put it to eg 999 then be able to press cancel on the prompt and have the loop finish


Image is not displaying in the view ASP.NET MVC

I am trying to upload and retrieve image from SQL server database. I created model, Controller and view as below.

Viewmodel is very similiar to actual modal

CheckoutModel.cs

public class CheckOutViewModel
{
    public int ID { get; set; }
    public ApplicationUser CandidateId { get; set; }
    [Required]
    public byte[] Image { get; set; }
}

Also i created a controller to upload and display images with action methods namely index, create and retreive

Index method is used to display images , create method is used to upload and save image in database and retrieve method is used to query the image according to its id.

CheckOutController.cs

using Microsoft.AspNet.Identity;
using shanuMVCUserRoles.Repositories;
using shanuMVCUserRoles.ViewModels;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace shanuMVCUserRoles.Models
{
    public class CheckOutController : Controller
    {
        private readonly ApplicationDbContext db;
        public CheckOutController()
        {
            db = new ApplicationDbContext();
        }

        [Route("Index")]
        [HttpGet]
        public ActionResult Index()
        {
            var content = db.Checkouts.Select(s => new
            {
                s.ID,
                s.CandidateId,
                s.Image,
            });

            List<CheckOutViewModel> contentModel = content.Select(item => new CheckOutViewModel()
            {
                ID = item.ID,
                CandidateId = item.CandidateId,
                Image = item.Image,
            }).ToList();
            return View(contentModel);
        }

        public ActionResult RetrieveImage(int id)
        {
            byte[] cover = GetImageFromDataBase(id);
            if (cover != null)
            {
                return File(cover, "image/jpg");
            }
            else
            {
                return null;
            }
        }

        public byte[] GetImageFromDataBase(int Id)
        {
            var q = from temp in db.Checkouts where temp.ID == Id select temp.Image;
            byte[] cover = q.First();
            return cover;
        }

        // GET: CheckOut
        [Authorize]
        public ActionResult Create()
        {
            return View();
        }

        [Route("Create")]
        [HttpPost]
        public ActionResult Create(CheckOutViewModel model)
        {
            HttpPostedFileBase file = Request.Files["ImageData"];
            CheckOutRepository service = new CheckOutRepository();
            int i = service.UploadImageInDataBase(file, model);
            if (i == 1)
            {
                return RedirectToAction("Index");
            }
            return View(model);
        }

    }

}

Then i created a repository folder to save images and fields in database and also a method for converted image to bytes.

CheckoutRepostiory.cs

public class CheckOutRepository
{
    private readonly ApplicationDbContext db;
    public CheckOutRepository()
    {
        db = new ApplicationDbContext();
    }
    public int UploadImageInDataBase(HttpPostedFileBase file, CheckOutViewModel contentViewModel)
    {
        contentViewModel.Image = ConvertToBytes(file);
        var userId = HttpContext.Current.User.Identity.GetUserId();
        var member = db.Users.Single(u => u.Id == userId);
        var Content = new CheckOut
        {
            CandidateId = member,
            Image = contentViewModel.Image
        };
        db.Checkouts.Add(Content);
        int i = db.SaveChanges();
        if (i == 1)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }
    public byte[] ConvertToBytes(HttpPostedFileBase image)
    {
        byte[] imageBytes = null;
        BinaryReader reader = new BinaryReader(image.InputStream);
        imageBytes = reader.ReadBytes((int)image.ContentLength);
        return imageBytes;
    }
}

Also i created the index view and then i placed the image in image tag using the for each loop.

Index.cshtml

@foreach (var item in Model)
{
    <tr>
        <td>
            <img src="/Content/RetrieveImage/@item.ID" alt="" height=100 width=200 />
        </td>
    </tr>
}


Kindle Silk Browser: Set focus on a textbox

This is my first post, so I hope it finds it's way to the correct forum.

I created a web page with a SQL backend to capture the start time for a production job.  There is only one textbox on the page.  After the timestamp is saved, the focus is directed back to the textbox so that the next timestamp can be entered.  It works fine for the browsers on my PC..I've tested it in IE and Chrome both.

However, the end user will be using a Kindle Fire HD tablet to input data.  The form displays properly on Kindle's Silk Browser, but the focus doesn't set on my textbox.  I have to use my finger to press inside the textbox in order for the cursor to appear.

I wrote code in both C# and JS to set the focus on my textbox, but neither approach worked on the Silk Browser.  Again, it works fine on my PC for IE and Chrome.

I mostly work with SQL and I'm just starting to branch out into .net and C#.  If someone could point me in the right direction, I would certainly appreciate it.  Thanks!

void btnSave_Click(object sender, EventArgs e) {
cmd = new SqlCommand("UpdateEndTime_sp", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@WorkOrderNum", SqlDbType.Int).Value = tbWorkOrderNum.Text; con.Open();
cmd.ExecuteNonQuery();
con.Close();
tbWorkOrderNum.Text = "";
Label1.Visible = true;
tbWorkOrderNum.Focus();

Javascript:

if (document.getElementById("Textbox1").value == "") {
  document.getElementById("Textbox1").focus();
}


Google Map is not getting displayed in xcode5

I am using xcode 5, I am creating a map view using google map api, using the link https://developers.google.com/maps/documentation/ios/start#getting_the_google_maps_sdk_for_ios
i am using google maps SDK 1.7.0.

When I move to the mapView, in my log, it is getting printed as

Cannot find executable for CFBundle 0xc540670 </Users/wifin/Library/Application Support/iPhone Simulator/7.0.3/Applications/5C049949-8859-4542-A434-F35A3A193356/MaaramaWines.app/GoogleMaps.bundle/GMSCoreResources.bundle> (not loaded)

Google Maps SDK for iOS version: 1.7.0.7198

But, the map is not getting displayed in the view, can anyone help me


Upgrading a code signed Mono app causes KeyChain to stop access without reboot

We've a mono app that we sign and bundle into an app on OSX.
Our app accesses the keychain for stored passwords, stored using the app name

This works fine, until we perform an upgrade.
On upgrade we replace the .app contents with the (also signed) contents of the upgrade zip file.

However, when the app attempts to access the keychain before, we have NULLs returned in place of our stored passwords. We have found:

Running codesign -vvv against the upgraded app shows the signature is valid.

If we reboot the box, the app can access the keychain fine.

If the app is unsigned the upgrade and keychain access works fine.

So if there a step I'm missing in the signing / upgrade? Is there a service I can restart that would solve it?

Update:

after the update, the keychain call to retrieve credentials returns 'AuthFailed' after reboot we get 'Success'


Divide a std::string without copying

Is it possible to divide a std::string into two or more substrings without copying, much like we can use a move constructor to create a new std::string without copying?


Is it possible to protect a database from being deleted in Azure?

I have one production database and a test database. Now and then I delete the test database, and make a fresh duplicate from the production db.

I am pretty scared that at a brainless moment I will by accident delete the production database.

I know that you can restore a deleted database, but even the downtime can be quite catastrophic at certain moments in time.

Is it possible to give it an extra lock or some other way to prevent me from deleting this database by accident?


CLEAR DATA when a home screen widget is active?

I have a Home Screen widget that stores both some cached data and some shared preferences in the package's private data directory.

I can handle the loss of the data cleanly when the user "CLEAR DATA" option is selected, but I have important shared preferences that get trashed also. (There can be multiple instances of the widget, etc.) The point is that a normal App won't be running when the CLEAR DATA is performed and so the App can recover next time it is launched, but the widget has no way to recover or even know that the preferences have been trashed.

Does any one have any suggestions how to make my preferences truly persistent for the lifetime of the widget on the Home Screen?

It is irritating that this behaviour of the CLEAR DATA button was added some time after the developer documentation was written and it directly contradicts the documentation. Who updates the documentation? Why has this been left as a lie to confuse developers for so long?


Javascript, saving values from onclick and saving previous values in arrays

i'm trying to save values retrieved from "onclick" and also save the values previously retrieved from "onclick" in different arrays when buttons are clicked.

but it seems like when "for loop" is used, newly retrieved values overwrite previously retrieved data even though those values are saved separately in different arrays.

i'm really confused right now, does anybody know why?

(if you hit the button "refresh", you can see the current values that are saved.)

var firstValue = [];
var preValue = [];

function returneD(a){

    preValue = firstValue;
    console.log("returned! preValue:  "+preValue);

    for (var i = 0; i < 1; i++) {
      firstValue[i] = a;
      console.log("returned! firstValue:  "+firstValue);
    }
}

function refresh1(){
  console.log("preValue:  "+preValue);
  console.log("firstValue:  "+firstValue);
}

<!DOCTYPE html>
<html>
<head>
  <script src="jstest.js"></script>
</head>
<body id="thebody">

<button id="1" onclick="returneD(this.id)">O N E</button>
<button id="2" onclick="returneD(this.id)">T W O</button>
<button id="3" onclick="returneD(this.id)">T H R E E</button>
<button id="4" onclick="returneD(this.id)">F O U R</button>
<br>
<button onclick="refresh1()">refresh</button>

</body>
</html>


Plotting function on sphere

I have a problem with plotting a function on the unit sphere.

The function is given analytically:

f = 0.75*exp(-(9*x-2)^2/4 - (9*y-2)^2/4 - (9*z-2)^2/4) + 0.75*exp(-(9*x+1)^2/49-(9*y+1)/10-(9*z+1)/10) + 0.5*exp(-(9*x-7)^2/4 - (9*y-3)^2/4 - (9*z-5)^2/4)-0.2*exp(-(9*x-4)^2 - (9*y-7)^2 - (9*z-5)^2);

with x,y,z - points on the sphere. I want to plot it on the sphere, namely stretch it somehow on the unit sphere instead of surf(x,y,f)


Laravel search results Not Displaying Properly

I have a Form (Laravel 5.2) for a search.  I only have one table and my data displays.  If I search by a lastName I would like it to display everyone who has the last name.  If I search by manufacturer I would like it to display all PCs made by that manufacturer.  I am basically trying to make each column on the database searchable.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Inventory</title>
    <link rel="stylesheet" href="/css/libs.css">
    <link rel="stylesheet" href="/css/app.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  </head>
  <body>

    <nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="http://inventory.app:8000/computers/create" Inventory</a>
  </div>
  <div id="navbar" class="navbar-collapse collapse">
    <ul class="nav navbar-nav navbar-right">
      <li>
          {{ Form::open(['method' => 'GET', 'url'=>'computers/search']) }}
          {{ Form::input('search', 'q', null, ['placeholder' => 'Search...']) }}
          {{ Form::close() }}
      </li>
      <li><a href="http://inventory.app:8000/computers/create">Update Inventory</a></li>
      <li><a href="#">Logout</a></li>
    </ul>

  </div>
</div>
</nav>

I am using Route Resource for my Routing.  My route for my search is

Route::get('computers/search', 'InventoriesController@search');

My Search Controller is as follows

public function search()

        {
            $search = \Request::get('search'); //<-- we use global request to get the param of URI

//            $search = Input::get('search');

            $inventories = Inventory::where('lastName','LIKE','%'.$search.'%')
               -> orwhere('firstName', 'LIKE','%'.$search.'%' )
                -> orwhere('department', 'LIKE','%'.$search.'%' )
                -> orwhere('building', 'LIKE','%'.$search.'%' )
                -> orwhere('room', 'LIKE','%'.$search.'%' )
                -> orwhere('manufacturer', 'LIKE','%'.$search.'%' )
                -> orwhere('device', 'LIKE','%'.$search.'%' )
                -> orwhere('model', 'LIKE','%'.$search.'%' )
                -> orwhere('tag', 'LIKE','%'.$search.'%' )
                -> orwhere('macAddress', 'LIKE','%'.$search.'%' )
                -> orwhere('status', 'LIKE','%'.$search.'%' )
                -> orwhere('comments', 'LIKE','%'.$search.'%' )
                ->get($search);

            return view('computers.search',compact('inventories'));
        }

I have tried doing an orderBy('search') but that did not do anything.  My table just displays but it does redirect to the search route because the URL changes
For example http://inventory.app:8000/computers/search?q=Dell


how to read a specific region in android emmc

I want to read the emmc of my device as the recovery seems to be on it.
cat /proc/mtd doesn't give any output and the deice can't be read by sp flash tool :(

What I want to do is to replace some files from CWM recovery with the stock ones (its an MTK device).

cat /proc/dumchar_info gives a table like this:

Part_Name   Size    StartAddr   Type    MapTo
preloader    0x0000000000040000   0x0000000000000000   2   /dev/misc-sd
dsp_bl       0x00000000005c0000   0x0000000000040000   2   /dev/misc-sd
mbr          0x0000000000004000   0x0000000000000000   2   /dev/block/mmcblk0
ebr1         0x000000000005c000   0x0000000000004000   2   /dev/block/mmcblk0p1
pmt          0x0000000000400000   0x0000000000060000   2   /dev/block/mmcblk0
nvram        0x0000000000300000   0x0000000000460000   2   /dev/block/mmcblk0
seccfg       0x0000000000020000   0x0000000000760000   2   /dev/block/mmcblk0
uboot        0x0000000000060000   0x0000000000780000   2   /dev/block/mmcblk0
bootimg      0x0000000000600000   0x00000000007e0000   2   /dev/block/mmcblk0
recovery     0x0000000000600000   0x0000000000de0000   2   /dev/block/mmcblk0
sec_ro       0x0000000000600000   0x00000000013e0000   2   /dev/block/mmcblk0p5
misc         0x0000000000060000   0x00000000019e0000   2   /dev/block/mmcblk0
logo         0x0000000000300000   0x0000000001a40000   2   /dev/block/mmcblk0
expdb        0x00000000000a0000   0x0000000001d40000   2   /dev/block/mmcblk0
ebr2         0x0000000000004000   0x0000000001de0000   2   /dev/block/mmcblk0
android      0x0000000020100000   0x0000000001de4000   2   /dev/block/mmcblk0p6
cache        0x0000000020100000   0x0000000021ee4000   2   /dev/block/mmcblk0p2
usrdata      0x0000000020100000   0x0000000041fe4000   2   /dev/block/mmcblk0p3
fat          0x0000000083f1c000   0x00000000620e4000   2   /dev/block/mmcblk0p4
bmtpool      0x0000000000a00000   0x00000000ff9f0050   2   /dev/block/mmcblk0
Part_Name:Partition name you should open;
Size:size of partition
StartAddr:Start Address of partition;
Type:Type of partition(MTD=1,EMMC=2)
MapTo:actual device you operate

Any help?


Virtual property in Entity Framework or SQL Server join using view

I have a model that has many navigation properties to other poco models. I was wondering that replacing it with a SQL view that join all these tables by foreign keys into one respecting model to get all data that I need in one trip will boost performance. Any tips will be appreciated.


Jasmine Error: Expected undefined to equal

I'm trying to figure out why I'm getting this error. I have a $scope.message in my angular application in my controller but when I put expect(scope.message)toEqual("It Works");  I get this Error can anyone point me in the right direction as to what I'm doing wrong. It works when I render the application with index file, I'm using Jasmine and Karma for unit testing. Here is my code.

var app = angular.module("MyApp", []);

app.controller("MyController",['$scope', function($scope) {
console.log("Reaching Controller");

  $scope.message="Its Good";

   $scope.customer = {
   name: 'Naomi',
   address: '1600 Amphitheatre'
  };

}])

//normilized name factory function and should return an object
    app.directive('myCustomer', function(){
    return function(scope, elem){ //this for strictly testing
     directives

    elem.append('<span>This span is appended from directive.</span>');
   };
});

 /*Here is my unit test
 describe("Hello PageCtrl working", function() {
    beforeEach(module('MyApp'));

   describe('Reaching Controller', function(){
       var scope,appCtrl, message;

      beforeEach(inject(function($rootScope, $controller) {
      scope = $rootScope.$new();
      appCtrl = $controller("MyController", {$scope:scope});

 }));

        it("should have a message of Its Good", function () {
         expect(scope.message).toEqual("Its Good");
      });
   });
});

Thanks In Advance,
HP


How to write shell script which handles interactive inputs?

I have a command which takes 2 arguments.

When I run the command manually, I do this way:

cmd -i xyz.dat
hit enter
enter password in the prompt
hit enter
confirm password

My script needs to do the above operations without expecting user to enter password. I can hardcode the passwords in the file, but need a way to run this command successfully when I execute the shell script.

As on Feb 7th,
I have expect installed on my AIX. When I type expect at the command prompt, the prompt changes to expect 1.1>  OS is 64 bit AIX

I have followed the instructions mentioned in the below comment, but I keep getting error - could not execute the command; no such file or directory"? I am able to manually run this command from same directory I am running the script. Besides that I have given the complete path of the command and the
file.

I am pasting another program I tried to su with root password as below: i get the same error message when I run the test program. I doubt if this is something related to quotes.

#!/bin/bash
set timeout 20
spawn "su"
expect "Password:" { send:"temp123\r" }
interact

Can someone please help me fix this error?


Finding min and max time in a set of arrays

I have a array of time as,

 var arr= ["17:30:48","19:30:48","18:30:48","19:30:48","17:40:48","19:10:48","17:10:48","19:30:45","17:13:48","19:13:48","17:30:48","19:28:48"];

I want to get the  min and max time out of these. tried if else but its becoming to lengthy by it.is there any easy way to do it.


Activity streams / feeds, to denormalize or not?

I know variations of this question have been asked many times before (and I've read them, 2 of them being: 1, 2), but I just can't wrap my head around anything that just feels like the right solution.

Everything has been suggested from many to many relations, to fanout, to polymorphic associations, to NoSQL solutions, to message queues, to denormalization and combinations of them all.

I know this question is very situational, so I'll briefly explain mine:

Many activities that trigger many events.

Following, creating, liking, commenting, editing, deleting, etc.

A user can follow another user's activity (the events they trigger).

The most requested events will be the most recent events.

The ability to view past events is desired.

No sorting or searching of the feed is desired past ordering by date desc.

Scalability is a concern (performance and expandability).

For the mean time, I ended up going with a denormalized setup basically being made up of an events table consisting of: id, date, user_id, action, root_id, object_id, object, data.

user_id being the person that triggered the event.

action being the action.

root_id being the user the object belongs to.

object being the object type.

data containing the minimum amount of information needed to render the event in a user's stream.

Then to get the desired events, I just grab all rows in which the user_id is the id of a user being followed by whose stream we're grabbing.

It works, but the denormalization just feels wrong. Polymorphic associations seem similarly so. Fanout seems to be somewhere in between, but feels very messy.

With all my searching on the issue, and reading the numerous questions here on SO, I just can't get anything to click and feel like the right solution.

Any experience, insight, or help anyone can offer is greatly appreciated. Thanks.


How to change the URL in browser due to the navigation at iframe?

I want to change the URL in browser based on the iframe navigation like:

**[URL at navigator: http://localhost/]**

<html>
<body>
<iframe src="http://localhost/?loadiframe=true">
   <!-- this is at the code retrieved by the iframe -->
   <a id="mypage" href="http://localhost/mypage/?loadiframe=true">Navi</a>
</iframe>
</body>
</html>

When the user clicks the #mypage link the URL in the browser will be:

http://localhost/mypage/

Not matters that the src of the iframe be the same always.

¿Is that possible?

Maybe using ajax.........??


Does IdIMAP4.UIDRetrieveEnvelope get the entire message body?

Does IdIMAP4.UIDRetrieveEnvelope method retrieve the entire message body or only the headers?