Saturday, 15 February 2014

Yodlee executeUserSearchRequest -



Yodlee executeUserSearchRequest -

am using yodlee integration in site. have used "executeusersearchrequest" api phone call perform search action based on user details.

i have analyzed documentation of yodlee in below link param properties. not clear in alternative of using user input. transactionsearchrequest.userinput in documentation.

what possible values can pass through transactionsearchrequest.userinput restrict search action. have given bank names in user input there no changes in retrived result.

note: have made alternative of "transactionsearchrequest.ignoreuserinput"=>'false' perform search based on given user input value.

any help welcomed. in advance.

the transactionsearchrequest.userinput parameter text filter. can used identify transactions based on description. can pass sequence of characters such "atm or wallmart, etc" transaction having specific description in it. if there no matching transaction description given input string result zero.

yodlee

cdecl and stdcall calling conventions in Native Nuget -



cdecl and stdcall calling conventions in Native Nuget -

i'm trying build native nuget bundle offers pivot on calling conventions, providing dlls both cdecl , stdcall conventions x86 builds. (most users prefer cdecl calling conventions, .net users p/invoke library prefer stdcall various reasons.)

my .autopkg contains both cdecl , stdcall pivots:

nuget { [nuspec omitted brevity] files { [win32,cdecl] { lib: build\x86-cdecl\debug\git2-0_21_0.lib; bin: build\x86-cdecl\debug\git2-0_21_0.dll; symbols: build\x86-cdecl\debug\git2-0_21_0.pdb; } [win32,stdcall] { lib: build\x86-stdcall\debug\git2-0_21_0.lib; bin: build\x86-stdcall\debug\git2-0_21_0.dll; symbols: build\x86-stdcall\debug\git2-0_21_0.pdb; } }; }

building .nupkg using native nuget scripts appears succeed , installing , using nuget bundle within standard c project (one cdecl calling conventions) succeeds.

however, if create new c project , set calling conventions stdcall , install nuget package, not stdcall version of library. instead, cdecl version installed , cannot link.

i optimistic nuget bundle manager observe project's configuration , utilize appropriate calling convention pivot (like processor type), not appear happen. nor given alternative select calling convention manually. yet fact there is pivot in autopkg configuration makes me think could select one.

how can take advantage of pivot?

nuget

c++ - Can't print Fibonacci series -



c++ - Can't print Fibonacci series -

i writing little snippet fibonacci number sequence depending on user input. if user supplies 4 input, should homecoming him first n members of fibonacci sequence.

#include <iostream> using namespace std; int main (){ int = 0; int b = 1; int c; int n = 3; n -= 2; if (n == 1){ cout << << endl; } else { cout << << b << endl; (int i=0;i<n;i++){ c = b + a; cout << c << endl; = b; b = c; } } }

however, end getting 0 output whatever number supply. have working in php , kinda miss i've blundered. guess don't render input , output properly.

int =0; int n = 3; n -= 2; if (n == 1){ cout << << endl; }

you have n equal 3, subtract 2, n equal 1, so, come in if body , output a, zero.

[edit]

you don't seem input -as stated in comment- in programme (you utilize std::cin or std::getline() this), mean have input hard-coded, changing value of n hand.

you may want check how fibonacci series programme expected work:

fib. @ rosseta page. fib. recursion non-recursive fib.

after reading links provided above, should able see code should changed this:

#include <iostream> using namespace std; int main (){ int = 1; int b = 0; int c; int n = 10; // "input" 10 if (n == 0 || n == 1) { // 0 , 1 case cout << n << endl; } else { (int = 2; <= n; ++i) { // here want reach n c = + b; b = a; = c; } cout << c << endl; } homecoming 0; }

however, code above outputs result. should modify terms of sequence, i'll leave have fun too.

in order allow user input number, change:

int n = 10;

to

int n; std::cout << "please, input.\n"; std::cin >> n;

however, letting user inputting must followed validation of input. see users can, accident or not, provide input in program, can cause undefined behaviour.

c++ fibonacci

variables - Rails no implicit conversion of Symbol into Integer -



variables - Rails no implicit conversion of Symbol into Integer -

i trying create private method counting based on database info follows.

class applicationcontroller < actioncontroller::base # prevent csrf attacks raising exception. # apis, may want utilize :null_session instead. protect_from_forgery with: :exception before_action :moderation_count private def moderation_count @count = ''; @count[:venues_pending] = venue.where(:is_approved => 0).count.to_i @count[:venues_rejected] = venue.where(:is_approved => 2).count.to_i @count[:venue_photos_pending] = venuephoto.where(:is_approved => 0).count.to_i @count[:venue_photos_rejected] = venuephoto.where(:is_approved => 2).count.to_i @count[:venue_reviews_pending] = venuereview.where(:is_approved => 0).count.to_i @count[:venue_reviews_rejected] = venuereview.where(:is_approved => 2).count.to_i end end

error:

no implicit conversion of symbol integer

you have set @count empty string with

@count = '';

so when @count[:venues_pending], ruby tries convert symbol :venues_pending integer access particular index of string @count. resulting in error no implicit conversion of symbol integer

as planning utilize instance variable @count hash, should instantiate hash rather empty string.

use @count = {}; or @count = hash.new;

ruby-on-rails variables ruby-on-rails-4

r - How to connect data dictionaries to the unlabeled data -



r - How to connect data dictionaries to the unlabeled data -

i'm working large authorities datasets section of transportation available tab-delimited text files accompanied info dictionaries. example, auto complaints file 670mb file of unlabeled info (when unzipped), , comes a dictionary. here excerpts:

last updated: apr 24, 2014 fields: ======= field# name type/size description ------ --------- --------- -------------------------------------- 1 cmplid char(9) nhtsa's internal unique sequence number. updateable field,thus info given record potentially alter 1 info output file next. 2 odino char(9) nhtsa's internal reference number. number may repeated multiple components. also, if ldate prior dec 15, 2002, number may repeated multiple products owned same complainant.

some of fields have foreign keys listed so:

21 cmpl_type char(4) source of complaint code: cag =consumer action grouping con =forwarded congressional office dp =defect petition,result of defect petition evoq =hotline voq ewr =early warning reporting ins =insurance company ivoq =nhtsa web site letr =consumer letter mavq =nhtsa mobile app mivq =nhtsa mobile app mvoq =optical marked voq rc =recall complaint,result of recall investigation rp =recall petition,result of recall petition svoq =portable safety complaint form (pdf) voq =nhtsa vehicle owners questionnaire

there import instructions microsoft access, don't have , not utilize if did. think info dictionary meant machine-readable.

my question: info dictionary standard format of kind? i've tried google around, it's hard without right terminology. import r, though i'm flexible long can done programmatically.

r ms-access data-dictionary

bash-completion for scp on a different port -



bash-completion for scp on a different port -

i've installed bash-completion-20060301-1 gives auto completion of remove directories when using scp. problem have many servers utilize ssh via port 26. how can modify completion in order note if -p26 specified in scp command line?

thanks!

this work if add together such servers ssh_config, i.e. ~/.ssh/config.

host weirdbox user maxim hostname 10.9.8.7 port 26

tab completing scp weirdbox: work then.

bash scp bash-completion

eclipse - What does this Android Runtime logCat error mean? -



eclipse - What does this Android Runtime logCat error mean? -

i'm new android programming , eclipse. have hard time undersanding logcat errors mean , prepare them. i'm used visual studios tells me error located at. of classes shows me arent classes have created, built in ones i'm confused..

logcat:

06-26 09:03:56.201: e/androidruntime(3428): fatal exception: main 06-26 09:03:56.201: e/androidruntime(3428): java.lang.runtimeexception: unable instantiate activity componentinfo{com.example.basicscanner/com.example.basicscanner.mainactivity}: java.lang.classnotfoundexception: com.example.basicscanner.mainactivity in loader dalvik.system.pathclassloader[/data/app/com.example.basicscanner-1.apk] 06-26 09:03:56.201: e/androidruntime(3428): @ android.app.activitythread.performlaunchactivity(activitythread.java:1569) 06-26 09:03:56.201: e/androidruntime(3428): @ android.app.activitythread.handlelaunchactivity(activitythread.java:1663) 06-26 09:03:56.201: e/androidruntime(3428): @ android.app.activitythread.access$1500(activitythread.java:117) 06-26 09:03:56.201: e/androidruntime(3428): @ android.app.activitythread$h.handlemessage(activitythread.java:931) 06-26 09:03:56.201: e/androidruntime(3428): @ android.os.handler.dispatchmessage(handler.java:99) 06-26 09:03:56.201: e/androidruntime(3428): @ android.os.looper.loop(looper.java:130) 06-26 09:03:56.201: e/androidruntime(3428): @ android.app.activitythread.main(activitythread.java:3683) 06-26 09:03:56.201: e/androidruntime(3428): @ java.lang.reflect.method.invokenative(native method) 06-26 09:03:56.201: e/androidruntime(3428): @ java.lang.reflect.method.invoke(method.java:507) 06-26 09:03:56.201: e/androidruntime(3428): @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:839) 06-26 09:03:56.201: e/androidruntime(3428): @ com.android.internal.os.zygoteinit.main(zygoteinit.java:597) 06-26 09:03:56.201: e/androidruntime(3428): @ dalvik.system.nativestart.main(native method) 06-26 09:03:56.201: e/androidruntime(3428): caused by: java.lang.classnotfoundexception: com.example.basicscanner.mainactivity in loader dalvik.system.pathclassloader[/data/app/com.example.basicscanner-1.apk] 06-26 09:03:56.201: e/androidruntime(3428): @ dalvik.system.pathclassloader.findclass(pathclassloader.java:240) 06-26 09:03:56.201: e/androidruntime(3428): @ java.lang.classloader.loadclass(classloader.java:551) 06-26 09:03:56.201: e/androidruntime(3428): @ java.lang.classloader.loadclass(classloader.java:511) 06-26 09:03:56.201: e/androidruntime(3428): @ android.app.instrumentation.newactivity(instrumentation.java:1021) 06-26 09:03:56.201: e/androidruntime(3428): @ android.app.activitythread.performlaunchactivity(activitythread.java:1561)

it means compiler not able find class, maybe because haven't defined in android manifest or maybe path class not right;)

android eclipse debugging android-logcat

javascript - Click a button programmatically - JS -



javascript - Click a button programmatically - JS -

i've seen done in other webapps, i'm new javascript , can't figure out on own. want create google hangout programmatically. however, in official api way can create hangout including hangout button on page.

here's google doc on hangouts button.

what want have user click img of user , open hangout way. seems capture click , 'click' hangouts button in background. however, i'm not javascript wouldn't know how accomplish this.

edit

i tried mohamedrais' solution below no luck. class of button?

here's code button, taken hangouts docs added id:

<script type="text/javascript" src="https://apis.google.com/js/platform.js"></script> <div class="g-hangout" id="hangout-gilkojrpuk" data-render="createhangout"> </div>

here's js added, rendered ids:

<script> window.onload = function() { var userimage = document.getelementbyid("img-gilkojrpuk"); var hangoutbutton = document.getelementbyid("hangout-gilkojrpuk"); userimage.onclick = function() { console.log("in onclick"); hangoutbutton.click(); // trigger click event }; }; </script>

when click img, "in onclick" getting logged, function getting called. however, nil happens - hangouts isn't launched.

when click straight on hangouts button launch hangouts. however, want hide , perform click image.

here's image of hangouts button above img:

window.onload = function() { var userimage = document.getelementbyid('imageotheruser'); var hangoutbutton = document.getelementbyid("hangoutbuttonid"); userimage.onclick = function() { hangoutbutton.click(); // trigger click event }; };

this trick

javascript

javascript - Angular.js - making function available in other controllers -



javascript - Angular.js - making function available in other controllers -

i have angular controller called submissiontreecontroller , has update_dashboard() function refreshes ui every minute.

my goal refresh ui on successful post request different controller.

how create function available in other controllers?

var module = angular.module("submissiondashboard", ['ui.tree', 'ngcookies', 'ui.bootstrap',]); module.controller("submissiontreecontroller", ["$scope", "$http", "$modal", function($scope, $http, $modal) { $scope.selected_items = {}; var update_dashboard = function() { var url = django.url('submission:active_list_ajax', { site : site }); $http.get(url).success(function(data) { $scope.list = data.results; }); }; update_dashboard(); $scope.closetask = function(scope) { var modalinstance = $modal.open({ templateurl: 'modal_close_submission_renderer.html', controller: 'modalclosesubmissioncontroller', resolve: { items: function () { homecoming $scope.selected_items; }} }); }; }]); module.controller('modalclosesubmissioncontroller', ['$scope', '$modalinstance', '$http', 'items', function ($scope, $modalinstance, $http, items) { $scope.items = items; $scope.selected = { item: 1, text: '' }; $scope.ok = function () { var val = $scope.selected.item; if (val === 1) { var url = django.url('submission:close-notify', { site : site }); $http.post(url, $scope.selected_items).success(function(data) { update_dashboard(); }); } else if (val === 2) { var url = django.url('submission:close', { site : site }); $http.post(url, $scope.selected_items).success(function(data) { update_dashboard(); }); } else if (val === 3) { var url = django.url('submission:cancel', { site : site }); $http.post(url, $scope.selected_items).success(function(data) { update_dashboard(); }); }; $modalinstance.close($scope.selected.item); }; $scope.cancel = function () { $modalinstance.dismiss('cancel'); }; }]);

edit:

what trying do:

module.service('updatedashboardservice', function($scope, $http){ this.update_dashboard = function() { $scope = $scope; var url = django.url('submission:active_list_ajax', { site : site }); $http.get(url).success(function(data) { $scope.list = data.results; }); }; }); module.controller("submissiontreecontroller", ["$scope", "$http", "$modal", "updatedashboardservice", function($scope, $http, $modal, updatedashboardservice) { $scope.selected_items = {}; updatedashboardservice.update_dashboard(); var timer = setinterval(function() { $scope.$apply(updatedashboardservice.update_dashboard($scope, $http)); }, 1000 * 60);

what getting: error: [$injector:unpr] unknown provider: $scopeprovider <- $scope <- updatedashboardservice

edit 2:

module.service('updatedashboardservice', function($rootscope, $http){ this.update_dashboard = function() { var url = django.url('submission:active_list_ajax', { site : site }); $http.get(url).success(function(data) { $rootscope.list = data.results; }); }; });

as @gopesh says create mill method, or, can in submissiontreecontroller:

$scope.$on("event:updatedashboard", function(){ update_dashboard() });

and in other controller:

$http.post(url, $scope.selected_items).success(function(data) { $scope.$emit("event:updatedashboard"); });

javascript angularjs

concept - SSAO, Opmizations and pipelines using OpenSceneGraph -



concept - SSAO, Opmizations and pipelines using OpenSceneGraph -

i have questions ssao technique implementation:

does need sec (or more) pipeline every geometry? mean, found tutorials , stuff give directions without entering in farther details.

is there optimization possible? i'm using osg , i've got impression if send textures cpu , throwing 1 time again gpu isn't best solution possible.

is possible create shaders generate texture samples depth in buffer , send sec pipe line using quad screen, colors, depth of scene , depth tests? i'm using osg , couldn't find how in documentations.

in general, ssao best suited beingness implemented part of deferred shading approach. strictly forwards shading approach possible, still require 2 rendering passes, , ssao can added sec rendering pass of deferred shading engine. in ssao, need finish depth buffer of scene able calculate occlusion, short reply section 1 of question yes, ssao requires 2 rendering passes.

note in deferred shading, although there 2 rendering passes, complex geometry (i.e. models) rendered during first pass, , sec pass made of simple polygon shapes rendered each type of light. you're suggesting in section 3 of question.

with regards section 2 of question, when set correctly, shouldn't need move intermediate textures cpu , gpu between 2 rendering passes; simply create first rendering pass's textures available resource sec rendering pass.

openscenegraph concept ssao

performance - Expensiveness of inheritance and nesting within protobuf-net serialization -



performance - Expensiveness of inheritance and nesting within protobuf-net serialization -

i using protobuf-net within high-performance wcf services. serialized objects have:

an inheritance depth of 3-4 levels (child class root class -> flattened well) a nesting of objects of 3-4 levels (objects containing objects -> flattened well)

is there considerable overhead in dealing inheritance , nesting give reason flatten max?

thank insights.

performance wcf serialization protobuf-net

php - process to disable cross domain request -



php - process to disable cross domain request -

i want disable cross domain ajax request.

what mean if im posting info through ajax phone call like

var request = $.ajax({ url: 'uploadfiles.php', type: 'post', data: data, cache: false, contenttype: false, processdata: false, beforesend: function( ) { $(".progressbar").show(); }, xhr: function() { var xhr = $.ajaxsettings.xhr(); if(xhr.upload){ xhr.upload.addeventlistener( 'progress', showprogress, false); } homecoming xhr; }, success: function(data){ if( percentcomplete <= 100 ) { $('#pb div').animate({ width: '100%' }, { step: function(now) { $(this).text( math.round(now) + '%' ); }, duration: 10}); ajaxloading = false; } $('#uplcomp').append( info ); } }); }

if 1 trying post uploadfiles.php through ajax request domain , how can prevent access uploadfiles.php

i want allow domain send info through ajax call

after googling found solution:

$http_origin = $_server['http_origin']; if ($http_origin == "http://www.domain1.com" || $http_origin == "http://www.domain2.com" || $http_origin == "http://www.domain3.info") { header("access-control-allow-origin: $http_origin"); }

where have utilize above code. in uploadfiles.php ?

updated : have used in uploadfiles.php

displays : notice

**undefined index: http_origin**

updated 2

how can utilize statement

content-security-policy: script-src 'self' https://apis.google.com

do have mention php config files or in filesupload.php

what above statement do?

php jquery ajax security content-security-policy

Google App engine: No key_name attribute -



Google App engine: No key_name attribute -

i'm trying larn how gae, things working, unusual reason, code outputs

attributeerror: 'user_account' object has no attribute 'key_name'

here's 2 code extracts relevant:

class user_account(ndb.model): name = ndb.stringproperty() firstname = ndb.stringproperty() class adduser(webapp2.requesthandler): def get(self): test_user = user_account(name = "snow", firstname ="jon", key_name="jon")

i've tried db , ndb model, doesn't work either way...

thanks in advance answer.

update: here's "full" code (i removed other un-necessary parts):

import webapp2 import cgi google.appengine.ext import ndb main_page_html = """\ <html> <body> <br/> <a href="/add_user"> add together user </a> </body> </html> """ class comment(ndb.model): content = ndb.stringproperty() class user_account(ndb.model): name = ndb.stringproperty() firstname = ndb.stringproperty() comments = ndb.keyproperty(repeated=true) class adduser(webapp2.requesthandler): def get(self): test_user = user_account(name = "jon", firstname ="snow", key_name="jon") self.response.write(test_user.key_name + "<br/>") test_user.put() self.response.write("user added") class mainpage(webapp2.requesthandler): def get(self): self.response.write(main_page_html) application = webapp2.wsgiapplication([ ('/', mainpage), ('/add_user', adduser) ], debug=true)

moar edit: simple code, when executed in dev console, outputs error

import os import pprint google.appengine.ext import ndb class comment(ndb.model): content = ndb.stringproperty() test_comment = comment(content="hello world", key_name="hello") test_comment.put()

please read documentation ndb model class. on model constructor arguments. https://developers.google.com/appengine/docs/python/ndb/modelclass#constructor

you see takes id, rather than key_name. key_name constructor argument db api.

google-app-engine google-datastore

php - how to fetch linkedin data in codeigniter -



php - how to fetch linkedin data in codeigniter -

i using codeigniter , want fetch linkedin info not works.. getting no error not fetch info using code defined in next url:

linkedin php api not setting access token in codeigniter

and codes are

create library:

defined('basepath') or exit('no direct script access allowed'); class linkedin { function __construct(){ } public function getauthorizationcode() { $params = array('response_type' => 'code', 'client_id' => api_key, 'scope' => scope, 'state' => uniqid('', true), // unique long string 'redirect_uri' => redirect_uri, ); // authentication request $url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params); // needed identify request when returns $_session['state'] = $params['state']; // redirect user authenticate header("location: $url"); exit; } public function getaccesstoken() { $params = array('grant_type' => 'authorization_code', 'client_id' => api_key, 'client_secret' => api_secret, 'code' => $_get['code'], 'redirect_uri' => redirect_uri, ); // access token request $url = 'https://www.linkedin.com/uas/oauth2/accesstoken?' . http_build_query($params); // tell streams create post request $context = stream_context_create( array('http' => array('method' => 'post', ) ) ); // retrieve access token info $response = file_get_contents($url, false, $context); // native php object, please $token = json_decode($response); // store access token , expiration time $_session['access_token'] = $token->access_token; // guard this! $_session['expires_in'] = $token->expires_in; // relative time (in seconds) $_session['expires_at'] = time() + $_session['expires_in']; // absolute time homecoming true; } public function fetch($method, $resource, $body = '') { $params = array('oauth2_access_token' => $_session['access_token'], 'format' => 'json', ); // need utilize https $url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params); // tell streams create (get, post, put, or delete) request $context = stream_context_create( array('http' => array('method' => $method, ) ) ); // hocus pocus $response = file_get_contents($url, false, $context); // native php object, please homecoming json_decode($response); } }

put constants stuff in confin/constants.php

define('api_key', 'put yoour api_key here'); define('api_secret', 'put yoour api_secret here'); define('redirect_uri', 'put yoour redirect_uri here'); define('scope', 'r_fullprofile r_emailaddress rw_nus r_contactinfo r_network');

and create controller

class profile extends ci_controller { function __construct() { parent:: __construct(); $this->load->library('linkedin'); // load library session_name('linkedin'); session_start(); } // linkedin login script function profile() { // oauth 2 command flow if (isset($_get['error'])) { // linkedin returned error // load error view here exit; } elseif (isset($_get['code'])) { // user authorized application if ($_session['state'] == $_get['state']) { // token can create api calls $this->linkedin->getaccesstoken(); } else { // csrf attack? or did mix states? exit; } } else { if ((empty($_session['expires_at'])) || (time() > $_session['expires_at'])) { // token has expired, clear state $_session = array(); } if (empty($_session['access_token'])) { // start authorization process $this->linkedin->getauthorizationcode(); } } // define array of profile fields $profile_fileds = array( 'id', 'firstname', 'maiden-name', 'lastname', 'picture-url', 'email-address', 'location:(country:(code))', 'industry', 'summary', 'specialties', 'interests', 'public-profile-url', 'last-modified-timestamp', 'num-recommenders', 'date-of-birth', ); $profiledata = $this->linkedin->fetch('get', '/v1/people/~:(' . implode(',', $profile_fileds) . ')'); if ($profiledata) { $this->session->set_userdata("profile_session",$profiledata); } else { // linked homecoming empty array of profile info } } }

when running controller linkedin api works modal window appears app name ..but after login when trying print session not apppears... dont know code working or not.. please help

this should work:

linkedin class:

class linkedin extends ci_controller { function __construct(){ parent:: __construct(); $this->load->library('session'); } public function getauthorizationcode() { $params = array('response_type' => 'code', 'client_id' => api_key, 'scope' => scope, 'state' => uniqid('', true), // unique long string 'redirect_uri' => redirect_uri, ); // authentication request $url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params); // needed identify request when returns $this->session->set_userdata('state',$params['state']); // redirect user authenticate header("location: $url"); exit; } public function getaccesstoken() { $params = array('grant_type' => 'authorization_code', 'client_id' => api_key, 'client_secret' => api_secret, 'code' => $_get['code'], 'redirect_uri' => redirect_uri, ); // access token request $url = 'https://www.linkedin.com/uas/oauth2/accesstoken?' . http_build_query($params); // tell streams create post request $context = stream_context_create( array('http' => array('method' => 'post', ) ) ); // retrieve access token info $response = file_get_contents($url, false, $context); // native php object, please $token = json_decode($response); // store access token , expiration time $ses_params = array('access_token' => $token->access_token, 'expires_in' => $token->expires_in, 'expires_at' => time() + $_session['expires_in']); $this->session->set_userdata($ses_params); homecoming true; } public function fetch($method, $resource, $body = '') { $params = array('oauth2_access_token' => $_session['access_token'], 'format' => 'json', ); // need utilize https $url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params); // tell streams create (get, post, put, or delete) request $context = stream_context_create( array('http' => array('method' => $method, ) ) ); // hocus pocus $response = file_get_contents($url, false, $context); // native php object, please homecoming json_decode($response); } }

profile controller:

class profile extends ci_controller { function __construct() { parent:: __construct(); $this->load->library('linkedin'); // load library $this->load->library('session'); } // linkedin login script function profile() { // oauth 2 command flow if (isset($_get['error'])) { // linkedin returned error // load error view here exit; } elseif (isset($_get['code'])) { // user authorized application if ($this->session->userdata('state'); == $_get['state']) { // token can create api calls $this->linkedin->getaccesstoken(); } else { // csrf attack? or did mix states? exit; } } else { if ((empty($this->session->userdata('expires_at'))) || (time() > $this->session->userdata('expires_at'))) { // token has expired, clear state $this->session->sess_destroy(); } if (empty($this->session->userdata('access_token'))) { // start authorization process $this->linkedin->getauthorizationcode(); } } // define array of profile fields $profile_fileds = array( 'id', 'firstname', 'maiden-name', 'lastname', 'picture-url', 'email-address', 'location:(country:(code))', 'industry', 'summary', 'specialties', 'interests', 'public-profile-url', 'last-modified-timestamp', 'num-recommenders', 'date-of-birth', ); $profiledata = $this->linkedin->fetch('get', '/v1/people/~:(' . implode(',', $profile_fileds) . ')'); if ($profiledata) { $this->session->set_userdata("profile_session",$profiledata); } else { // linked homecoming empty array of profile info } } }

php codeigniter linkedin

algorithm - Compress many numbers into a string -



algorithm - Compress many numbers into a string -

i wondering if there's way compress 20 or big numbers (~10^8) string of reasonable length. instance, if numbers stored hex , concatenated, it'd @ to the lowest degree 160 characters long. wonder if there's smart way compress numbers in , them out. thinking having sequence 0-9 reference , allow 1 part of input string number <1024. number converted binary, serves mask, i.e. indicating digits exist in number. it's still not clear go on here.

are there improve alternatives?

thanks

if these big numbers of same size in bytes, , if know count of numbers, there easy way it. have array of bytes, , instead of reading them out integers, read them out characters. trying obfuscate values or pack them transferred?

algorithm compression

.net - How to use `Me` in vb.net With...End With block -



.net - How to use `Me` in vb.net With...End With block -

with code "vb.net 2005"

dim dep new section dep.addnewemployee() .firstname = "mr. a" .lastname = "b" if typeof {dep.addnewemployee()'s instance} serializable 'do end if end

in {dep.addnewemployee()'s instance} there syntax code.

is possible?

there no way using with syntax. add together local variable references new object though:

dim dep new section dim emp = dep.addnewemployee() emp .firstname = "mr. a" .lastname = "b" if emp.gettype().isserializable 'do end if end

.net vb.net instance with-statement

Export Datatable to Excel vb.net -



Export Datatable to Excel vb.net -

i trying export datatable excel in 2013 visual studio express web. while generating excel file, application throwing next error (see image attached)

-- code export

private function convertdttotdf(byval dt datatable, byval filename string) string dim dr datarow, ary() object, integer dim icol integer httpcontext.current.response.clear() httpcontext.current.response.addheader("content-disposition", "attachment;filename=" & filename & ".xls") httpcontext.current.response.charset = "" httpcontext.current.response.contenttype = "application/vnd.xls" 'output column headers icol = 0 dt.columns.count - 1 response.write(dt.columns(icol).tostring & vbtab) next response.write(vbcrlf) 'output info each dr in dt.rows ary = dr.itemarray = 0 ubound(ary) response.write(ary(i).tostring & vbtab) next response.write(vbcrlf) next httpcontext.current.response.end() end function

vb.net excel visual-studio-2013 export

xml - Find an Attribute based off Attribute in same element using XmlDocument -



xml - Find an Attribute based off Attribute in same element using XmlDocument -

i looking loop thru element based off 1 attribute, "sequence" , retrieve another, "strokes".

my xml follows:

<tournament> <leaderboard> <player first_name="jimmy" last_name="walker" country="united states" id="2db60f6e-7b0a-4daf-97d9-01a057f44f1d" position="1" money="900000.0" points="500.0" score="-17" strokes="267"> <rounds> <round score="-1" strokes="70" thru="18" eagles="0" birdies="5" pars="9" bogeys="4" double_bogeys="0" other_scores="0" sequence="1"/> <round score="-2" strokes="69" thru="18" eagles="0" birdies="3" pars="14" bogeys="1" double_bogeys="0" other_scores="0" sequence="2"/> <round score="-9" strokes="62" thru="18" eagles="0" birdies="10" pars="7" bogeys="1" double_bogeys="0" other_scores="0" sequence="3"/> <round score="-5" strokes="66" thru="18" eagles="0" birdies="6" pars="11" bogeys="1" double_bogeys="0" other_scores="0" sequence="4"/> </rounds> </player> </leaderboard> </tournament>

i able retrieve individual round elements based on next code:

// edited reflect solution

foreach (xmlnode player in doc.getelementsbytagname("player")) { string strokes; dtattributelist.rows.add( player.attributes["last_name"].value, player.attributes["first_name"].value, player.attributes["position"].value, player.attributes["score"].value); if (player.haschildnodes) { foreach (xmlnode round in player.lastchild) { strokes = round.attributes["strokes"].value; dtattributelist.rows.add(strokes); } } }

however in doing able retrieve first element , values.

please help me find solution loop thru "round" elements either via filter on sequence or loop of sort.

it's much easier utilize xpath approach you've tried above. you're creating huge amount of duplicate code using for loop instead of foreach:

foreach (xmlnode player in doc.getelementsbytagname("player")) { string strokes; dtattributelist.rows.add( player.attributes["last_name"].value, player.attributes["first_name"].value, player.attributes["position"].value, player.attributes["score"].value); foreach (xmlnode round in player.selectnodes("rounds/round")) { strokes = round.attributes["strokes"].value; dtattributelist.rows.add(strokes); } }

if need iterate throug them based on order of sequence (and they're not in order), can this:

var rounds = player.selectnodes("rounds/round") .oftype<xmlnode>() .orderby(n => int.parse(n.attributes["sequence"].value)); foreach (xmlnode round in rounds) { // ... }

xml xml-parsing

database - how to implement nested comment system using redis efficiently -



database - how to implement nested comment system using redis efficiently -

i'm trying implement nested comment scheme using redis, illustration every article can have comments first layer comments, first layer comments can commented , create sec layer comments, , on, can have infinite layers. i'm using hashs, each key represents article, 1 field article info , 1 field comment, value of comment in xml format tags comment ids nested kid nodes. it's inefficient because each seek retrieve comment, have of them whole. wondering if there's other more efficient way this? thanks

i think first step thinking in relational database. example, simple scheme have next schema:

article ( id int, name text, body text ) comment ( id int, article_id int, parent int, author text, body text )

converting redis takes little thinking. want create sure info structures utilize right ones provide fastest times. here different keys/key structures utilize in implementing system:

article:<id> - hash stores article info , has next keys: name - name of article body - body text of article article-id - auto-increment value article ids article-comments:<id> - set of comment ids top-level comments on article id <id> comment:<id> - has stores comment info , has next keys: author - comment author body - body text of comment comment-id - auto-increment value comment ids comment-children:<id> - set of comment ids represent comments replys comment id <id>

the steps adding new comment follows:

increment comment-id create new hash key concatination of comment: , value homecoming in step 1 fill in hash created in step 2 comment data if comment not have parent, add together id appropriate article-comments:<id> set. if have parent, add together appropriate comment-children:<id> set.

database redis

matlab - How to implement a conditional random field based energy function from images? -



matlab - How to implement a conditional random field based energy function from images? -

i trying implement segmentation tool images, , trying utilize conditional random field (crf) based method. example, in this paper.

the standard crf energy function includes 2 parts, i.e., unary potential , pairwise potential

where l class labels , x observations (image pixels).

i have got training image labels of objects in image. example, have got ground truth segmentation of objects in image labels.

if want utilize texture of these objects feature, wondering how implement , training of energy function? example, unary term can represented by

where v_texture vectorised texture feature of each labelled object.

my question how implement log probability function? using histogram? thanks. a.

matlab image-processing computer-vision image-segmentation crf

javascript - Unable to run show image preview on android webview? -



javascript - Unable to run show image preview on android webview? -

firstly may sound duplicate question unable solutions via previous posted questions.i have jsp page through selecting images pc , showing preview of image working fine on chrome browser of android phone also.but when run on webview document.getelementbyid.click() function not working unable image preview.

this jsp page:

<!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>jsp page</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <script> function img_prvw(id1,id2)/*******************show preview of image*******************/ { var ofiles = document.getelementbyid(id1).files; var valid_extensions = /(.jpg|.jpeg|.png)$/i; if(!(valid_extensions.test(document.getelementbyid(id1).files[0].name))) { document.getelementbyid('er').innerhtml="select jpg or png image"; } else { var reader = new filereader(); reader.readasdataurl(ofiles[0]); reader.onload= function (e) { document.getelementbyid(id2).src=e.target.result; }; } } </script> </head> <body> <input type="file" style="display: none;" id="advrts_img" name="advrts_img" onchange="img_prvw('advrts_img','advrts_img_prvw')"> <img src="images/img_place.png" id="advrts_img_prvw" alt="" class="cursor margin_top10" style="width:100px;height:100px" onclick="document.getelementbyid('advrts_img').click()"> </body> </html>

this android webview code:

package com.example.sample_webview; import android.app.activity; import android.content.intent; import android.content.res.configuration; import android.graphics.bitmap; import android.net.uri; import android.os.bundle; import android.view.view; import android.webkit.valuecallback; import android.webkit.webchromeclient; import android.webkit.webview; import android.webkit.webviewclient; import android.widget.progressbar; public class mainactivity extends activity { /** called when activity first created. */ webview web; private valuecallback<uri> muploadmessage; private final static int filechooser_resultcode = 1; @override protected void onactivityresult(int requestcode, int resultcode, intent intent) { if (requestcode == filechooser_resultcode) { if (null == muploadmessage) return; uri result = intent == null || resultcode != result_ok ? null : intent.getdata(); muploadmessage.onreceivevalue(result); muploadmessage = null; } } @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); web = (webview) findviewbyid(r.id.wview); web = new webview(this); web.getsettings().setjavascriptenabled(true); web.loadurl("http://minkme.org/minkmeuser/image_preview1.jsp"); web.setwebviewclient(new mywebclient()); web.setwebchromeclient(new webchromeclient() { // undocumented magic method override // eclipse swear @ if seek set @override here // android 3.0+ public void openfilechooser(valuecallback<uri> uploadmsg) { muploadmessage = uploadmsg; intent = new intent(intent.action_get_content); i.addcategory(intent.category_openable); i.settype("image/*"); mainactivity.this.startactivityforresult( intent.createchooser(i, "file chooser"), filechooser_resultcode); } // android 3.0+ public void openfilechooser(valuecallback uploadmsg, string accepttype) { muploadmessage = uploadmsg; intent = new intent(intent.action_get_content); i.addcategory(intent.category_openable); i.settype("*/*"); mainactivity.this.startactivityforresult( intent.createchooser(i, "file browser"), filechooser_resultcode); } // android 4.1 public void openfilechooser(valuecallback<uri> uploadmsg, string accepttype, string capture) { muploadmessage = uploadmsg; intent = new intent(intent.action_get_content); i.addcategory(intent.category_openable); i.settype("image/*"); mainactivity.this.startactivityforresult( intent.createchooser(i, "file chooser"), mainactivity.filechooser_resultcode); } }); setcontentview(web); } public class mywebclient extends webviewclient { @override public void onpagestarted(webview view, string url, bitmap favicon) { // todo auto-generated method stub super.onpagestarted(view, url, favicon); } @override public boolean shouldoverrideurlloading(webview view, string url) { // todo auto-generated method stub view.loadurl(url); homecoming true; } @override public void onpagefinished(webview view, string url) { // todo auto-generated method stub super.onpagefinished(view, url); } } // flipscreen not loading 1 time again @override public void onconfigurationchanged(configuration newconfig) { super.onconfigurationchanged(newconfig); } // handle "back" key press event webview go previous // screen. /* * @override public boolean onkeydown(int keycode, keyevent event) { if * ((keycode == keyevent.keycode_back) && web.cangoback()) { web.goback(); * homecoming true; } homecoming super.onkeydown(keycode, event); } */ }

i want browse images android phone using input type="file".

in short : on here input file input file in webview

after time , test, have found document.getelementbyid.click work well. have test next change

test.html

<!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>jsp page</title> <script src="jquery-1.11.1.min.js"> </script> <script> function img_prvw(id1,id2)/*******************show preview of image*******************/ { console.log("call of img_prvw"); var ofiles = document.getelementbyid(id1).files; var valid_extensions = /(.jpg|.jpeg|.png)$/i; if(!(valid_extensions.test(document.getelementbyid(id1).files[0].name))) { document.getelementbyid('er').innerhtml="select jpg or png image"; } else { var reader = new filereader(); reader.readasdataurl(ofiles[0]); reader.onload= function (e) { document.getelementbyid(id2).src=e.target.result; }; } } function onadvrtsimgprvwclick() { console.log('clickevent'); document.getelementbyid('advrts_img').click(); } </script> </head> <body> <input type="file" style="display: none;" id="advrts_img" name="advrts_img" onclick="console.log('click on input');" onchange="img_prvw('advrts_img','advrts_img_prvw')"> <img src="images/img_place.png" id="advrts_img_prvw" alt="" class="cursor margin_top10" style="width:100px;height:100px" onclick="onadvrtsimgprvwclick()"> </body> </html>

mainactivity.java

public class mainactivity extends activity { private webview mwebview; static final string tag = "mainactivity"; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); mwebview = (webview) findviewbyid(r.id.webview1); mwebview.getsettings().setjavascriptenabled(true); // enable javascript final activity activity = this; mwebview.setwebviewclient(new webviewclient() { public void onreceivederror(webview view, int errorcode, string description, string failingurl) { toast.maketext(activity, description, toast.length_short) .show(); } }); mwebview.setwebchromeclient(new webchromeclient() { @override public boolean onconsolemessage(consolemessage cm) { string msg = cm.message() + " -- line " + cm.linenumber() + " of " + cm.sourceid(); switch (cm.messagelevel()) { case error: log.e(tag, msg); break; case log: case tip: log.i(tag, msg); break; case warning: log.w(tag, msg); break; case debug: default: log.d(tag, msg); break; } homecoming true; } }); mwebview.loadurl("file:///android_asset/test.html"); //setcontentview(mwebview); } }

and it's appear console show message 'click on input', have been correctly call, it's on alter not called properly.

javascript android jsp webview

php - Maximum execution time of 300 seconds exceeded, can't change max_execution_time -



php - Maximum execution time of 300 seconds exceeded, can't change max_execution_time -

i'm running wordpress installaction on localhost, using xampp.

i made backup using wp clone plugin, , i'm trying restore on localhost version.

after time, message:

fatal error: maximum execution time of 300 seconds exceeded in c:\xampp\htdocs\sbc\wp-admin\includes\class-wp-filesystem-direct.php on line 217

i tried several times, , same error always. difference happens on different files.

i tried changing value of max_execution_time 30 1000 in php.ini (and restarting xampp afterwards) , didn't help.

any ideas?

make sure you're changing right ini.

<?php phpinfo(); ?>

you can alter value in .htaccess:

<ifmodule mod_php5.c> php_value max_execution_time 1000 </ifmodule>

php xampp

In Raphael, what's the difference between a Paper and a Raphael? -



In Raphael, what's the difference between a Paper and a Raphael? -

according raphael documentation, there 2 different entities paper , raphael. difference between two? "paper" means "raphael canvas" , "raphael" refers methods can done when raphael bundle installed in general?

as far understand spot on. paper referring particular element raphael render to. raphael methods static methods: can called without creating paper instance. have several papers on given web page, you'll have 1 raphael. simple way think them may paper canvas, , raphael library has static methods.

raphael

python - Check if key is in the dictionary? -



python - Check if key is in the dictionary? -

this question has reply here:

check if given key exists in dictionary 12 answers

how check if there key in dictionary?

here dictionary:

edges = {(1, 'a') : 2, (2, 'a') : 2, (2, '1') : 3, (3, '1') : 3}

i have tried this:

if edges[(1, 'a')]

but error:

traceback (most recent phone call last): file "vm_main.py", line 33, in <module> import main file "/tmp/vmuser_lvzelvvmfq/main.py", line 30, in <module> print fsmsim("aaa111",1,edges,accepting) file "/tmp/vmuser_lvzelvvmfq/main.py", line 16, in fsmsim if edges[(1, 'a')]: typeerror: 'dict' object not callable

what right way it?

just utilize in operator (which accompanied not in operator):

if (1, 'a') in edges: if (1, 'a') not in edges:

below excerpt documentation of python's dictionary type, d dictionary:

key in d

return true if d has key key, else false.

key not in d

equivalent not key in d.

python python-2.7 dictionary

html - CSS nested div height 100% doesn't work -



html - CSS nested div height 100% doesn't work -

i hope can help me problem. have construction this

<div id="div1" style="height:auto"> <div id="div2" style="height:100%;"> <div id="div3" style="min-height:100%;"></div> <div id="div4" style="height:100%;"></div> </div> </div>

also set in css file

html,body { height: 100%; }

problem neither div3 nor div4 have expected height of 100%, check size of first 2 divs firbug , ok, filling whole screen.

sorry bad english, hope understand question :)

have @ this. when using percentage, each div affected height of it's parent.

in illustration html,body has height of 100% , percentage of each div kid relative it's parent. note how each div half size of it's parent div, each step shrinks half size.

updated percentage example

simple example

html

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

css

html, body { height: 100%; } div { height: 100%; background: #f00; } div div { background: #ff0; height: 50%; } div div div { background: #000; height: 50%; } div div div div { background: #f30; height: 50%; }

html css height

Redirect using .htaccess from a PHP page to another both with variables -



Redirect using .htaccess from a PHP page to another both with variables -

i have simple question, cant find way it. need redirect or rewrite this:

http://mydomain.com/libro.php?isbn=9788493652470

to this:

http://mydomain.com/busqueda.php?busqueda=medimecum

i have tried doesn’t work:

redirect 301 /libro.php?isbn=9788493652470 http://mydomain.com/busqueda.php?busqueda=medimecum

a straight redirect not work well. using mod_rewrite rewritecond query string work well. should work example:

rewriteengine on rewritecond %{query_string} isbn=9788493652470 rewriterule ^libro.php http://mydomain.com/busqueda.php?busqueda=medimecum [l,r=301]

now looking @ question 1 time again it’s not clear if want pass along original query string, correct? url:

http://mydomain.com/libro.php?isbn=9788493652470

would become url:

http://mydomain.com/busqueda.php?busqueda=medimecum&isbn=9788493652470

but if somehow wanted that, add together qsa (query string append) flag rewriterule this:

rewriteengine on rewritecond %{query_string} isbn=9788493652470 rewriterule ^libro\.php http://mydomain.com/busqueda.php?busqueda=medimecum [l,r=301,qsa]

php .htaccess redirect

python - ReferenceField and Wtforms -



python - ReferenceField and Wtforms -

i have connexion problem mongoengine , wtforms.

i tried attribute permission user class role class can't attribute role class foreign key user class

this code :

# on class file mongoengine import document, stringfield, referencefield class user(document): username = stringfield(unique=true) password = stringfield() role = refrencefield(role, default=role.objects.get(num=3)) class role(document): num = intfield() name = stringfield() # on form file wtforms import form, stringfield, selectfield class usereditform(form): username = stringfield(u'username', [validators.required()] role = selectfield(u'role', [validators.required()], choices = [(r.id, r.name) r in role.objects])

when saving, i've error message :

validationerror: validationerror (user:53a14fb0cdc4674abf452f2d) (a referencefield accepts dbref or documents: ['role'])

i tried remplace r.id r , r._object_key() no result

thanks,

i find reply : selectfield doesn't homecoming type element referencefield.

so new code :

# form file class usereditform(form): username = stringfield(u'username', [validators.required()]) role = selectfield(u'role', [validators.required()], choices=[(r.num, r.name) r in role.objects], coerce=int) # controller class class edituser(methodview): def get_context(self, id): usr = user.objects.get(id=id) form = usereditform(request.form, usr) homecoming {"usr": usr, "form": form} def post(self, id): context = self.get_context(id) form = context.get("form") if form.validate(): usr = context.get("usr") form.populate_obj(usr) usr.role = role.objects.get(num=form.role.data) usr.save() homecoming redirect("/user_edit/" + id) homecoming response("form error validation")

have nice day

python flask mongoengine flask-wtforms flask-mongoengine

sockets - How to attach GIOChannel for different context instead of default context? -



sockets - How to attach GIOChannel for different context instead of default context? -

i writing 1 simple server , client application uses socket communication. in client side have created giochannel listening socket events such read, write, exception..etc. client provides asynchronous apis.

i have written 1 sample application testing code creates g_main_loop , creates 1 giochannel keyboard events.

mainloop = g_main_loop_new(null, false); channel = g_io_channel_unix_new(0); g_test_io_watch_id = g_io_add_watch(channel, (giocondition)(g_io_in | g_io_err | g_io_hup | g_io_nval), test_thread, null); g_main_loop_run(mainloop);

it working fine if dont loop or block main thread in callback function test_thread. illustration when phone call asynchronous api of client set sleep in sample programme time , expecting asynchronous message server time main thread wakes up. not happening, client socket getting read event reading asynchronous message server after main thread called api returns.

from got know both keyboad events , socket events registered same default context , can not notified main event dispatcher same time.

i have create programme such way socket reading @ client side should not dependent on default context of g_main_loop sync , async both happen seperate threads.

i found apis through gnome docs adding giochannel default context. have add together giochannel created socket reading different context.

can suggest me how or there improve alternative available handling socket reading asynchronously using glib.

thank you.

sockets asynchronous

Populate PDF form with mysql data in php -



Populate PDF form with mysql data in php -

i have pdf next form fields:

cost clicks impressions keyword1 clicks1 cost1 keyword2 clicks2 cost2

and goes 10

i have next code trying figure out way query table , limit of 10 results , populate fields. can't figure out whats best way go doing this, because fdf has have variable associated form field need assigned dynamically. can please help me this. below code have:

<?php error_reporting(e_all); ini_set('display_errors', 1); $con=mysqli_connect("localhost","username","password","my_db"); // check connection if (mysqli_connect_errno()) { echo "failed connect mysql: " . mysqli_connect_error(); } $result = mysqli_query($con,"select * reports"); $fdf = '%fdf-1.2 1 0 obj<</fdf<< /fields[ <</t(clicks)/v('.$clicks.')>> <</t(impressions)/v('.$impressions.')>> <</t(cost)/v('.$cost.')>> <</t(keyword1)/v('.$keyword1.')>> <</t(clicks1)/v('.$clicks1.')>> <</t(cost1)/v('.$cost1.')>> <</t(keyword2)/v('.$keyword2.')>> <</t(clicks2)/v('.$clicks2.')>> <</t(cost2)/v('.$cost2.')>> ] >> >> endobj trailer <</root 1 0 r>> %%eof'; file_put_contents('fields.fdf', $fdf); $results = shell_exec("pdftk report.pdf fill_form fields.fdf output report_final.pdf flatten");

php mysql pdf pdftk fdf

rest - Sinatra view and restapi -



rest - Sinatra view and restapi -

i'm new here not newbie in ruby.

i've litte question sinatra. if want utilize rest api functionality generate info source (like mysql). how decide utilize rest response (only values in json or other) or view (html.erb) ?

routes.rb

get '/api/movies/:id' film ||= movie.get(params[:id]) || halt(404) format_response(movie, request.accept) end

response_format.rb

def format_response(data, accept) accept.each |type| homecoming data.to_xml if type.downcase.eql? 'text/xml' homecoming data.to_json if type.downcase.eql? 'application/json' homecoming data.to_yaml if type.downcase.eql? 'text/x-yaml' homecoming data.to_csv if type.downcase.eql? 'text/csv' homecoming data.to_json end end

something like: (decide in routes)

get '/api/movies/:id' film ||= movie.get(params[:id]) || halt(404) request.user_agent =~ /mozilla/ ? format_response(movie, request.accept) : erb :view_movie end

or like: (decide in helper)

def format_response(data, accept) accept.each |type| homecoming data.to_xml if type.downcase.eql? 'text/xml' homecoming data.to_json if type.downcase.eql? 'application/json' homecoming data.to_yaml if type.downcase.eql? 'text/x-yaml' homecoming data.to_csv if type.downcase.eql? 'text/csv' erb :view_movie if type.downcase.eql? 'text/html' end end

rest sinatra erb

c# - Obtain data from checked rows in iggrid with checkboxes -



c# - Obtain data from checked rows in iggrid with checkboxes -

i have grid stores info of selected row in array when clicked. method works fine, i'm trying alter can select multiple rows checkbox , able store date in array. basically, instead of adding 1 row @ time in array, want able add together multiple rows checked in it. don't know if guys follow me please code can find way that.

here is,

javascript :

class="lang-js prettyprint-override">$('#gridbindcontact').on('iggridselectionactiverowchanged', function (event, args) { $("#primarykey").val(args.row.element[0].cells[1].textcontent); $("#contacttobind_numcon").val(args.row.element[0].cells[1].textcontent); $("#contacttobind_fullname").val(args.row.element[0].cells[2].textcontent + ' ' + args.row.element[0].cells[3].textcontent); $("#contacttobind_titcon").val(args.row.element[0].cells[4].textcontent); $("#contacttobind_tel1con").val(args.row.element[0].cells[5].textcontent); $("#contacttobind_tel2con").val(args.row.element[0].cells[6].textcontent); $("#contacttobind_emailcon").val(args.row.element[0].cells[7].textcontent); $("#contacttobind_numemployees").val(args.row.element[0].cells[8].textcontent); $("#contacttobind_nameemployees").val(args.row.element[0].cells[9].textcontent); $("#contacttobind_added").val(true); $(".ui-button-text").trigger("click"); });

in view :

class="lang-cs prettyprint-override">@(html.infragistics.grid(of contact)(model.results).id("gridbindcontact"). autogeneratecolumns(false). width("100%"). height("400px"). responsedatakey("results"). columns(sub(column) column.for(function(e) e.numcon).template("${numcon}").headertext("num") column.for(function(e) e.pnmcon).template("${pnmcon}").headertext("pnm").width("10%") column.for(function(e) e.namemcon).template("${namecon}").headertext("name").width("15%") column.for(function(e) e.titcon).template("${titcon}").headertext("title").width("20%") column.for(function(e) e.tel1con).template("${tel1con}").headertext("tel1") column.for(function(e) e.tel2con).template("${tel2con}").headertext("tel2") column.for(function(e) e.emailcon).template("${emailcon}").headertext("email") column.for(function(e) e.numemployees).headertext("num emp") column.for(function(e) e.nameemployees).headertext("name emp") end sub). features(sub(features) features.sorting().type(optype.local) features.rowselectors.enablecheckboxes(true).rowselectorscolumnwidth("50px").enablerownumbering(false) features.selection().mode(selectionmode.row).multipleselection(true).addclientevent("activerowchanging", "activerowchanging") features.updating().editmode(grideditmode.none).enableaddrow(false).enabledeleterow(false) end sub).render()) <form action="#" id="ajaxform" method="post"> @html.hiddenfor(function(x) x.primarykey) @html.hiddenfor(function(x) x.contacttobind.numcon) @html.hiddenfor(function(x) x.contacttobind.fullname) @html.hiddenfor(function(x) x.contacttobind.titcon) @html.hiddenfor(function(x) x.contacttobind.tel1con) @html.hiddenfor(function(x) x.contacttobind.tel2con) @html.hiddenfor(function(x) x.contacttobind.emailcon) @html.hiddenfor(function(x) x.contacttobind.numemployees) @html.hiddenfor(function(x) x.contacttobind.nameemployees) </form>

i added feature have checkboxes in grid, got nil handle them yet !

///////////////////////////////////////////////////////////////////////////////////////////

little edit can clear things

let me seek elaborate little more want able exactly. want able add together info rows checked in row array batch. said, let's checked 3 rows. when press 'ok' button, should store info 3 rows in array.

if succeed, array should have 3 'elements'. example, array[0] contain info first row checked. allow me access each cells , store 'textcontent' them in 'contacttobind' i'm using store each cell info @ moment.

i hope clears little bit !

thanks alot help.

guillaume

you can utilize .iggrid( "allrows" ); rows in grid, save in variable named "myrows". write javascript code traverse through "myrows" got .iggrid( "allrows" ) , check value of each row's combo box. if current row has combo box "checked", set current row in array. @ end of loop have rows in array checked.

if dont know how traverse through "allrows" stored in "myrows" variable, utilize console.log(myrows) , check object construction in browser's console window. able see how checkbox columns, not sure please check using console.log:

for(var = 0 ; < myrows.length ; ++ ) { myrows[i].cells....(select checked combobox) if yes store myrows[i] in array; }

c# javascript visual-studio-2012 infragistics iggrid

asp.net - MSBUILD script building solution, but not deploying publishing profile -



asp.net - MSBUILD script building solution, but not deploying publishing profile -

i have created publishing profile web page, , can publish using web deploy interface in visual studio (right click project, deploy etc). builds project on local pc, , copies files across destination iis server.

but trying create msbuild command, should same, building solution, not copying across server.

my msbuild command looks this, , run solution source directory

msbuild "test.co.za.sln" p:deployonbuild=true /p:publishprofile="test.co.za" /p:username="domain\test" /p:password="test"

is there wrong build command? can see in screenshot, building successfully, no files beingness copied across. makes me wonder if publishing profile executed @ all. have tried various combinations of publishprofile paths, total paths, extensions, without, nil seems re-create files accross.

my publishing profile looks app_data\publishprofile\test.co.za.pubxml

<?xml version="1.0" encoding="utf-8"?> <project toolsversion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <propertygroup> <webpublishmethod>msdeploy</webpublishmethod> <lastusedbuildconfiguration>debug</lastusedbuildconfiguration> <siteurltolaunchafterpublish>http://test.co.za</siteurltolaunchafterpublish> <launchsiteafterpublish>true</launchsiteafterpublish> <msdeployserviceurl>test.co.za</msdeployserviceurl> <deployiisapppath>test.co.za</deployiisapppath> <skipextrafilesonserver>true</skipextrafilesonserver> <msdeploypublishmethod>wmsvc</msdeploypublishmethod> <username>domain\test</username> <_savepwd>true</_savepwd> </propertygroup> </project>

edit: existing classic asp website added solution, doesn't contain ".csproj" file, "website.publishproj", doesn't seem execute

it doesn't passing in visualstudioversion property. should include that. value either 11.0, 12.0, or 14.0 based on version of visual studio using. should pass in value configuration it's not required. i've blogged why of import @ http://sedodream.com/2012/08/19/visualstudioprojectcompatabilityandvisualstudioversion.aspx.

you can find docs asp.net command line publishing @ http://www.asp.net/mvc/tutorials/deployment/visual-studio-web-deployment/command-line-deployment

asp.net msbuild msdeploy

how to connect sql server 2008 from my android app -



how to connect sql server 2008 from my android app -

i'm developing android app connect sql server 2008, , source code dbconn.java

public class dbconn { private static connection conn = null ; private static string driver = "net.sourceforge.jtds.jdbc.driver"; private static string db_name = "testdb" ; private static string db_user = "sa" ; private static string db_password = "sa" ; public boolean consqlserver() { log.d("err","start connect sql server") ; seek { class.forname(driver).newinstance(); string connstring = "jdbc:jtds:sqlserver://192.168.1.100:1433/testdb; instance=sqlexpress; user=sa;password=sa"; conn = drivermanager.getconnection(connstring); log.d("success","connection successful "); homecoming true; } grab (sqlexception e) { log.d("err","error connection 1 = " + e.getmessage()); e.printstacktrace(); homecoming false ; } grab (exception ex ) { log.d("err","error connection 2 = " + ex.getmessage()); ex.printstacktrace(); homecoming false ; } } }

i phone call mainactivity.java

public class mainactivity extends actionbaractivity { .... .... dbconn dbconn = new dbconn(); dbconn.consqlserver() ; ... }

androidmanifest.xml

<manifest> ..... <uses-permission android:name="android.permission.internet" /> ..... </manifest>

but got error this

java.sql.sqlexception: network error ioexception: socket failed: eacces (permission denied) @ net.sourceforge.jtds.jdbc.jtdsconnection.<init>(jtdsconnection.java:436) @ net.sourceforge.jtds.jdbc.driver.connect(driver.java:184) @ java.sql.drivermanager.getconnection(drivermanager.java:179) @ java.sql.drivermanager.getconnection(drivermanager.java:213) @ com.noh.connectdb.app.core.dbconn.consqlserver(dbconn.java:35) @ com.noh.connectdb.app.mainactivity.oncreate(mainactivity.java:20) .... .... i run android device via wifi i check connection device can ping server firewall closed port 1433 opened

can 1 help me ?

android sql-server-2008 database-connection

.net - How to make Visual Studio 2013 Errors show in english -



.net - How to make Visual Studio 2013 Errors show in english -

i larn asp .net , if error occures have translate stackoverflow. instance:

exception thrown @ line 37, column 60451 in http://localhost:3176/d36ef192c476437f94f058c98480760b/browserlink 0x800a139e - błąd czasu wykonywania kodu javascript: syntaxerror

how switch language partially polish-english english. visual studio 2013 in english language besides that.

it not error string visual studio generated. came ierrorinfo, com interface document hresult code. 0x800a139e in case.

clearly browser convinced polish still mother-tongue. ought inquire @ superuser.com how tell otherwise. in likelihood does require running english language version of windows. ultimate supports downloadable language packs permit changing scheme language on fly. well, flyish, half gigabyte each , require logout + login create alter effective.

.net visual-studio localization visual-studio-2013

data fitting - Matlab fminsearch Hessians? -



data fitting - Matlab fminsearch Hessians? -

a warning im new , out of depth, apologies if novice or unclear.

im estimating parameters using fminsearch number of datasets , has been suggested should seek plot hessians fit each dataset. possible these using fminsearch?

i told should standard output option, far can tell not 1 of options fminsearch (although looks alternative fminunc)

this relevant bit of code im hoping modify:

[par,fval] = fminsearch(@(x) logistic(x,arg), [m me p pe c ce]);

any help @ much appreciated.

the answer, after searching, utilize fmincon. interested, code worked:

[par,fval,exitflag,output,lambda,grad,hessian] = fmincon(@(x) logistic(x,arg), [m me p pe c ce], [], [], [], [], [-inf -inf -inf -inf -inf], [inf inf inf inf inf], [], optimopt)

matlab data-fitting fminsearch hessian-matrix

c - K&R Exercise 3-2 garbage characters -



c - K&R Exercise 3-2 garbage characters -

i working through k&r 2nd edition , have run curious problem exercise 3-2. reason \n shows it's supposed , of 2 tabs in original string, 1 shows \ while other missing completely. varying amounts of garbage in string, current output string beingness "i \ (micro symbol mu) . \n". more curious there couple more spaces between \n , period in original. looked solution (https://code.google.com/p/k-and-r-exercises/source/browse/3-2.c) , similar did. furthermore, did 2 putchars in main, '\' , 't', , got \t display without issue. pretty stumped on causing error , utilize advice.

#include<stdio.h> #include<string.h> void switchfunction(char s[], char t[]); main(){ char originalstring[] = "i \t \t . \n \0"; char copiedstring[1000]; char a, b; switchfunction(originalstring, copiedstring); printf(originalstring); printf("\n"); printf(copiedstring); printf("\n"); = '\\'; b = 't'; putchar(a); putchar(b); } void switchfunction(char s[], char t[]){ int i; int j = 0; int originalstringlen; originalstringlen = strlen(s); printf("original %d characters.\n", originalstringlen); for(i = 0; < originalstringlen; ++i){ switch(s[i]){ case '\n': t[j] = '\\'; j++; t[j] = 'n'; j++; break; case '\t': t[j] = '\\'; j++; t[j] = 't'; j++; break; default: t[i] = s[i]; j++; } } t[j] = '\0'; }

p.s. did putchar every character in new string within function (as getting assigned) , got more garbage characters although \t's show without issue.

this problem line:

t[i] = s[i];

you need:

t[j] = s[i];

c garbage kernighan-and-ritchie

ios - PFQuery querying n number of PFUser and PFObjects -



ios - PFQuery querying n number of PFUser and PFObjects -

i'm using parse.com , have question regarding relational database. have user class (the default _user class) 1 of columns has "friends" array. friends array consists of pointers other users.

what want populate facebook-style timeline @ origin of app query current user array of friends , posts, queries user's array of friends , posts.

i have friends array. can query current user, , can query specific user.

my question is, how efficiently query posts on n number of users's posts? while can query specific users 1 1, gets slow if user has 100+ friends since need query each of friends posts.

thank you. ps: i'm using ios.

i assume have post class maintain users' posts. can posts of number of users using containedin

pfquery *query = [pfquery querywithclassname:@"post"]; [query wherekey:@"user" containedin:friends]; //friends array of users

or can go matcheskey. code anypic example:

pfquery *followingactivitiesquery = [pfquery querywithclassname:kpapactivityclasskey]; [followingactivitiesquery wherekey:kpapactivitytypekey equalto:kpapactivitytypefollow]; [followingactivitiesquery wherekey:kpapactivityfromuserkey equalto:[pfuser currentuser]]; followingactivitiesquery.limit = 1000; pfquery *photosfromfollowedusersquery = [pfquery querywithclassname:self.classname]; [photosfromfollowedusersquery wherekey:kpapphotouserkey matcheskey:kpapactivitytouserkey inquery:followingactivitiesquery]; [photosfromfollowedusersquery wherekeyexists:kpapphotopicturekey];

ios relational-database parse.com

java - Generics with Inheritance -



java - Generics with Inheritance -

the class trainingdata has attribute intent can of of subtypes of class intent. trying utilize java generics enforce generic type t can sub-class of intent. how can that?

public class trainingdata<t> extends info { private t intent; private string id; public trainingdata (usercommand usercommand, t intent) { super(usercommand); this.intent = intent; } public klass getklass() { homecoming intent.getklass(); // <-- works if t extends intent } public intent getintent() { homecoming intent; } public void setintent(intent intent) { this.intent = intent; } @override public string tostring() { homecoming "trainingdata [intent=" + intent + ", id: " + id + "]"; } }

the class trainingdata has attribute intent can of of subtypes of class intent.

try t extends intent means class extends intent accepted.

public class trainingdata<t extends intent> extends info {...}

read more java tutorial bounded type parameters

change getter & setter methods well.

class trainingdata<t extends intent> extends info { private t intent; public t getintent() { homecoming intent; } public void setintent(t intent) { this.intent = intent; } ... }

java generics

css - HTML White Color Font Shows Yellow -



css - HTML White Color Font Shows Yellow -

i'm trying edit html page's color fonts in table. i've been asked give reddish background , white font. problem is, when white, shows yellowish on page. don't know i'm doing wrong, i'm not terribly great @ this, have no 1 else.

here's table (only worrying first cell right now)

<table border="3"> <tr> <th><td bgcolor="#b22222;"><font color="#ffffff;" size="+1">queue</font></th> </tr>

the semicolon playing tricks on you. take out.

<font color="#ffffff" size="+1">queue</font>

now utilize css or something. css doesn’t think chuck norris colour.

<h2>queue</h2> class="lang-css prettyprint-override">h2 { background-color: #b22222; color: white; }

html css

play/pause button image in notification ,Android -



play/pause button image in notification ,Android -

i have implemented music player fires custom notification when stream sound playing

everything working , can play /pause sound using button in notification. problem have image button , can't alter image on click button indicate play / or pause

using remoteviews.setimageviewresource() in remotereciever nothing

the command done using broadcastreceiver

this code of firing notification player activity

public void setnotification(string songname){ string ns = context.notification_service; notificationmanager notificationmanager = (notificationmanager) getsystemservice(ns); @suppresswarnings("deprecation") notification notification = new notification(r.drawable.ic_launcher, null, system.currenttimemillis()); remoteviews notificationview = new remoteviews(getpackagename(), r.layout.notification_view); notificationview.setimageviewresource(r.id.button1, r.drawable.pause); notificationview.settextviewtext(r.id.textview1, songname); //the intent started when notification clicked (works) intent notificationintent = new intent(this, playeractivity.class); pendingintent pendingnotificationintent = pendingintent.getactivity(this, 0, notificationintent, pendingintent.flag_update_current); notification.contentview = notificationview; notification.contentintent = pendingnotificationintent; intent switchintent = new intent("com.example.test.action_play"); pendingintent pendingswitchintent = pendingintent.getbroadcast(this, 0, switchintent, pendingintent.flag_update_current); notificationview.setonclickpendingintent(r.id.play_pause, pendingswitchintent); notificationmanager.notify(1, notification); }

the notification xml

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <imageview android:layout_alignparentleft="true" android:layout_width="60dp" android:layout_height="60dp" android:src="@drawable/ic_launcher" android:id="@+id/imgappic" /> <textview android:layout_torightof="@id/imgappic" android:singleline="true" android:id="@+id/textview1" android:ellipsize="marquee" android:layout_marginleft="7dp" android:layout_margintop="10dp" android:marqueerepeatlimit ="marquee_forever" android:focusable="true" android:focusableintouchmode="true" android:scrollhorizontally="true" android:layout_width="170dp" android:layout_height="wrap_content"/> <imagebutton android:id="@+id/play_pause" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toleftof="@+id/play" /> </relativelayout>

this remoterecivier class

public class remotecontrolreceiver extends broadcastreceiver { @override public void onreceive(context context, intent intent) { remoteviews remoteviews = new remoteviews(context.getpackagename(), r.layout.notification_view); if(action.equalsignorecase("com.example.test.action_play")){ if(mediaplayer.isplaying()){ mediaplayer.pause(); remoteviews.setimageviewresource(r.id.button1, r.drawable.play); } else { mediaplayer.start(); remoteviews.setimageviewresource(r.id.button1, r.drawable.pause); } } } }

and manifest

<receiver android:name=".remotecontrolreceiver"> <intent-filter> <action android:name="com.music.app.action_play" /> </intent-filter> </receiver> <activity android:name="playeractivity" />

please , help solve , i've been stuck long time in advance

you have set notification.contentview new remoteview after changed can update notification view itself.

meaning, after receive action in broadcastreceiver, re-build notification desired button display ( pause or play )

hope helps

android notifications media-player android-remoteview

html - Railo 4.2 content type in return header becomes text/xml -



html - Railo 4.2 content type in return header becomes text/xml -

my problem here quite confusing me, though fear reply simple unable find

i using railo 4.2 @ moment. setting decently old webpage customer

in many cases have links like

/filename.cfc?method=dosomething

no matter returned, returns content-type : text/xml

i have added seems chosen xml before looking @ that.

<cffunction name="needhelp" access="remote" output="true" produces="text/html"> <html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body>help!</body></html> </cffunction>

the code above seems simple enough, gives error due not formed xml.

just create things strange:

<cffunction name="needhelp" access="remote" output="true" produces="text/html"> <cfset setlocale('no_no')> <html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body>help!</body></html> </cffunction>

this code works think should. returns text/html.

i cant understand why happens, have lead seek check? :)

html xml coldfusion railo

c# - Regex match with dictionary key -



c# - Regex match with dictionary key -

i'm expanding upon asked question.

before explain, here c# code:

static dictionary<string, string> phenom = new dictionary<string, string> { {"-", "light"}, {"\\+", "heavy"}, {"\bvc\b","in vicinity"}, // descriptor {"mi","shallow"}, {"pr","partial"}, {"bc","patches"}, {"dr","low drifting"}, {"bl","blowing"}, {"sh","showers"}, {"ts","thunderstorm"}, {"fz","freezing"}, // precipitation {"dz","drizzle"}, {"ra","rain"}, {"sn","snow"}, {"sg","snow grains"}, {"ic","ice crystals"}, {"pl","ice pellets"}, {"gr","hail"}, {"gs","small hail/snow pellets"}, {"up","uknown precipitation"}, // obscuration {"br","mist"}, {"fg","fog"}, {"fu","smoke"}, {"va","volcanic ash"}, {"du","widespread dust"}, {"sa","sand"}, {"hz","haze"}, {"py","spray"}, // other {"po","well-developed dust/sand whirls"}, {"sq","squalls"}, {"fc","funnel cloud tornado waterspout"}, {"ss","sandstorm"}, {"ds","duststorm"} }; public static string process(string metar) { metar = regex.replace(metar, "(?<=a[0-9]{4}).*", ""); stringbuilder _string = new stringbuilder(); var results = result in phenom regex.match(metar, result.key, regexoptions.singleline).success select result; foreach (var result in results) { if (result.key == "dz" || result.key == "ra" || result.key == "sn" || result.key == "sg" || result.key == "pl") { switch (result.key) { case "+": _string.append("heavy "); break; case "-": _string.append("light"); break; case "vc": _string.append("in vicinity "); break; default: break; } } _string.appendformat("{0} ", result.value); } homecoming _string.tostring(); }

basically, code parses weather phenomenons in airport metar weather report. take next metar example:

kama 230623z auto 05016kt 7sm +tsragr few070 bkn090 ovc110 16/14 a3001 rmk ao2 pk wnd 06026/0601 ltg dsnt e-sw rab04 tsb02e17 p0005 t01560144

notice +tsragr...this portion want focus on. code have works fine...but not close want. spits out this: "heavy thunderstorm rain hail".

the actual decoding differs slightly. referenced this manual (see 5th page).

the intensity indicators (+ , -) come before first precipitation. in above metar, ra. so, ideally should spit out "thunderstorm heavy rain hail", instead. however, not. there other times when phenomena not intense...sometimes may -ra, in case should homecoming "light rain".

also note, manual referenced says, intensity identifiers not coded ic, gr, gs or precipitation types, explains effort @ checking key value before appending intensity, failed.

if point me in right direction on how append intensity identifiers in right location, i'd much appreciate it.

tl;dr...basically, code logic decide set prefixes before specific items dictionary list.

given construction of code, recommend pre-parsing input string "move" intensity indicators after terms don't modify, words come out in order makes sense.

then, might consider adding few keys dictionary cover +/- versions of each type of precipitation can have intensity indicator, overall code simplified.

c# regex

shell - Puppet : How to get logs in to the same terminal in agent side -



shell - Puppet : How to get logs in to the same terminal in agent side -

i executing shell script in puppet agent side. if execute same shell script in local machine print several log messages terminal. when execute in puppet agent not print log agent terminal.

how can print logs of shell script when run using puppet?

i using next command execute shell script.

exec { "strating": user => 'root', environment => 'java_home=/home/malintha/jdk1.6.0', path => $command_path, command => "/pathtoshellscript/myscript.sh", logoutput => true, timeout => 3600, require => exec['another goal'], }

note: set logoutput => true

you can add together --debug flag puppet command.

puppet agent --test --debug

or alternatively can set loglevel metaparameter info or notice:

exec { 'starting': path => $command_path, command => '/path/to/script.sh', logoutput => true, loglevel => info }

see below output:

[~]$ puppet apply --verbose test.pp notice: compiled catalog dpsmqm009.local in environment production in 0.03 seconds info: applying configuration version '1403302144' info: /stage[main]/main/exec[starting]/returns: testing info: /stage[main]/main/exec[starting]/returns: testing 1 time again info: /stage[main]/main/exec[starting]/returns: testing more info: /stage[main]/main/exec[starting]/returns: executed notice: finished catalog run in 0.20 seconds reference

http://docs.puppetlabs.com/references/latest/metaparameter.html#loglevel

shell puppet puppetlabs-apache

javascript - JQuery percent loaded very slow in Firefox / Chrome - IE no issues -



javascript - JQuery percent loaded very slow in Firefox / Chrome - IE no issues -

i'm using http://widgets.better2web.com/loader/

all seems fine...

// initialise progress meter initmeter('progressmeter',150); function initmeter(id,size) { // initialise upload meter uploader = $('#'+id).percentageloader({width: size, height: size, controllable : false, progress : 0.5}); uploader.setprogress(0); uploader.setvalue('0'+sizeunit); }

when meter loads in ie, see gauge image , progress moving along percentage loaded , amount of kb/mb processed no problems.

however, when viewing in ff/chrome, see gauge image , progress moving, centre percentage , number of kb/mb uploaded takes few seconds show on big files, , little files, finishes uploading before gauge info displayed?

why happening?

thanks, 1dmf

i believe timing issue, calling ajax upload formdata after calling initmeter function within sendform function

so moved initmeter phone call $(on.submit) of form, calls sendform function starts ajax upload , callback progress, seems working fine.

javascript jquery progress

Forcing error in TypeScript compile with void return -



Forcing error in TypeScript compile with void return -

with next code:

function foo() : void { // } var f = foo(); // why no error here?

this not produce compiler warning/error though foo function has been declared not homecoming anything.

another case i'd prevent is:

if (foo()) { }

i'm building api used other developers, , typescript works encouraging type safety , helps grab mutual javascript errors otherwise caught in testing rather @ compile time. case though isn't apparently handled though in other languages c#. developers customers, , may not have much experience, want create platform robust possible, , grab many issues before code deployed.

is there reasonable way construction code prevent other code attempting utilize undefined result of function has no homecoming value? if foo doesn't homecoming anything, i'd rather code can phone call foo(); , not inadvertently expect valid homecoming value when doing assignment (or similar execution).

other programming languages grab type of code construction @ compile time (and display warning/error).

it because void valid typescript type declaration. e.g next valid

var f:void;

however not useful variable type.

from language spec (http://www.typescriptlang.org/content/typescript%20language%20specification.pdf):

note: might consider disallowing declaring variables of type void serve no useful purpose. however, because void permitted type argument generic type or function not feasible disallow void properties or parameters.

update: pointed out ryan : https://twitter.com/searyanc/status/479664200323579904 don't much additional typesafety if f:void disallowed. can't utilize f in meaningful way e.g. next compile errors.

var f:void; f.bar; // error function bar(f:{}){} bar(f); // error var baz:{a?:number} = f; // error // allowed cases f = undefined; f = null;

curious real world case though.

update based on question update: unfortunately don't see way compiler prevent this, since anything allowed in js/ts if statement. perhaps want boolean truthy/falsy restriction.

if (f()) { }

typescript