lundi 31 mars 2014

On a single core machine, how can a kernel impose restrictions (memory, etc) on a process, if the compiled code is directly executed on the processor?


Vote count:

0




Basically, how does the kernel prevent me from doing something like this?



char *p = (char *) 0xfea80650; // or any random point in memory
*p = 0;


asked 23 secs ago






Documentation of 'playType' ids


Vote count:

0




Is there available documentation on the playType documents. More specifically, a list of the possible playType objects that could be returned?



asked 29 secs ago






CKEditor - kcfinder browse server does not work


Vote count:

0




First of all I apologize for my poor english.


I am using CKEditor on my website and I've integrated kcfind.


Click the browse button was added to the server.


But when I click the button, this screen is displayed.


http://ift.tt/1fIg12T


Blank pop-up windows and buttons do not work.



asked 49 secs ago






jQuery Mobile Popups won't open after page refresh


Vote count:

0




I have a page in a jQuery mobile app where there are several ajax forms submissions possible, and on 2 of those forms, upon the successful ajax response I reload the page like this:



$.mobile.changePage(window.location.href, {
transition : 'flip',
reverse : false,
changeHash: false,
allowSamePageTransition : true,
reloadPage:true
});


After this refresh occurs the popups on the page will no longer open (until a hard refresh is done in the browser). I'm guessing it has something to do with jQM thinking there are 2 pages (even though its a reload of the same page), and since the same ID's exist its causing problems. How can I fix this?



asked 1 min ago






Serialization vs Raw Data


Vote count:

0




So I have an application sending a stream of images (think teamviewer) and as it currently stands it converts the images to Byte and then to Base64 and sends that as text through the StreamWriter. I've done a few things to improve latency and performance however I'm curious if I'm using the wrong tool for the job and if Serializing the images would reduces size and have less overhead.


Any advice would be appreciated :)



asked 1 min ago






using a function inside an excel IF and use its return value


Vote count:

0




I use excel for my budget. The top row has the dates when I am paid. I wrote a function called Between which determines if the date I am suppose to pay a particular bill will occur within the timeframe specified in Between. If it does, it will fill the cell with the correct value, otherwise blank. The arguments for Between are Between([cell with start date],[number of days in period], [date to test is in the period],[value to fill cell if date in period]). So, say A1 has 9/1/2014. Between(A1,14,7,500) would put 500 in the cell since the 7th is between 9/1 and 9/15. If A1 was 9/20/2014, the cell would be blank since the 7th is not between 9/20 and 10/4.


I would like to check if Between returns a value vs a blank so I could fill empty cells with a 0 so I can sum up numbers in a row. Suppose I had this expression in a cell say B12:


=IF(ISBLANK(Between(A1,14,7,500),0,?) I want the ? to be the value of Between in the IF statement. How can I get the value of Between into the cell if Between does not return blank?



asked 1 min ago







Vote count:

0




in c++, so I need to use the following:


set> info;


where the set info has pairs of strings within it. How can I initialize this info variable? I don't need to initialize it to anything specific. But just for the sake of initialization?


For example:


int i = 0;



asked 56 secs ago






JQuery Validate plugin alters submission button CSS


Vote count:

0




I am using Jquery Validate plugin for a form. Everything works fine except if I tab to the submission button it changes the text color. I have tried using the "ignore:" option then specify the class of the submission button in the validate() function but this doesn't work.



$("#edit_phone_form").validate({
ignore: ".orange-button",
rules: {
phone_number: {
required: true,
phoneUS: true
}
}
});


If anyone knows how I can tell Validate to ignore the ".orange-button" class please let me know. I have no code that is manipulating this button so I know Validate is doing something since it does this same text effect with all other form elements.


Thanks!



asked 1 min ago






Add a label tag for each input tag dynamically for the DOM using JQuery


Vote count:

0




1.The input element's id attribute and the corresponding label element should have a for attribute. The values of these two attributes must be equal. For this, needs to add a label tag for each input tag for the DOM using JQuery.


example: First Name :


needs to add


First Name :


2. Or this will also be fine


First Name :


Thank you so much inadvance :) :)



asked 1 min ago






Evaluating math expression given in character array


Vote count:

0




So, I have an input expression which is of the form ....?5+8 ...


I need to parse this and evaluate the result. Since I know that the expression starts after the ? and ends with a ' ', I tried this:



int evaluate(char *buffer){
while(buffer[i] != '+' || buffer[i] != '-' || buffer[i] != '*' || buffer[i] != '/'){
exp[j] = buffer[i];
i++;
j++;
}
exp[j] = '\0';
int number1 = atoi(exp);

char operation = buffer[i];
i++;
j = 0;
while(buffer[i] !=' '){
exp[j] = buffer[i];
i++;
j++;
}
exp[j] = '\0';
int number2 = atoi(exp);

switch(operation)....
}


where j is initialized from 0 and i is initialized to the position after ?.


The function is called using evaluate(buffer);


However, I keep getting the error Segmentation Fault (core dumped).


Any Ideas?



asked 44 secs ago

gary

28





Data from JSON Parsing straight to UITableView


Vote count:

0




I am getting data using json with this code and I need to display it in a tableview with two part code and name the problem is writing it all to an array is taking forever and the array comes back null. How can I get each returned element as its own tableview cell? Hundreds of airports are returned.



NSString* path = @"http://ift.tt/1gijch1";


NSMutableURLRequest* _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];

[_request setHTTPMethod:@"GET"];


NSURLResponse *response = nil;

NSError *error = nil;


NSData* _connectionData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];

if(nil != error)
{
NSLog(@"Error: %@", error);
}
else
{

NSMutableDictionary* json = nil;


if(nil != _connectionData)
{
json = [NSJSONSerialization JSONObjectWithData:_connectionData options:NSJSONReadingMutableContainers error:&error];
}

if (error || !json)
{
NSLog(@"Could not parse loaded json with error:%@", error);
}
else
{


NSMutableDictionary *routeRes;

routeRes = [json objectForKey:@"airports"];




for(NSMutableDictionary *flight in routeRes)
{
NSLog(@"ident is %@", [flight objectForKey:@"name"]);
NSString *code=[json objectForKey:@"fs"];
NSString *name=[flight objectForKey:@"name"];
NSLog(@"code %@, name %@", code, name);


[candyArray addObject:[Candy code:code name:name]];

}



}

_connectionData = nil;
NSLog(@"connection done");
}


The following is the cellForRowatIndex were nothing is shown



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath


{ static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if ( cell == nil ) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; }



// Create a new Candy Object
Candy *candy = nil;

// Check to see whether the normal table or search results table is being displayed and set the Candy object from the appropriate array
if (tableView == self.searchDisplayController.searchResultsTableView)
{
candy = [filteredCandyArray objectAtIndex:[indexPath row]];
}
else
{
candy = [candyArray objectAtIndex:[indexPath row]];
}

// Configure the cell
[[cell textLabel] setText:[candy name]];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];

return cell;


}



asked 52 secs ago






why what keyword this references in these 2 situation is different?


Vote count:

0






  1. var object1 = {name: "my object", ha: function() { return this;} }


    object1.ha() returns Object {name: "my object", ha: function}




  2. var object2 = {name: "my object2", ha2: function() { return function() { return this} } }


    object2.ha()() returns window





asked 1 min ago

Will

26





How to avoid country-based redirects with urlopen or urllib2 in Python


Vote count:

0




I am using Python 2.7.


I want to open the URL of a website and extract information out of it. The information I am looking for is within the US version of the website (http://ift.tt/1ms3x4f) . Since I am based in Canada, I get automatically redirected to the Canadian version of the website (http://ift.tt/1gVtZ6P). I am looking for a solution to try to avoid this.


If I take any browser (IE, Firefox, Chrome, ...) and navigate to http://ift.tt/1ms3x4f, I will get redirected. The website offers a menu where the visitor can pick the "country-version" of the website he wants to view. Once I select United States, I am no longer redirected to the Canadian version of the website. This is true for any new tab within the browsing session. I suspect this has to do with cookies storage.


I tried to use the following code to prevent the redirect:



import urllib2
class RedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_302(self, req, fp, code, msg, headers):
result = urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)
result.status = code
return result
http_error_301 = http_error_303 = http_error_307 = http_error_302

opener = urllib2.build_opener(RedirectHandler())
webpage = opener.open('http://ift.tt/1ms3x4f')


but it didn't seem to work since the only bit of code that can be extracted afterwards is:



<html><head></head><body>‹</body></html>


A solution to my problem would be to use a proxy while scraping the website but I was wondering if there is any way to prevent these kind of redirects using exclusively Python or Python packages.



asked 50 secs ago






Build error with Jenkins Git and grunt-contrib-imagemin


Vote count:

0




I'm using the latest (unpublished and perhaps unstable) version of grunt-contrib-imagemin, and everything works great except for when I push to Github & Jenkins, the build fails because of this error:



Started by an SCM change
Building in workspace D:\workspace\STAGE-Deploy
Fetching changes from the remote Git repository
Fetching upstream changes from git@git.lbox.com:randyxxxxg/xxxxxxxxx.git
Checking out Revision dbd678e9bc48c627d0d3ec7439e29c6a2c2de7ab (origin/staging)
FATAL: Could not checkout null with start point dbd678e9bc48c627d0d3ec7439e29c6a2c2de7ab
hudson.plugins.git.GitException: Could not checkout null with start point dbd678e9bc48c627d0d3ec7439e29c6a2c2de7ab
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.checkoutBranch(CliGitAPIImpl.java:1299)
at hudson.plugins.git.GitSCM.checkout(GitSCM.java:890)
at hudson.model.AbstractProject.checkout(AbstractProject.java:1414)
at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:671)
at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:88)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:580)
at hudson.model.Run.execute(Run.java:1676)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:88)
at hudson.model.Executor.run(Executor.java:231)
Caused by: hudson.plugins.git.GitException: Command "git checkout -f dbd678e9bc48c627d0d3ec7439e29c6a2c2de7ab" returned status code 128:
stdout:
stderr: fatal: cannot create directory at 'xxxx/node_modules/grunt-contrib-imagemin/node_modules/image-min/node_modules/gifsicle/node_modules/bin-wrapper/node_modules/download/node_modules/decompress/node_modules/adm-zip/test/assets/attributes_test': No such file or directory

at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1173)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1150)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1146)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommand(CliGitAPIImpl.java:962)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommand(CliGitAPIImpl.java:972)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.checkout(CliGitAPIImpl.java:1273)
at hudson.plugins.git.GitAPI.checkout(GitAPI.java:208)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.checkoutBranch(CliGitAPIImpl.java:1283)
... 9 more


I've checked, and the directory is indeed there. Any help is greatly appreciated!


Thanks.



asked 58 secs ago






[C#/XAML][W8] how to initalize a set of random image files in c# and bind them randomly in XAML


Vote count:

0




Warning, a noob here!


I'am coding a Windows8 Metro app in which use some sort of quiz. I even don't know where to start because this is what bothers me. I have 3 sets of 10 images. I want that every time, when that page with quiz run, that program pick a picture randomly, and when a user ticks the answer, on the next page appears image #2 that is also picked randomly and so on, and so on. I'didnt write any code here, because I don't have it since i don't know where to start.


In my own head with some logic it should go something like this:




  1. in .cs there should be a method that picks some random number between 1 and 3 (i know how to do that, that is not the problem)




  2. that number represents a set of images




  3. here comes the problem, i should somehow connect that number with an image saved in my folder inside the project and bind it to XAML




  4. Every image can be selected only once in that run, so that every time i run that page i have random appearance of those images.




I hope I was not too confusing, and excuse me for my terrible english.


Best regards!



asked 1 min ago






The scanner will not take in the input so it cant process it


Vote count:

0




This all looks good to me. The class runs but when I type something into the scanner nothing happens. its supposed to have the input be registered and ran through another class where then i get the response and try to print it.


import java.io.File; import java.util.Scanner;


public class Eliza {



/**
* Main Eliza program that processes user input & responds
*/
public static void main(String[] args) {
String line = ""; // variable to hold user input
String response = ""; // variable to hold eliza's response
ElizaResponder responder = new ElizaResponder();

// 1. Print welcome -- TODO add your name instead----DONE
System.out.println("Welcome to Christian Rebelo's Eliza");
System.out.println("---------------------------");

// Print Eliza's initial greeting to start the conversation
System.out.println("ELIZA> " + responder.getGreeting());

// 2. Create scanner object (TODO)------DONE
Scanner s = new Scanner(System.in);


// Continuously run question-response pattern until
// user indicates they're finished by entering:
// bye, goodbye, done, exit, or quit
while (responder.isNotFinished()) {
// 3. Use scanner to get next line of user input (TODO)----DONE
line = s.nextLine();
}
// 4. Get Eliza's response (TODO)----DONE
response = responder.getResponse(line);


// 5. Display (print) Eliza's response to user (TODO)----DONE
System.out.println(response);


// Print Eliza's farewell----DONE
System.out.println("ELIZA> " + responder.getFarewell());

}


}



asked 42 secs ago






Rubymotion: Rake fails


Vote count:

0




I am using ruby 1.9.3-p484, Xcode 5.1, and OS X 10.9 Mavericks, and I get the following error when running rake with RubyMotion.



$ rake
Build ./build/iPhoneSimulator-7.1-Development
Build vendor/Pods/NewRelicAgent/NewRelic_iOS_Agent_3.252/NewRelicAgent.framework
Link ./build/iPhoneSimulator-7.1-Development/Themes.app/Themes
Undefined symbols for architecture i386:
"_OBJC_CLASS_$_CTTelephonyNetworkInfo", referenced from:
objc-class-ref in NewRelicAgent(NewRelicInternalUtils.o)
"_deflate", referenced from:
-[NRHarvesterConnection createPostWithURI:message:] in NewRelicAgent(NRHarvesterConnection.o)
"_deflateEnd", referenced from:
-[NRHarvesterConnection createPostWithURI:message:] in NewRelicAgent(NRHarvesterConnection.o)
"_deflateInit_", referenced from:
-[NRHarvesterConnection createPostWithURI:message:] in NewRelicAgent(NRHarvesterConnection.o)
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
rake aborted!
Command failed with status (1): [/Applications/http://ift.tt/1emgKvh...]

Tasks: TOP => build:simulator
(See full trace by running task with --trace)


asked 50 secs ago






Fixed timestep and gamespeed


Vote count:

0




this is my first game and I'm not that experienced of a programmer but I've researched a lot and I've worked on this game every day for the last couple of weeks. I research different things on this website every day and I find your posts here tremendously helpful :)


I have a question regarding fixed timestep loops, can't wrap my head around why changing the time to wait between updates affects the speed of which my entire game moves. Maybe there's something I'm missing or something I don't understand yet


My loop looks like this:



private void gameLoop(){
final double updateWaitTime = 1000000000/50;
double nextUpdateTime = System.nanoTime();
while(running) {
double now = System.nanoTime();
while( now > nextUpdateTime) {
updateGame(now);
nextUpdateTime += updateWaitTime;
}
double interpolation = (now+updateWaitTime-nextUpdateTime)/updateWaitTime;
drawGame(interpolation);
}
}


If I decrease the value of updateWaitTime, my game moves much faster because it is getting updated so much more.


The methods that execute my movement looks like this, they both get the current time with getNanoSecond() which holds the same value that the gameLoop sets "now" as.



protected void travel(){
if(moveShotTime <= c.getNanoSecond()){
setX(getX()+dx);
setY(getY()+dy);
moveShotTime = c.getNanoSecond()+bulletMoveDelay;
}
}


//[0] = degree. [1] = distance. [2] = movementspeed
public void move(){
if(moves.isEmpty() == false){
ArrayList<double[]> movementDirection = moves.get(0);
if(movementDirection.isEmpty() == false){
double[] oneMove = movementDirection.get(0);
if(getNextMoveTime() <= c.getNanoSecond()){
else if(oneMove[1] > distanceMoved){
double radian = (oneMove[0]/360)*2*Math.PI;
double dx = round((Math.cos(radian)*oneMove[2]), 9);
double dy = round((Math.sin(radian)*oneMove[2]), 9);
double dz;
if(dx<0){
dz = round(dx/(Math.cos(radian)), 5);
}
else if(dx==0){
dz = dy;

}
else if(dy==0){
dz = dx;
}
else{
dz = round((dx/(Math.cos(radian))), 5);
}
setX(getX()+dx);
setY(getY()+dy);

if(dz<0){
distanceMoved = distanceMoved-dz;
}
else{
distanceMoved = distanceMoved+dz;
}

movedX = movedX + dx;
movedY = movedY + dy;
}
else{

movementDirection.remove(0);
distanceMoved = 0;

}
}
}
else{
setPreviousX(getX()-movedX);
setPreviousY(getY()-movedY);
moves.remove(0);
}
}
else{
}
}


So what I'm wondering is why changing the updateWaitTime affects the speed of everything. Since I'm using timestamps as a reference for when to execute the movement again, in my mind it shouldn't make a difference how often the game is updated as long as it's more often than the timesteps inside of the game. I'm new to this and I'm surely missing something here. I would also like to ask what a common update-time for games are on PC and android? If I can't figure this out I'm gonna have to set an update-time that I can't change to work with from here on (since i would have to adjust everything in the game).


Thanks in advance and thanks for all the great info on this website!! :)



asked 36 secs ago






can't save Google maps marker objects to array in hidden html field


Vote count:

0




I followed the example here to create an array of the markers that I put on my Google map on my web page.


I've looked for the past few hours at a lot of example both on the open web and here on SO and nothing I've tried works.


I need to:


1) save a Javascript array of Google Maps marker objects in a hidden input field


2) then retrieve the 'value' of the hidden input field and convert that back to the array of Marker objects so that I can remove these markers from the map


Here's my code, some is based on the Google Maps sample above:



theMarkersArray = new Array();
for(var i = 0; i < 5; i++)
{
marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
shape: shape,
title: "aMarker",
zIndex: 1000});

theMarkersArray.push(marker);
}

theMarkersArrayField = document.getElementById('markersArray');

// I'm using Firefox v28.0, the following line of code halts code executing,
// I'm thinking that 'JSON.stringify()' is not defined for FF 28.0..?)

//theMarkersArrayField.value = JSON.stringify(theMarkersArray);

// this executes, but I don't think it's saving the array of Marker objects
// correctly
theMarkersArrayField.value = theMarkersArray;

alert("the theMarkersArray is: "+ theMarkersArray);


When I display the contents of theMarkersArrayField.value using alert(), it looks like this:



[object Object],[object Object],[object Object],[object Object],[object Object]


and when I try to convert theMarkersArrayField.value back into a Javascript array using either eval() or JSON.parse(), both fail.



var theMarkersArrayField = document.getElementById('markersArray');

// DOES NOT WORK
//var theMarkersArray = JSON.parse(theMarkersArrayField.value);

// THIS doesn't work either
//var theMarkersArray = eval(theMarkersArrayField.value);


// IS NOT AN ARRAY OF 'Marker' objects, just a text string it seems...?
var theMarkersArray = document.getElementById('markersArray').value;

// RETURNS '79' INSTEAD OF 5 (only 5 markers were stored in the array, not 79) --
// 79 is the count of characters in:
// [object Object],[object Object],[object Object],[object Object],[object Object]
var numMarkers = theMarkersArray.length;


I need to store an array of Marker objects in an array then save that array in a hidden field on the page, then later retrieve that from the hidden field, convert it back to an array of Marker objects -- what am I missing?



asked 1 min ago






Laravel how to save comment and attaching post_id?


Vote count:

0




I'm doing my first blog with posts and comments - but i can't figure out how to save the comments and retrieve the post_id to the post_id field in comments table??


My tables look like this


comments id | comment | post_id | user_id | updated_at | created_at


posts id | title | content | category_id | user_id | updated_at | created_at


Any help is much appreciated:-)



asked 1 min ago






CakePHP Unit testing controller returning undefined variable


Vote count:

0




I am new to the Unit Testing portion of CakePHP. There is no better time to learn than now.


I have ready through all of the documentation and numerous tutorials on the web. I have run up against a snag during the completion of some of my more basic unit tests.


My Controller test looks like this:



class TestsControllerTest extends ControllerTestCase {

public $fixtures = array('app.test');

public function testIndex() {

$result = $this->testAction('tests/index');
debug($result);
}
}


The output of my test is:



PHPUNIT_FRAMEWORK_ERROR_NOTICE
Undefined variable: tests
Test case: testsControllerTest(testIndex)


The only viable solution to the error I am receiving would be that maybe the test controller needs authentication before it can actually run the testAction() ?


This is a very simple sample from the CakePHP Documentation guide, yet I receive and undefined variable error. Any help is greatly appreciated.



asked 1 min ago






struggling on xpath establishment


Vote count:

0




I'm trying to establish the xpath for this page:


http://ift.tt/Pbz4w1


items I want to scrape are brand, model name and price respectively for all smartphones, as shown on the photo:


enter image description here


however I'm struggling to establish the valid main xpath. tried to test few xpath, finishing with this one:



sel.xpath('//div[@style="position: relative;"]').extract()


but no success.


Any hints on this?


Thanks!



asked 1 min ago






Mac using default Python despite Anaconda install


Vote count:

0




I am running Mac 10.9 Mavericks and have installed Anaconda. However, despite that, when I access python via terminal, I still get the default Apple version:



Python 2.7.5 (default, Sep 2 2013, 05:24:04)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin


My .bash_profile is this:



export PATH="$HOME/anaconda/bin:$PATH"

MONGO_PATH=/usr/local/mongodb/bin
SQL_PATH=/usr/local/mysql

export PATH="/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:$PATH"


Is there anything I can do to use the Anaconda version of Python? At a loss at the moment.


Thank you



asked 1 min ago

intl

586





SDL program immediatly quitting after being started. What did I do wrong?


Vote count:

0




I am trying to write a simple program with the help of SDL. This program loads in an SDL_Texture, and renders it to the window. However, upon starting my program it immediately quits. I am using VS Express 2013 with SDL2 and SDL2_image libraries added to the project. What can be the problem? Thanks in advance!



#include "SDL.h"
#include "SDL_image.h"
#include <iostream>
#include <string>

const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;

bool init();
bool loadMedia();
void close();
// Loads individual image as texture
SDL_Texture* loadTexture(std::string);

SDL_Event event;
SDL_Window* gWindow = NULL;
// The window renderes
SDL_Renderer* gRenderer = NULL;
// Current displayed texture
SDL_Texture* gTexture = NULL;

int main(int argc, char* args[])
{
if (!init())
{
std::cout << "An error has occured while initializing the window: " << SDL_GetError();
return 1;
}

if (loadMedia() == NULL)
{
std::cout << "Could not load media!";
return 1;
}

bool quit = false;
// main game loop
while (!quit)
{
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
quit = true;
break;
}
}

// Clear screen
SDL_RenderClear(gRenderer);

// Render texture to screen
SDL_RenderCopy(gRenderer, gTexture, NULL, NULL);

SDL_RenderPresent(gRenderer);
}

close();
return 0;
}

bool init()
{
//initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) == -1)
{
std::cout << "SDL could not initialize! Error: " << SDL_GetError();
return false;
}

// Set texture filtering to linear
if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"))
std::cout << "Warning: Linear texture filtering not enabled!";

//create window
gWindow = SDL_CreateWindow("Hello World", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);

if (gWindow == NULL)
return false;

// Hardware accelerated renderer
gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED);

if (gRenderer == NULL)
return false;

// Initialize renderer color
SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);

//Initialize PNG loading
int imgFlags = IMG_INIT_PNG;
if(!(IMG_Init(imgFlags ) & imgFlags))
{
std::cout << "SDL_image could not initialize! SDL_image Error: " << IMG_GetError();
return false;
}

return true;
}

bool loadMedia()
{
gTexture = loadTexture("texture.png");

if (gTexture == NULL)
{
std::cout << "Failed to load texture image!!";
return false;
}

return true;
}

SDL_Texture* loadTexture(std::string path)
{
SDL_Texture* newTexture = NULL;

// Load an image from a specific path
SDL_Surface* loadedSurface = IMG_Load(path.c_str());

if (loadedSurface == NULL)
{
std::cout << "Error while loading surface: " << IMG_GetError();
return newTexture;
}

newTexture = SDL_CreateTextureFromSurface(gRenderer, loadedSurface);

SDL_FreeSurface(loadedSurface);
loadedSurface = NULL;

return newTexture;
}

void close()
{
SDL_DestroyTexture(gTexture);
SDL_DestroyWindow(gWindow);
IMG_Quit();
SDL_Quit();
}


asked 44 secs ago






Change the appearance of only one ListView items


Vote count:

0




In my ListView, I want the first item to have a special style, while the other items have the regular layout called by the adapter:



myAdapt = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, list);

// Set Appearance of item 1 here
//

myListView.setAdapter(myAdapt);


Is there a way to do that? The item cannot be added via a TextView using the addHeaderView method because I might have to delete it at some point, which the adapter will not let me do (if there's actually a way to do that, shoot!).



asked 50 secs ago






How do I get invoice associated with a credit memo in Magento?


Vote count:

0




I am assuming that every credit memo is associated with an invoice in magento. If I am right, given a credit memo object i.e $creditmemo, how do i get the invoice id related to that credit memo?


Thanks for your help!



asked 53 secs ago






Adding or Removing Numbers from an Array using Ember


Vote count:

0




I recently started working on a project which requires that I learn how to use Ember.js, so for the past few weeks I have been trying to understand the syntax and inner workings of the framework/MVC. Let me begin by showing you my models.



var ClassGroup = DS.Model.extend({
className: DS.attr('string'),
isActive: DS.attr('boolean'),
isExpanded: DS.attr('boolean'),
students: DS.hasMany('Students',{async:true}),
isSelected: DS.hasMany('Students',{async:true})
});

ClassGroup.FIXTURES = [
{
id: 123,
className: 'Class 1',
isActive: true,
isExpanded: false,
students: [11, 22, 33, 44, 55],
isSelected: [11, 22, 33, 44, 55]
},
{
id: 456,
className: 'Class 2',
isActive: false,
isExpanded: false,
students: [66, 77, 88, 99],
isSelected: [66, 88, 99]
},
{
id: 789,
className: 'Group 1',
isActive: false,
isExpanded: false,
students: [22, 77],
isSelected: []
}
];

export default ClassGroup;


And...



var Students = DS.Model.extend({
first: DS.attr('string'),
last: DS.attr('string'),
classes: DS.hasMany('classgroup',{async:true}),
isSelected: DS.hasMany('classgroup',{async:true})
});

Students.FIXTURES = [
{
id: 11,
first: 'Student',
last: 'One',
classes: [123],
isSelected: [123]
},
{
id: 22,
first: 'Student',
last: 'Two',
classes: [123, 789],
isSelected: [123]
},
{
id: 33,
first: 'Student',
last: 'Three',
classes: [123],
isSelected: [123]
},
{
id: 44,
first: 'Student',
last: 'Four',
classes: [123],
isSelected: [123]
},
{
id: 55,
first: 'Student',
last: 'Five',
classes: [123],
isSelected: [123]
},
{
id: 66,
first: 'Student',
last: 'Six',
classes: [456],
isSelected: [456]
},
{
id: 77,
first: 'Student',
last: 'Seven',
classes: [456, 789],
isSelected: []
},
{
id: 88,
first: 'Student',
last: 'Eight',
classes: [456],
isSelected: [456]
},
{
id: 99,
first: 'Student',
last: 'Nine',
classes: [456],
isSelected: [456]
}
];

export default Students;


I'm not sure if this is the best way to go about doing this, but I store a students array in my ClassGroup model, and a classes array in my Students model. I am basically storing the same data in both models, just in different ways. Each class has an array containing the IDs of all students in that class, and each students contains an array of all the classes in which he/she belongs to.


There is also an isSelected array in both models, and that is the array that I am dealing with at the moment.


Here is what I am trying to accomplish:


I have a list of classes. Under each class is a list of students with a checkbox by each student name. A checked checkbox means that that student isSelected for that class. Thus, checking a checkbox will need to cause the ID for that student to be added to the isSelected array for the class, as well as the ID for the class to be added to the isSelected array for the student. I am not sure how much of this will automatically be accomplished by Ember what with the hasMany's that I've added to the models.


Let me show you my code. Here are my controllers:



var ClassGroupsController = Ember.ArrayController.extend({
itemController: 'classgroup',
classCount: function(){
return this.get('length');
}.property('@each')
});

export default ClassGroupsController;

var ClassGroupController = Ember.ObjectController.extend({
actions: {
selected: function(){
//console.info("You selected: "+ this.get('className'));
this.toggleProperty('isActive');
//console.info("My isActive state is now: " + this.get('isActive'));
},
selectAll: function() {
console.log("SELECTING ALL STUDENTS:");
},
expanded: function() {
this.toggleProperty('isExpanded');
},
selectedStudent: function(){
this.toggleProperty('isSelected');
},
selectStudent: function() {
console.log("Selected Student");
console.log(this.get('student.id'));
this.store.removeItem('selected');
}
}
});

export default ClassGroupController;


Here is the relevant part of my handlebars file:



<div id="classGroupMenu">
<ul class="specialtyMenu manageMenuWidth" id="classGroup">
{{#each}}
<li id="c_{{unbound this.id}}" class="classMenu manageMenuWidth">
{{#view 'selectall'}}{{input type="checkbox"}}{{/view}}
{{#view 'classgroup' classBinding="controller.content.isActive:activeSelection isExpanded:classLayoutOpen:classLayoutClosed"}}{{classCount}}{{className}}{{/view}}
{{#view 'toggleclass' classBinding="controller.content.isExpanded:togControlOpen:togControlClosed"}}{{/view}}
</li>
<ul id="c_{{unbound this.id}}_sts" class="students manageMenuWidth">
{{#each students}}
<li class="student" id="s_{{unbound this.id}}_c_{{unbound classgroup.id}}">
{{#view 'student' classBinding="controller.content.isSelected:studentChecked:studentUnChecked"}}
{{last}}, {{first}}
{{/view}}
</li>
{{/each}}
</ul>
{{/each}}
</ul>
</div>


And finally, here is the view I have:



//Using this to toggle the class menu on and off

var view = Ember.View.create({
templateName: 'student',
name: 'Student'
});

export default Ember.View.extend({
tagName: 'span',
classNames: ['studentChk'],
click: function(evt) {
console.log("IN VIEW: Student");
this.get('controller').send('selectStudent');

/*var tog_sa_id = $(evt.currentTarget).siblings('span.classSA');
console.log(tog_sa_id);
var url = '/assets/images/sel-active.png';
$(tog_sa_id).css('background', 'url(' + url + ')');*/
}
});


I don't think I need to include the other views or my router, but if you think it would help, let me know and I will include them.


The Long Story Short:


Now that I've posted my code, let me simplify things a bit and show you what exactly I'm trying to do:


In my handlebars template I have the following line (also found above):



{{#view 'student' classBinding="controller.content.isSelected:studentChecked:studentUnChecked"}}
{{last}}, {{first}}
{{/view}}


The CSS for the studentChecked and studentUnChecked change a background-image which makes it appear like a checkbox. So it's not literally a checkbox which we are dealing with; I apologize if that was misleading.


Upon clicking on this student view, I run this on the click event:



this.get('controller').send('selectStudent');


Which runs this function in my controller:



selectStudent: function() {
console.log("Selected Student");
console.log(this.get('student.id'));
this.store.removeItem('selected');
}


When calling this function in my controller, I would like to be able to pass in the Student's ID, and then either add or remove that Student ID from the isSelected array. I will also need to keep the student model's isSelected array updated by adding or removing the Class ID.


What kind of functions do I have access to that can help me alter the contents of these arrays? I am very new to Ember, so I am looking for explanations in the simplest of terms. I appreciate you taking the time to read my question; any and all suggestions/comments would be a tremendous help for us.



asked 1 min ago






qxtglobalshortcut not found compile error but QT Creator does acknowledge its location in IDE


Vote count:

0




I have a simple QT and QxT app that I am working on. Right now, I can build without issue on Mac and Linux. On Windows, I have tons of problems. I keep getting the error C1083: Cannot open include file 'QxtGlobalShortcut': no such file or directory.


Have QT 5.2.1 32bit MSVC12 version installed. MSVC12 Pro 32bit installed. Windows 7 64 bit. LibQxT checked out from Git and compiled without issue. Followed the instructions from http://ift.tt/1fgBnrf, including copying the header files to includes, and made sure to copy the prf files to mkspecs/features on the QT install. qxtvars.prf also was updated to show my current libqxt install location. My .pro file includes QXT += core gui widgets and CONFIG += QXT. The QT Creator IDE shows QxtGlobalShortcut in the tabcomplete, and I still get failure regarldess of if #include or #include . I have seen recommended #include but autocomplete doesn't show that as an option, and if I try anyway it still fails.


Anyone have an idea on what is going on here? Anyone know of another way for crossplatform global hot keys should all else fails (really surprised that QT doesn't have that built in).



asked 1 min ago






getting RS Eevents category name from Joomla database


Vote count:

0




I'm trying to get the category details from the joomla database for RSEvents. Can anyone shed any light on why this isn't working:



function _getCategorySlug($value) {
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Select all articles for users who have a username which starts with 'a'.
// Order it by the created date.
// Note by putting 'a' as a second parameter will generate `#__content` AS `a`
$query
->select($db->quoteName(array('a.*', 'b.id', 'b.ide')))
->from($db->quoteName('#__categories', 'a'))
->join('INNER', $db->quoteName('#__rseventspro_taxonomy', 'b')
. ' ON (' . $db->quoteName('a.id') . ' = ' . $db->quoteName('b.id') . ')')
->where($db->quoteName('b.ide') . ' = '.$db->quote($value));
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
}


asked 1 min ago






Image with a complex border


Vote count:

0




For example, there is a picture http://ift.tt/1ghNz7w



<a class="image-wrapper" href="">
<img src="//s1.iconbird.com/ico/2013/6/280/w64h641371488108chrome64.png"/>
<img src="//www.ferra.ru/images/315/315404.png"/>
<div class="border"></div>
</a>


How to clean a beige background in image-border so that the main image is preserved only in the scope of the designated image-border. Perhaps there is another way? Need exactly such border shape.


If beige background make an alpha channel, the image boundary will go beyond the border.



asked 24 secs ago






Why does this program show 3 outputs, also why does b override a?


Vote count:

0





#include "stdafx.h"
#include <iostream>

using namespace std;

void silly(int & a, int & b)
{
a=10;
b=20;
cout << a << "" << b << endl;
}


void main()
{
int z=30;
silly(z,z);
cout << z << endl;
system("Pause");

}


The output for this is:


2020 20


Why are there 3 outputs, and why does b override a?


I'm asking because this is part of homework and I don't exactly understand the passing of variables especially strings/arrays.



asked 29 secs ago






Feature scaling in d3.js


Vote count:

0




I am trying to make a line chart. Right now I am using this



data.forEach(function(d) {
d.MEDV = +d.MEDV;
d.CRIM = +d.CRIM;
});

x.domain(d3.extent(data, function(d) { return d.CRIM; })).nice();
y.domain(d3.extent(data, function(d) { return d.MEDV; })).nice();


But I want to do feature scaling since my CRIM values varies from 0.006 to 88.



asked 42 secs ago

wannaC

126





AVAssetExportSession works on iPad, no audio on iPhone


Vote count:

0




I have the exact same code running on both the iPad and iPhone versions of my app and the code works fine on the iPad (the video is being exported properly with audio), but the exported video on the iPhone doesn't have any sound. I even ran the iPhone version on the iPad and it worked fine, which means that nothing should be wrong with the code itself.


Any insight on why the iPhone isn't exporting the video with audio would be much appreciated.


I have done some research and somebody mentioned that memory issues could be causing some export problems. The memory and CPU usage are fairly high during the video processing/exporting, but never high enough to receive a memory warning.


Thanks in advance.



asked 2 mins ago






Constraint error in adding Multi rows to master/detail dataset


Vote count:

0




I have 2 dataGridViews bound to a master/detail relationship. When I try to add a second row to the master dataGridView I get the following error.


system.data.constraintexception column "Project Customer UBF Id" is constrained to be unique. Value '' is already present Data relation.


I can add multi rows to the child DataGridView, and if I remove the DataRelation between the tables I can add multi rows to the master.


The tables are set up with autoincrement primary keys in SQL server.


Any help in overcoming this error would be appreciated



private void getData()
{
try
{
conn = new SqlConnection(connstr);
conn.Open();

// Create a DataSet.
data = new DataSet();
data.Locale = System.Globalization.CultureInfo.InvariantCulture;

string sqlStr = "SELECT [Project Customer UBF].* FROM [Project Customer UBF]; "; //WHERE [Project Customer UBF].[Project Id] = " +_projectID;

// Add data from the Customers table to the DataSet.
masterDataAdapter = new
SqlDataAdapter(sqlStr, conn);

masterDataAdapter.Fill(data, "[Project Customer UBF]");

// Add data from the Orders table to the DataSet.
detailsDataAdapter = new
SqlDataAdapter("SELECT [Project Customer Discount].* FROM [Project Customer Discount]", conn);
detailsDataAdapter.Fill(data, "[Project Customer Discount]");

// Establish a relationship between the two tables.
DataRelation relation = new DataRelation("CustDist",
data.Tables["[Project Customer UBF]"].Columns["Project Customer UBF Id"],
data.Tables["[Project Customer Discount]"].Columns["Project Customer UBF Id"]);
data.Relations.Add(relation);

// Bind the master data connector to the Customers table.
masterBindingSource.DataSource = data;
masterBindingSource.DataMember = "[Project Customer UBF]";
masterBindingSource.Filter = "[Project Id] =" + _projectID;

// Bind the details data connector to the master data connector,
// using the DataRelation name to filter the information in the
// details table based on the current row in the master table.
detailsBindingSource.DataSource = masterBindingSource;
detailsBindingSource.DataMember = "CustDist";
conn.Close();
}
catch (SqlException)
{
MessageBox.Show("To run this example, replace the value of the " +
"connectionString variable with a connection string that is " +
"valid for your system.");
}
}

private void ProjectEdit_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = masterBindingSource;
dataGridView2.DataSource = detailsBindingSource;
getData();
}


asked 2 mins ago






Task Continuation


Vote count:

1




I have a Web API that returns a list of people:



public async Task<HttpResponseMessage> Get()
{
var people = await _PeopleRepo.GetAll();
return Request.CreateResponse(HttpStatusCode.OK, people);
}


I have a console application that I'd like to be able to call so that it first gets the people, then iterates over them calling their ToString() method, and then completing.


I have the following method to get the people:



static async Task<List<Person>> GetAllPeople()
{
List<Person> peopleList = null;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:38263/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = await client.GetAsync("People");
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
peopleList = await response.Content.ReadAsAsync<List<Person>>();
}
}

return peopleList;
}


I then have a second function to print the list:



static void PrintPeopleList(List<Person> people)
{
if (people == null)
{
Console.Write("No people to speak of.");
return;
}

people.ForEach(m => Console.WriteLine(m.ToString()));
}


I tried using a task factory to first download the people list with GetAllPeople() and then supply the results to PrintPeopleList() when the response is back but the compiler gives an ambiguous invocation error:



Task.Factory.StartNew(() => GetAllPeople()).ContinueWith((t) => PrintPeopleList(t.Result));


Am I way off?



asked 2 mins ago

Bullines

2,453





Connect QTextEdit and QTextBrowser in QT


Vote count:

0




I am trying to connect QTextEdit to QTextBrowser,so the text browser widget outputs what is entered in text edit widget. As a signal I used textChanged() function,and as a slot I used setText(QString) function. And these two don't have same parameters.


If I used QLineEdit instead of QTextEdit, in that case there is textChanged(QString) function which is compatible with the slot,but I need to make it work with QTextEdit. Here is the code:



#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtWidgets>



MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
QWidget * mainWidget=new QWidget(this);
ui->setupUi(this);
QTextEdit * mainTextEdit=new QTextEdit();
QTextBrowser * textDisplay=new QTextBrowser();


connect(mainTextEdit,SIGNAL( textChanged() ),
textDisplay,SLOT( setText(QString) ) );

QHBoxLayout * Alayout=new QHBoxLayout();
Alayout->addWidget(mainTextEdit);
Alayout->addWidget(textDisplay);
mainWidget->setLayout(Alayout);
setCentralWidget(mainWidget);


}

MainWindow::~MainWindow()
{
delete ui;
}


asked 1 min ago






Reverse elements via pipeline


Vote count:

0




Is there a function reverses elements passed via pipeline?


E.g.:



PS C:\> 10, 20, 30 | Reverse
30
20
10


asked 1 min ago


1 Answer



Vote count:

0




Here's one approach:



function Reverse ()
{
$arr = $input | ForEach-Object { $_ }
[array]::Reverse($arr)
return $arr
}


answered 44 secs ago





JQuery - Using .each() To Change Selected Elements


Vote count:

0




As I'm iterating through a set of HTML elements passed into a function, I'm trying to set a class on certain elements (rel), depending upon a test. After I set the class, the content I'm returning appears not to have been changed. I'm sure there's a basic disconnect in my logic - any guidance on why my changes don't appear?



data:

< ul >
< li title = "ID: 3 " id = "ID1" rel = "departmentgroup" class = "leaf" >
< a href = "#" class = "departmentgroup" rel = "15000_3_16010_relationship_Department-Path" >
< ins class = "departmentgroup" > & nbsp; < /ins>
Floating
</a >
< /li>
< /ul >

function:

newData = $.trim(data);

$.each($(newData).find("a"), function (i, item) {
thisrel = $(item).attr("rel");
if ($('#' + thisrel).length > 0) {
$(item).children().removeClass().addClass('tick');
}
});

$.each($(newData).find("a"), function (x, curr) {
alert($(curr).children().attr("class")); // no changes evident
});


asked 1 min ago






Group by Expression


Vote count:

0





Grades:

SID CID GRADE
--------------
S1 C1 50
S1 C2 85
S1 C3 60
S1 C4 90
S1 C5 50
S2 C1 30
S2 C2 40
S3 C2 85
S4 C2 80
S4 C4 75
S4 C5 60


We have Grades table, SID = Student_ID CID = Course_ID


We want to get SID of student who gets the highest grade from the course ‘C1’.


This is my solution



SELECT DISTINCT SID
FROM GRADES
WHERE GRADE =
(SELECT max(GRADE)
FROM GRADES
GROUP BY CID HAVING CID = 'C1')


it works wrong in my opinion, how can i fix it?



asked 1 min ago






Populate database only once before @Test methods in spring test?


Vote count:

0




I have the same problem that in this question:


How to populate database only once before @Test methods in spring test?


But the solution is not acceptable for me because that would run the same script for all my tests classes. What I want is to run a different script for every test class only once. The only solution that I have found so far is to add an if in the @Before method



asked 1 min ago

Oscar

438





How do you embed a .JPG picture in an EPS file?


Vote count:

-1




I have an eps file which makes a watermark. I want to drop in a .jpg file that is my logo at the top of the page. How do you do this?



asked 2 mins ago






How to get thread.sleep to work


Vote count:

0




In my code below im am tring to add a thread.sleep for when someone chooses the option to exit the lift, i am not sure whats wrong with the code i entered to make it sleep.I already included the Interrupted exception so can someone tell me where i went wrong.



import java.util.Arrays;
import java.util.Scanner;


public class username
{

public static void main(String... args) throws InterruptedException {

String[] verifiedNames = { "barry", "matty", "olly", "joey" };
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");

Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();

switch (choice) {
case 1:
scanner.nextLine(); // get '\n' symbol from previous input
int nameAttemptsLeft = 3;
while (nameAttemptsLeft-- > 0) {
System.out.println(" Enter your name ");
String name = scanner.nextLine();

if (Arrays.asList(verifiedNames).contains(name)) {
System.out.println("dear " + name + " you are verified " +
"you may use the lift, calling lift ");
break; // break out of loop
}
}
if (nameAttemptsLeft < 0) {
System.out.println("Username Invalid");
}
break;

case 2:
System.out.println("option 2");
break;
case 3:
System.out.println(" Please Exit Lift ");
Thread.sleep(5000);
System.exit(0);
break;
}


asked 23 secs ago






Determine if one TimeSpan falls into another time span intervals


Vote count:

0




I have a TimeSpan variable that can be some time like 10:00:00 or some time like 10:23:00 And also I have another TimeSpan variable that is used to set the time interval, currently as default it is set on one hour intervals so 1:00:00


I am looking for a good way to determine if my timespan variable falls into my interval or not? For example if interval is every one hour then 10:00:00 is ok because we have hours or 1,2,3,4,5,etc.. but 10:23:00 is not ok because we have 10 and 11 but not 10:23


Is there any built in .NET way to determine this? if there is not then what is a good way to determine this.



asked 23 secs ago






unexpected matlab expression very simple code.


Vote count:

0




There seems to be a small problem with my matlabcode. i'm trying to calculate Qx using this simple formula. Anybody has an idea what i'm doing wrong?



Error: File: functie5612.m Line: 2 Column: 28
Unexpected MATLAB expression.

Error in oef5612 (line 2)
Qx=functie5612(D)


Define my function



function Qx=functie5612(D)
Qx= D*(11-(0.1*D)/(0.28-D))0.8
end


Initial parameter



D=[0;2;4;6;8;10;12;14;16;18;20;22;23;24;25;26;27;28;30;32;34;36;38]


Using my function



Qx=functie5612(D)


making a graph



clf
figure(1);
plot(D,Qx);
title ('Optimale dilutiesnelheid','FontSize',12);
xlabel('D(1/h)','FontSize',12);
ylabel('Volumetrische biomassaproductiviteit(kg/(m^3*h)','FontSize',12);
legend('Substraat','Product','Biomassa') `


asked 43 secs ago






Writing data into MongoDB with Crunch


Vote count:

0




We're going to use Apache Crunch to implement our new solutions. We'd like to extract data from HBase and then apply some logic in order to filter out unqualifying ones and at last write the data in a structured way into MongoDB for further processing. Is this feasible? Any ideas about how to make Crunch work with MongoDB?



asked 33 secs ago






C++ How do we find each line of a word from a text file?


Vote count:

0




I am reading a text file word for word and I am trying to find the number of the line the word is in. For example if I had the following:


Dog Cat Car Truck


Dog is found on line one, Cat is found on line one, Car line two, and Truck line 3.


I have the following code:



int main(){
string word;
ifstream inFile;
Node* rootPtr = NULL; // Pointer to the root node

inFile.open("example.txt");
if (!inFile)
cout << "Unable to open text file";

while (inFile >> word) {
if (word == "#")
break;
else{
rootPtr = Insert(rootPtr,word.substr(0,10));
}
}
inOrderPrint(rootPtr);
inFile.close();
}


You can ignore anything to do with the pointers. That is for some other stuff. I have tried figuring out how to check for the end of the line and creating a counter that will increment every time then end of a line is found but I was unsuccessful.


Thanks for your help!



asked 54 secs ago

Nick

23





Possible to specify a cache length or a forced refresh for a JavaScript file from the hosting server?


Vote count:

0




We are producing a JavaScript library that will be included by web pages on other domains that we do not have direct control over. Ideally, we'd like that file cached, but also have the ability to tell users' browsers (that have loaded the web page that includes our .js file) to clear its cache and reload that .js file should we need to push a bug fix or similar. If an 'on demand' refresh isn't possible, than we'd like to set an appropriate time to live so that changes are picked up at a reasonably predictable interval. Is this possible?



asked 54 secs ago

Pete

12.2k





How to Mock an Entity Framework 6 Async Projecting Query


Vote count:

0




By leveraging the Testing with async queries section of the Testing with a Mocking Framework article on MSDN, I've been able to create many successfully passing tests.


Here's my test code, which uses NSubstitute for mocks:



var dummyQueryable = locations.AsQueryable();

var mock = Substitute.For<DbSet<Location>, IDbAsyncEnumerable<Location>, IQueryable<Location>>();
((IDbAsyncEnumerable<Location>)mock).GetAsyncEnumerator().Returns(new TestDbAsyncEnumerator<Location>(dummyQueryable.GetEnumerator()));
((IQueryable<Location>)mock).Provider.Returns(new TestDbAsyncQueryProvider<Location>(dummyQueryable.Provider));
((IQueryable<Location>)mock).Expression.Returns(dummyQueryable.Expression);
((IQueryable<Location>)mock).ElementType.Returns(dummyQueryable.ElementType);
((IQueryable<Location>)mock).GetEnumerator().Returns(dummyQueryable.GetEnumerator());
sut.DataContext.Locations = mock;

var result = await sut.Index();

result.Should().BeView();


sut.Index() doesn't do much, but it makes the following query:



await DataContext.Locations
.GroupBy(l => l.Area)
.ToListAsync());


This works fine until I add a projection into the query:



await DataContext.Locations
.GroupBy(l => l.Area)
.Select(l => new LocationsIndexVM{ Area = l.Key }) // added projection
.ToListAsync());


which results in this exception:



System.InvalidOperationException
The source IQueryable doesn't implement IDbAsyncEnumerable<LocationsIndexVM>. Only sources that implement IDbAsyncEnumerable can be used for Entity Framework asynchronous operations. For more details see http://ift.tt/1aRsSNY.
at System.Data.Entity.QueryableExtensions.AsDbAsyncEnumerable(IQueryable`1 source)
at System.Data.Entity.QueryableExtensions.ToListAsync(IQueryable`1 source)
at Example.Web.Controllers.HomeController.<Index>d__0.MoveNext() in HomeController.cs: line 25
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Example.Test.Web.Controllers.HomeControllerShould.<TempTest>d__4.MoveNext() in HomeControllerShould.cs: line 71


Can anyone provide an example of what is required to unit test a query that is both async and contains a .Select() projection?



asked 16 secs ago

nikmd23

5,587





svn read write permissions


Vote count:

0




I have a question about granting rights in svn. It is possible to take permissions like that?:


enter image description here


In short:


Admin can all in this project, read, write delete, change but User1 and User2 can only write his changes to svn. The best will be if every user(not Admin) have permissions only to his piece of project but cant delete anything. It is possible to do? I wrote some permissions in svn files but i never had that kind of perm. Can anybody tell me in short how to do that? Thanks.



asked 30 secs ago






Mvc and Web APIs filters


Vote count:

0




Please I need to know the difference between Mvc and Web apis attributes and I have created custom exception attribute in Web api how can I register it globally in mvc 4 we application


thanks



asked 39 secs ago






dimanche 30 mars 2014

Triggering an Event by KeyCombination in javaFX


Vote count:

0




I am trying to set a shortcut to save a file.



public static final KeyCombination saveShortcut = new KeyCodeCombination(KeyCode.S, KeyCombination.CONTROL_ANY);


I trigger an action by:



sceneRoot.addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if (saveShortcut.match(event)) {
saveProject.fire();
}
}

});


However, the event gets fired anytime I hit "S". Any ideas on why so?



asked 1 min ago