Friday, 15 April 2011

java - Midpoint Formula Overflow Error -



java - Midpoint Formula Overflow Error -

i'm learning algorithms/big o , curious this.

the utilize of

mid = (low+high)/2;

in order midpoint binary search algorithm discouraged because of possibility of overflow error. why cause overflow error occur, , how

mid = low + (high-low)/2;

prevent error?

thanks.

in first case calculate value (low+high) might huge fit int, if low , high both huge plenty (say if both equal 2^30+1 /or greater/). in sec case, don't calculate (low+high), little trick , go through look (high-low) , look much safer respect int overflow.

still, if don't have array size greater 2^30 (which quite huge array anyway), don't see how can run int overflow when using first expression. utilize first 1 in cases , not worry.

java algorithm binary-search

Accessing $_POST variables in PHP from JavaScript -



Accessing $_POST variables in PHP from JavaScript -

i've made android app sends 2 strings of latitude , longitude values on http post, taken php code , stored in variables. variables should then, in theory, taken in javascript code. however, while know php code getting strings since can write them different html file, whenever seek alert() value of javascript variable stored string, blank alert. here php , javascript code. help appreciated!

<?php $latitude = $_post["latitude"]; $longitude = $_post["longitude"]; $datetime = date('m/d/y h:i:s a'); file_put_contents("locationdata.html", $latitude, file_append); ?> <html> <title>find location</title> <style type="text/css"> html { height: 100% } body { height: 100%; margin: 0; padding: 0 } #map-canvas { height: 100% } #map-canvas { width: 100% } </style> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=(my api key removed privacy)"> </script> <script type="text/javascript"> var latitude = "<?php echo $latitude?>"; alert(latitude); function initialize() { var mapoptions = { center: new google.maps.latlng(29.6520, -82.3250), zoom:10 }; var map = new google.maps.map(document.getelementbyid("map-canvas"), mapoptions); } google.maps.event.adddomlistener(window, 'load', initialize); </script> <body> <head><strong>recent locations</strong></head> <div id="map-canvas"/> </body>

in above code not see reason why latitude isn't beingness alerted user. have made few changes think should implement prevent xss , error checking. should check if $_post variables exist before using them. reason why it's returning empty string.

<?php function latlong_xss_check($value) { $value = strip_tags($value); if(!is_numeric($value)) { homecoming 0; } homecoming $value; } if(isset($_post['latitude'],$_post['longitude'])) { $latitude = latlong_xss_check($_post['latitude']); $longitude = latlong_xss_check($_post['longitude']); }else{ $latitude = 0; $longitude = 0; } ?> <script> var latitude = "<?php echo $latitude; ?>"; var longitude = "<?php echo $longitude; ?>"; alert(latitude + ' : ' + longitude); </script>

javascript php post

database - Ghost .mdb File -



database - Ghost .mdb File -

so today try, of things, create mdb file vb.net (2012) , dao. please see following:

dim myengine new dao.dbengine sub createmdbfile() myengine.createdatabase("c:\windows\test.mdb", ";langid=0x0409;cp=1252;country=0", 64) end sub

it seems work great. code executes, , have other subroutines create , populate tables. can retrieve info recordsets, whole 9 yards. there's 1 weird issue:

when open explorer, can't find mdb file. it's not there. mean, programme can find it, open it, populate , query -- far windows explorer concerned, there's nil there.

is win 8 bug? why won't mdb file show in windows explorer?

thanks in advance,

jason

when application not "run administrator" (uac) attempts write scheme folder (including programme files subdirectories), windows no longer returns error. instead, file saved in %localappdata%\virtualstore. behavior started in windows vista.

http://blogs.windows.com/windows/archive/b/developers/archive/2009/08/04/user-account-control-data-redirection.aspx

tip: don't save user files scheme folders.

database vb.net windows-8.1

c# - xlApp.ActiveWorkbook returns null -



c# - xlApp.ActiveWorkbook returns null -

i have 2010 excel ribbon add-in. when press button writes lines of info excel app. in order write info need active worksheet. , in order active worksheet need activeworkbook. can xlapp fine

xlapp = (excel.application)system.runtime.interopservices.marshal.getactiveobject("excel.application");

and retrieves xlapp fine whenever seek active workbook returns null. no matter what. unless restart computer. works, first time. below whole block of code in context. i'm wondering how prepare xlapp.activeworkbook beingness null. can active worksheet. , write info active worksheet.

public void senddata() { excel.application xlapp = null; excel.workbook xlworkbook = null; excel.workbooks xlworkbooks = null; excel.worksheet xlworksheet = null; object misvalue = system.reflection.missing.value; seek { xlapp = new excel.application(); //xlworkbooks = xlapp.workbooks; //xlworkbook = xlworkbooks.add(properties.settings.default.filetosend); //xlworksheet = xlworkbook.sheets[1]; xlapp = (excel.application)system.runtime.interopservices.marshal.getactiveobject("excel.application"); xlworkbook = (excel.workbook)xlapp.activeworkbook; xlworksheet = (excel.worksheet)xlworkbook.activesheet; } grab (exception ex) { // handle error... } { if (xlworksheet != null) marshal.releasecomobject(xlworksheet); if (xlworkbook != null) marshal.releasecomobject(xlworkbook); if (xlworkbooks != null) marshal.releasecomobject(xlworkbooks); if (xlapp != null) marshal.releasecomobject(xlapp); }

thanks in advance!

you're getting hold of wrong excel instance phone call getactiveobject. utilize application reference passed com add-in's onconnection (or ribbon code bootstrapped).

if you're using excel-dna framework create managed excel add-in, hold of right application object phone call exceldnautil.application.

c# excel interop ribbon

vb.net - WPF Data gird row selection change event from selection change event -



vb.net - WPF Data gird row selection change event from selection change event -

i'm looking workaround issue i've noticed in project i'm working on. have datagrid bound list of class i've created. whenever user types in stock symbol in datagrid have roweditending event set pull in info populate other fields in datagrid.

this works fine, i've noticed event doesn't fire in instances. i'm going seek explain best can... upon info entry if come in info cell , click row on datagrid - focus doesn't shift new row shifts row containing cell entering info cell, if select row or input element row edit ending event doesn't appear fire , such code populate rest of row doesn't execute.

everything else fine, , it's pretty subtle issue, 1 path of input create happen, wondering if had run or found work-around?

i've been looking @ selection alter event, need able grab row selected. in row edit ending event use

dim newtrade trade = e.row.datacontext

to instance of class row represents , add together additional fields.

i'm not sure see way row , it's datacontext row shifted using selectionchangedeventargs.

any ideas workaround?

i sure tried best explain issue, still not clear. issue guess not generic info grid, seems specific code. please share xaml, .cs can dig deeper.

wpf vb.net datagrid

javascript - How to make a click event occur in BackboneJs -



javascript - How to make a click event occur in BackboneJs -

i'm staring larn backbonejs , im stuck 1 issue here. i'm trying post record list im unable perform click event on button post record. below view im using:

backboneview:

var newsubaccount = backbone.view.extend({ initialize: function(){ }, el: '#sub-account-list' events:{ 'click #save' : 'savelist' }, render: function(id){ debugger; value = new subaccountmodel(); var template = $("#sub-account-list").html(_.template(createtmpl, {data:value.attributes})); }, savelist: function(){ debugger; value = new subaccountmodel(); var values = $('form#create-sub-account').serializearray(); value.save(values, { success: function(value){ alert('hello'); } }); } });

html:

<form id="create-sub-account" role="form"> <legend>sub business relationship creation</legend> <label><em>account name</em></label> <input type = "text" name ="name" value=""></input><br/> <label><em>description</em></label> <input type = "text" name ="desc" value = ""></input><br/> <button type="submit" id="save">save</button> <button id="cancel">cancel</button> </form>

edit:

here router im using render 'newsubaccount':

routes: { 'new': 'newsubaccount', }, events:{ 'click .create-sub-account' : 'savesubaccount' }, newsubaccount: function(){ var newsubaccount = new newsubaccount(); newsubaccount.render(); },

when perform click event, dorectly takes me main page, without going debug mode ( set debugger @ value = new subaccountmodel();, , didnt go through. i'm wondering if way of writing click event worng or im missing something. please ideas, appreciated. thanks.let me know if needs more details.

the problem have clicking on #save button submitting form, reloading page. there couple of options can do:

1) create save button plain button rather submit button, doesn't seek submit form:

<button type="submit" id="save" type="button">save</button>

2) if intention utilize save submit form, should capture submit of form rather click of button , prevent form submitting server, consider following:

var newsubaccount = backbone.view.extend({ el: '#sub-account-list' events:{ 'submit form#create-sub-account' : 'savelist' //listen submit event on form. }, render: function(id){ value = new subaccountmodel(); var template = $("#sub-account-list").html(_.template(createtmpl, {data:value.attributes})); }, savelist: function(event){ event.preventdefault(); // prevent form submitting, handling manually value = new subaccountmodel(); var values = $('form#create-sub-account').serializearray(); value.save(values, { success: function(value){ alert('hello'); } }); } });

the other advantage listening form in way, other methods of submitting form (such pressing enter) collected , handled correctly well.

as side note:

you shouldn't have events in router. instead should create views handle user interaction.

router - deals interaction between browser state (url) , user sees (ui). main focus should converting url views on page (the ui).

view - deals interaction between user , data. main focus display info in ui , allow user interact it. example, submitting form.

model - deals interaction between browser , server (ajax requests). main focus should handle info saved/fetched server. view should utilize models encapsulate info , display in ui.

javascript backbone.js

scala - Testing Akka with Specs2 -



scala - Testing Akka with Specs2 -

i have next specs2 test:

package concurrent import akka.actor.{props, actorref2scala} import akka.testkit.testactorref import scala.concurrent.duration._ class messagecoordinatingactorspec extends actorbasespec { "messagecoordinatingactor" should { "receive result , update related token , status" in { val (repositoryactorprobe, messagecoordinatingactorref) = buildmockmessagecoordinatingactor val addresses = mocksession.gettestaddresseswithservicesat( "16 main street", list("service1", "service2")) val postcode = postcode("ne28 9qr", addresses) val matchedaddr = addresses.find(_.addrtoken=="16 main street") messagecoordinatingactorref ! result(lookupresult( lookupstatus.servicesavailable, postcode, matchedaddr, true), testrecord) //expect message persist virgin postcode record repositoryactorprobe.expectmsg(pairlongtoduration(3, seconds), persistpostcode(postcode)) 1 mustequal 1 } } } abstract class actorbasespec extends testkit(actorsystem("test")) implicitsender mustmatchers specificationlike mockito { //this class contains fixture mill methods //such buildmockmessagecoordinatingactor }

the content of test pretty unimportant question, have 2 problems. firstly notice had utilize

pairlongtoduration(3, seconds)

i want able utilize

3.seconds (from scala.concurrent.duration package)

but when do, next error:

[error] found : org.specs2.time.duration [error] required: scala.concurrent.duration.finiteduration

any thought how can around this?

also notice had stick

1 mustequal 1

at bottom. if take out get

[error] /users/.../messagecoordinatingactorspec.scala:18: not find implicit value evidence parameter of type org.specs2.execute.asresult[concurrent.repositoryactor.updateaddrtoken]

it seems specs2 not recognise probe.expectmsg success beingness test success, there way prepare in more satisfactory way?

cheers! nfv

you need mix in org.specs2.time.notimeconversions trait duration issue.

then can create implicit instance asresult[updateaddrtoken] typeclass:

implicit def tokenasresult = new asresult[updateaddrtoken] { def asresult(r: =>updateaddrtoken) = success }

scala akka specs2

ios - Get encrypted text as NSString instead of NSData -



ios - Get encrypted text as NSString instead of NSData -

how can encrypted info string instead of nsdata object in objectice -c? need send encrypted text >net method , decryption procedures handles in .net code. or can help me encrypt text in ios , decrypt in >net ?

adding comment - zaph using code:

stringencryption *crypto = [[stringencryption alloc] init]; nsdata *_secretdata = [searchkey datausingencoding:nsutf8stringencoding]; ccoptions padding = kccoptionpkcs7padding; nsdata *key = [_key datausingencoding:nsutf8stringencoding]; nsdata *encrypteddata = [crypto encrypt:_secretdata key:key padding:&padding];

i need send encrypteddata .net. dnt know how send nsdata .net method , tried convert encrypteddata nsstring, unfortunately gives me nil. tried base64encodedstringwithoptions,its giving error when decrypting.

you can convert nsdata base of operations 64 string. ios 7, nsdata has these 2 methods: (direct quotes apple doc)

base64encodeddatawithoptions : create base-64, utf-8 encoded nsdata receiver's contents using given options.

base64encodedstringwithoptions : create base-64 encoded nsstring receiver's contents using given options.

ios aes

Python Logging on the fly -



Python Logging on the fly -

what trying accomplish here beingness able check logs without closing server. have written server in python , able utilize logging in python. can see logs 1 time close server. there way can see logs when updated. open log file , can see logs of things have happened , server can contiue doing work.

thanks help.

python

jquery - How to find current elements root div class? -



jquery - How to find current elements root div class? -

when clicked on checkbox , trying find root div class of element

i trying different options ,but of them getting undefined .

$(document).on("click", ".checkboxclas", function(e) { var cls = $(this).find('div:first').attr('class') ; alert(cls) });

when clicked on activateuihtml checkbox, wanted display activateuihtmlparentdivclass

when clicked on ordersdiv checkbox , wanted display parentsordersdivclass

http://jsfiddle.net/e56ty/31/

could please tell me how .

try utilize .parents().last() find lastly parent element, think have confusion root element is.

$(document).on("click", ".checkboxclas", function(e) { var cls = $(this).parents('div').last().attr('class') ; alert(cls); }); demo

jquery

dart - Pub serve all files -



dart - Pub serve all files -

in terms of js/css/img type assets, there way serve have in "web" , "lib" regardless of whether or not used in html?

also, maybe set little bit in bold in documentation...it took me forever figure out pub serve included files used in html.

i tried --all flag, didn't seem work.

you may inquire why? because isn't awesome dart smart in includes use? yea if worked , simple that'd great...but problem while parses html , that's , good...other js files depend on assets. pub serve doesn't go deep. plus, ajax loading, etc. want assets. set them there reason. dislike how dart assumes things.

i suspect has transformers , perhaps have own...and i'm looking now, there i'm missing?

thanks!

dart dart-pub

c++ - using template assignment operator -



c++ - using template assignment operator -

having next code, why first assignment doesn't phone call template operator= in foo, sec does? going 1 here? there compiler-generated 1 first assignment if user defined template exists?

#include <iostream> using namespace std; struct uberfoo { }; struct foo : public uberfoo { template<typename t> void operator=(const t& v) { cout << "const t&" << endl; set(v); } template<typename t> void operator=(t& v) { cout << "t&" << endl; homecoming set(v); } virtual void set(const foo&) { cout << "foo::set(const foo&)" << endl; } virtual void set(const uberfoo&) { cout << "foo::set(const uberfoo&)" << endl; } }; struct bar : public foo { virtual void set(const foo&) { cout << "bar::set(const foo&)" << endl; } virtual void set(const uberfoo&) { cout << "bar::set(const uberfoo&)" << endl; } }; int main() { bar a, b; foo & pa = a; const foo& rb = b; const uberfoo & urb = b; cout << "first" << endl; pa = rb; cout << endl << "second" << endl; pa = urb; homecoming 0; }

the compiler still generating non-templated operator= first assignment binds to. in sec assignment, templated operator= improve candidate (because involves no cast), 1 picked.

you can see adding next in code:

foo& operator=(const foo&) = delete;

or forcing proper template call:

pa.operator=<foo>(b);

the standard says (emphasis mine):

12.8 copying , moving class objects, §12.8/17, page 271:

a user-declared re-create assignment operator x::operator= non-static non-template fellow member function of class x 1 parameter of type x, x&, const x&, volatile x& or const volatile x&

§12.8/18, same page:

if class definition not explicitly declare re-create assignment operator, 1 declared implicitly.

c++ templates

php - MYSQL insert data from one table to another? -



php - MYSQL insert data from one table to another? -

i have 2 tables , need add together value "user" table user table album user is.

table1 (user)

id_user auto_increase user password

table2 (album)

idalbum auto_increase title descripcion user text

insert `table2` select (null,"some title","some description",`user`) `table1` `id_user`="12345";`

this select username user 12345 table1 , insert table2.

php mysql sql insert

java - Whats the best way to forma list of objects from different tables using Hibernate and spring -



java - Whats the best way to forma list of objects from different tables using Hibernate and spring -

i trying create list of objects contains different types of logs db. build list such order made (a date created field that's in each of tables).

so way getting each list (4 different kinds of logs) , cycle through them , set them in new list comparing them , getting recent 1 each time? seems take long time if list long may or may not be.

is there improve way hibernate set tables , have work me? tables don't share keys or normal join?

any suggestions helpful.

contactlog has columns (id, memberid, phonenumber, email, address, datechanged)

salarylog has columns (id, memberid, salary, datechanged)

relationslog has columns (id, memberid, relationid, datechanged)

personalinfolog has columns (id, memberid, height, weight, eyecolor, haircolor, datechanged)

the purpose of these logs indicate anytime changes info , im trying provide user audit page show changes these different objects.

i suggest using union, if i'm not mistaken, hql not back upwards union, you'll have utilize native query , result transformer. here's sample:

public class log { private long id; private long memberid; private string logtype; private date datechanged; // getters & setters here } public class logservice { @persistencecontext private entitymanager em; public list<log> getlogs(){ final session sess = em.unwrap(session.class); final sqlquery query = session.createsqlquery( "select id,memberid,'contact' logtype, datechanged contactlog"+ "union select id,memberid,'salary' logtype,datechanged salarylog"+ "union select id,memberid,'relations' logtype,datechanged relationslog"+ "union select id,memberid,'personal info' logtype,datechanged personalinfolog "+ "order datechanged desc"; ); query.setresulttransformer(transformers.aliastobean(log.class)); homecoming query.list(); } }

notice mutual columns selected (because must select same number of columns each table when using union).

if want view total details of log, utilize id load specific log , log type know table have total information.

or

you modify query concat changed info 1 column tables (which means adding new field in log.class).

public class log { private long id; private long memberid; private string logtype; private date datechanged; private string changedinfo; // getters & setters here } "select id,memberid,'contact' logtype, datechanged, phonenumber||','||email||','||address changedinfo contactlog"+ "union select id,memberid,'salary' logtype,datechanged,salary changedinfo salarylog"+ "union select id,memberid,'relations' logtype,datechanged,relationid changedinfo relationslog"+ "union select id,memberid,'personal info' logtype,datechanged, height||','|| weight||','|| eyecolor||','|| haircolor changedinfo personalinfolog "+ "order datechanged desc

java spring hibernate spring-mvc

java - how to import-back a deleted project from same eclipse workspace -



java - how to import-back a deleted project from same eclipse workspace -

it looks basic question don't have solution,

long back, soft deleted(physically project in workspace directory) eclipse workspace. trying import project now. saying project in workspace.

so doing re-create project workspace other location and, deleting project workspace. , importing project workspace back. way, working fine.

but have improve thought this....

if deleted project disk best bet restore recycle bin. otherwise might need data-recovery tool.

if project deleted , you're still getting "already in workspace" message, check projects folder. might have similarly-named project deleted eclipse not workspace folder.

java eclipse

c# - InvalidOperationException, the calling thread should be STA because -



c# - InvalidOperationException, the calling thread should be STA because -

i developping project in order manipulate lot of objects several modalities (mouse, leapmotion, touch ...). made using mvvm pattern soi have several views , viewmodels components use. create easier develop chose have canvas component in manipulate grids. each grid can contain type of object (shape, text, image, documents...).

to able have modalities linked method, decided build 1 listener per modality (1 mouse, 1 leapmotion...) , create them observe basic gestures (as click, doubleclick ...). gestures chose observe associate method via dictionary. anyway linking working expected executes right method. t o give illustration have action calling in mouse listener:

if (_leftclickcounter == 1 && _capturedleft == false) { if (_dic.containskey(key.onclick)) { action<object> action = _dic[key.onclick]; action.invoke(null); } }

where:

_dic dictionary key enumeration of gestures (as onclick, ondoubleclick ...) action method execute

in illustration method executed is:

public void add(object sender) { objectmodel objectmodel = new objectmodel(); objectview objectview = new objectview(objectmodel); this.objectviews.add(objectview); }

where sender used test purpose. remains unused in method. execution stops when tries instanciate objectview saying:

invalidoperationexception calling thread must sta, because many ui components require

my objectview.xaml.cs class is:

public partial class objectview : usercontrol { public objectview(objectmodel obj) { initializecomponent(); eventlinker linker = new eventlinker(this.visualbox); objectviewmodel objectvm = new objectviewmodel(obj, linker); this.datacontext = objectvm; } }

and objectview.xaml defining usercontrol utilize basic:

<usercontrol x:class="ausytouchmultimodal_v1.view.objectview" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:ignorable="d" d:designheight="300" d:designwidth="300"> <grid x:name="visualbox" background="blue"/> </usercontrol>

i dont have compilation errors, invalidoperationexception. can explain issue me?

thanks!

try calling actions in ui thread, this

if (_leftclickcounter == 1 && _capturedleft == false) { if (_dic.containskey(key.onclick)) { action<object> action = _dic[key.onclick]; // action.invoke(null); system.windows.application.current.dispatcher.begininvoke( phone call action ) } }

c# wpf mvvm invalidoperationexception

indexing - Sitecore indexes multiple CD servers not consistent -



indexing - Sitecore indexes multiple CD servers not consistent -

i experiencing inconsistencies indexes on cd servers. have 4 cd servers, lets phone call them:

cd1 cd2 cd3 cd4

i have 2 databases servers, lets phone call them:

db1 db2

the configuration follows:

sitecore 7.2 cd1 , cd2 point db1 cd3 , cd4 point db2

i using eventqueue handle updates of cd servers. table getting populated , appears working, not consistently. if delete of indexes on of cd servers rebuild indexes , publish ca server see of index folders indexes on cd servers created. problem is, actual indexes empty on of cd servers , seems random.

any ideas on why indexes not beingness built same on cd servers?

indexing sitecore sitecore7 sitecore7.2

Connection issue in ASP.NET MVC + NHibernate+Oracle application after a couple of minutes -



Connection issue in ASP.NET MVC + NHibernate+Oracle application after a couple of minutes -

first of all, have mvc web application uses nhibernate (version 3) , oracle 11g database.

the application working, when publish in production server curious scenario happens:

the user access application , perform task, example, select link menu. the user waits couple of minutes (2-3 minutes). the user perform task, example, reload same page or select link menu. the application fails ora-12571: tns:packet author failure exception. the user refresh error page, application works.

the first thing tried isolate problem, published application server same configuration:

same binaries, of course. same oracle x64 client version, minor version. same windows server 2008 version iis 7.5. same iis configuration (we compared windows/system32/inetsrv/config files using winmerge). accessing same production database.

and our surprise couldn't reproduce problem.

please, have clue of going on?

the problem related connection pool of server's oracle client. seems delivering invalid connections web application, while in other servers not happens.

the solution not interesting, putting validate connection = true within connection string resolved issue. aware of performance penalty of this, out of options.

ps: using flag, each connection validated connection pool service before delivering client application. not nice, since database round-trip happen every connection request.

asp.net nhibernate oracle11g

java - How to Easily Find Non-Overridden Methods In a Class -



java - How to Easily Find Non-Overridden Methods In a Class -

for example, looking @ javadoc java.util.arraylist. want , conveniently know methods, if any, implements not specified interface.

how can find methods inspecting javadoc?

java javadoc

ruby on rails - How can i remove blank nested form field? -



ruby on rails - How can i remove blank nested form field? -

how can reject blank nested field in nested form in rails using code:

class award < activerecord::base attr_accessible :category, :country_iso,:title, :year,:status ,:nomination_awards_attributes,:sponsor_awards_attributes,:city has_many :nomination_awards, dependent: :destroy has_many :sponsor_awards, dependent: :destroy accepts_nested_attributes_for :nomination_awards, :allow_destroy => true accepts_nested_attributes_for :sponsor_awards, :allow_destroy => true#,:reject_if => lambda { |a| a[:sponsor_id].blank? } validates :title,:category,:country_iso,:year,:city, :presence => true end

reject blank field using code :reject_if => lambda { |a| a[:sponsor_id].blank? }

and check in in edit info nowadays or not, if info nowadays or build no need build in edit page if not nowadays or build have build on edit page ....

ruby-on-rails

c# - WCF service authentication fails -



c# - WCF service authentication fails -

i trying consume wcf service in console app. app.config file looks this

<configuration> <startup> <supportedruntime version="v4.0" sku=".netframework,version=v4.5" /> </startup> <system.servicemodel> <bindings> <wshttpbinding> <binding name="wshttpbinding_inventitemgroupservice" /> </wshttpbinding> </bindings> <client> <endpoint address="http://mydomain.com/microsoftdynamicsaxaif50/inventitemgroupservice.svc" binding="wshttpbinding" bindingconfiguration="wshttpbinding_inventitemgroupservice" contract="servicereference1.inventitemgroupservice" name="wshttpbinding_inventitemgroupservice"> <identity> <userprincipalname value="asd@as" /> </identity> </endpoint> </client> </system.servicemodel>

console app code create authentication part.

protected programclass(aifsos.inventitemgroupserviceclient inventitemgroupserviceclient) // constructor { minventitemgroupserviceclient = inventitemgroupserviceclient; // resharper disable 1 time possiblenullreferenceexception minventitemgroupserviceclient.clientcredentials.windows.clientcredential.username = "un"; minventitemgroupserviceclient.clientcredentials.windows.clientcredential.password = "pw"; minventitemgroupserviceclient.clientcredentials.windows.clientcredential.domain = "domain"; }

all seems okay me, throws error

the caller not authenticated service.

can 1 point out missing?

1 go client project properties.

a. go services tab

enable settings , utilize authentication mode windows

2 alter app.config file within client project 2 sample line

<security mode="none"> <transport clientcredentialtype="windows" proxycredentialtype="none" realm="" /> <message clientcredentialtype="windows" negotiateservicecredential="false" algorithmsuite="default" establishsecuritycontext="false" /> </security>

3 alter app.config file within service project

<security mode="none"> <message clientcredentialtype="windows" negotiateservicecredential="false" algorithmsuite="default" establishsecuritycontext="false" /> </security>

4 in client code when creating service instance , calling service utilize line provide login info in service pc.

service1client client = new service1client(); client.clientcredentials.windows.clientcredential.username = "etlit-1"; client.clientcredentials.windows.clientcredential.password = "etl"; client.clientcredentials.windows.allowntlm = false; client.clientcredentials.windows.clientcredential.domain = "etlit-1-pc"; console.writeline(client.addnumber(23, 2));

c# asp.net web-services wcf

Javascript, and radio buttons -



Javascript, and radio buttons -

ok here deal. have survey putting on 60 questions. want create them mandatory. need know if grouping has value, don't care is.

here have, giving me first value.

<function checkfield(myfieldname, mytext){ var x=document.getelementbyid(myfieldname).value; window.alert(myfieldname + "1: " +x);

. . .. . .

ok returns first value of 5. not matter select. need know if selected if not want mark question different color user knows go , reply question.

you can seek html5 required:

<label><input type="radio" name="option" required /> alternative 1</label> <label><input type="radio" name="option" /> alternative 2</label>

you can utilize on 1 radio (per each name), or on of them (see html5: how utilize "required" attribute in input field type="radio").

radio-button

asp.net mvc - MVC4 how to save changes of only a select field without affecting others -



asp.net mvc - MVC4 how to save changes of only a select field without affecting others -

i have edit page users can update 2 fields city , state, whole model has 11 different fields again; allow them edit 2 plus 1 other uniqueid can't edit that. issue upon editing , saving new info other fields become null in database particular row, can causing this? code

[authorize] public actionresult edit() { //get user uniqueid var ss = convert.toint32(user.identity.name); // uniqueid match in database , select 3 fields profileid,city,state string connectionstring = configurationmanager.connectionstrings ["looglercontext"].connectionstring; using (system.data.sqlclient.sqlconnection sqlconnection = new system.data.sqlclient.sqlconnection(connectionstring)) { sqlconnection.open(); var getinfo = sqlconnection.query<profile>("select profileid,city,state profiles profileid=@myprofile", new { myprofile = ss }).firstordefault(); homecoming view(getinfo); } }

my view looks this

@model hackerway.models.profile using (html.beginform("edit", "profile", formmethod.post { @html.hiddenfor(model => model.profileid) @html.editorfor(model => model.city) @html.editorfor(model => model.state) <div style="margin-left: 200px"> <p class="name"> <input type="submit" name="myedit" value="update" /> </p> </div> }

after user clicks update button go simple httppost

[httppost] public actionresult edit(profile profiler) { // utilize profiler fields view , update them if (modelstate.isvalid) { db.entry(profiler).state = entitystate.modified; db.savechanges(); viewbag.success = "your changes have been saved"; homecoming view(profiler); } }

as stated before works if field gets updated changes saved other 11 fields i'm nut putting in form homecoming 'null'. in sql code grabbing fields need hence reason didn't utilize * help great

you're understanding of how info moves , forth between database isn't quite right. selecting fields need database absolutely correct; there's nil wrong that.

where code needs alter in post method. method takes in profile typed parameter. when info html form submitted server, inputs form passed server (i.e. profileid, city , state). other properties on profiler object null because how else asp.net supposed know are? user passed on 3 values.

in entity framework world way solve following:

public actionresult edit(profile profiler) { if (modelstate.isvalid) { //go fetch existing profile database var currentprofile = db.profiles.firstordefault(p => p.profileid == profiler.profileid); //update database record values model currentprofile.city = profiler.city; currentprofile.state = profiler.state; //commit database! db.savechanges(); viewbag.success = "your changes have been saved"; homecoming view(profiler); } }

to give finish answer, there is way solve issue. however, highly recommend don't , i'll explain why shortly.

the other way solve issue add together additional hidden inputs on form other fields in table. doing so, when user submits form asp.net's model binding process create sure other properties on profiler object have data. when commit object database, @ point have need.

why bad idea? let's load page , want seek changing info i'm not supposed to. modify values of hidden inputs, submit form, , you're application commit info database! bad news bears. using hidden inputs putting trust in user. in cases may acceptable risk (e.g. little web app co-worker), in other cases high risk or fraudulent.

it adds unnecessary overhead in terms of bytes traveling on wire, that's minor detail in comparing latter.

asp.net-mvc asp.net-mvc-4

python - How are are NumPy's in-place operators implemented to explain the significant performance gain -



python - How are are NumPy's in-place operators implemented to explain the significant performance gain -

i know in python, in-place operators utilize __iadd__ method in-place operators. immutable types, __iadd__ workaround using __add__, e.g., tmp = + b; = tmp, mutable types (like lists) modified in-place, causes slight speed boost.

however, if have numpy array modify contained immutable types, e.g., integers or floats, there more important speed boost. how work? did illustration benchmarks below:

import numpy np def inplace(a, b): += b homecoming def assignment(a, b): = + b homecoming int1 = 1 int2 = 1 list1 = [1] list2 = [1] npary1 = np.ones((1000,1000)) npary2 = np.ones((1000,1000)) print('python integers') %timeit inplace(int1, 1) %timeit assignment(int2, 1) print('\npython lists') %timeit inplace(list1, [1]) %timeit assignment(list2, [1]) print('\nnumpy arrays') %timeit inplace(npary1, 1) %timeit assignment(npary2, 1)

what expect similar difference python integers when used in-place operators on numpy arrays, results different:

python integers 1000000 loops, best of 3: 265 ns per loop 1000000 loops, best of 3: 249 ns per loop python lists 1000000 loops, best of 3: 449 ns per loop 1000000 loops, best of 3: 638 ns per loop numpy arrays 100 loops, best of 3: 3.76 ms per loop 100 loops, best of 3: 6.6 ms per loop

each phone call assignment(npary2, 1) requires creating new 1 1000000 element array. consider how much time takes allocate (1000, 1000)-shaped array of ones:

in [21]: %timeit np.ones((1000, 1000)) 100 loops, best of 3: 3.84 ms per loop

this allocation of new temporary array requires on machine 3.84 ms, , on right order of magnitude explain entire difference between inplace(npary1, 1) , assignment(nparay2, 1):

in [12]: %timeit inplace(npary1, 1) 1000 loops, best of 3: 1.8 ms per loop in [13]: %timeit assignment(npary2, 1) 100 loops, best of 3: 4.04 ms per loop

so, given allocation relatively slow process, makes sense in-place add-on faster assignment new array.

numpy operations on numpy arrays may fast, creation of numpy arrays relatively slow. consider, example, how much more time takes create numpy array python list:

in [14]: %timeit list() 10000000 loops, best of 3: 106 ns per loop in [15]: %timeit np.array([]) 1000000 loops, best of 3: 563 ns per loop

this 1 reason why improve utilize 1 big numpy array (allocated once) rather thousands of little numpy arrays.

python arrays numpy

jQuery UI dialog box - uncaught exception -



jQuery UI dialog box - uncaught exception -

i have next jquery methods in page

<script type="text/javascript"> jquery.noconflict(); jquery.validator.setdefaults({ submithandler: function () { var usin = jquery('#usin').val(); var user = jquery('#user').val(); var ph = jquery('#ph').val(); var conductivity = jquery('#conductivity').val(); var hardness = jquery('#hardness').val(); var tds = jquery('#tds').val(); var turbidity = jquery('#turbidity').val(); var alkalinity = jquery('#alkalinity').val(); var chloride = jquery('#chloride').val(); jquery.post("scripts/water_qual_add.php", { "usin": usin, "user": user, "ph": ph, "conductivity": conductivity, "hardness": hardness, "tds": tds, "turbidity": turbidity, "alkalinity": alkalinity, "chloride": chloride }, function (data) { jquery('#dialog').dialog('open'); homecoming false; jquery('#eff_entry').each(function () { this.reset(); }); //jquery('#usin').focus(); }); } }); jquery(document).ready(function () { jquery("#dialog-message").dialog({ autoopen: false, modal: true, buttons: { ok: function () { jquery(this).dialog("close"); jquery('#usin').focus(); } } }); jquery("#datepicker").datepicker({ changemonth: true, changeyear: true, dateformat: "dd-mm-yy", altformat: "yy-mm-dd", altfield: "#stddate" }); jquery('#usin').focus(); jquery("#eff_entry").validate(); jquery("#usin").change(function () { var usin = jquery('[name="usin"]').val(); jquery.post("get_sample_details.php", { "usin": usin }, function (data) { if (data.msg) { // message_box.show_message(data.msg,'please come in valid no.'); alert(data.msg); jquery('#usin').focus(); } else { jquery('#submit_btn').show(); jquery('#comment').hide(); jquery('#doc').val(data.date); jquery('#desc').val(data.description); jquery('#loc').val(data.location); } }); }); }); </script>

and in body of page

<div id="content"> <div id="welcome">welcome&nbsp;&nbsp; <?php echo $_session[ 'empname']; ?> </div> <div id="dialog" class="dialog" title="water quality info entry"> <hr class="noscreen" /> <form id="eff_entry" name="eff_entry" action=""> <fieldset> <div id="rawdata"> <legend>water quality parameters</legend> <label for="usin">usin</label> <input name="usin" id="usin" type="text" class="usin" required/> <br /> <br/> <label for="ph">ph</label> <input name="ph" id="ph" value='0.0' required /> <label for="conductivity">conductivity</label> <input name="conductivity" id="conductivity" value='0.0' required /> <br /> <label for="tds">tds</label> <input name="tds" id="tds" value='0.0' required/> <br/> <label for="turbidity">turbidity</label> <input name="turbidity" id="turbidity" value='0.0' required /> <br/> <label for="chloride">chloride</label> <input name="chloride" id="chloride" value='0.0' required /> <br/> <label for="alkalinity">alkalinity</label> <input name="alkalinity" id="alkalinity" value='0.0' required /> <br /> <label for="hardness">hardness</label> <input name="hardness" id="hardness" value='0.0' required/> <label for="user">data entered by</label> <input id="user" name="user" style="color:#ff0000; background-color:#ffff33; font-weight:bold" onfocus="this.blur();" onselectstart="event.returnvalue=false;" value="<?php echo $_session['empno']; ?>" /> <br/> <br/> <div align="center"> <input id="submit_btn" type="submit" name="submit" value="submit" /> </div> </div> <div id="calculated"> <label for="loc">location</label> <input readonly="readonly" name="loc" id="loc" /> <br/> <label for="desc">type</label> <br/> <input readonly="readonly" name="desc" id="desc" /> <br/> <label for="doc">date of collection</label> <br/> <input readonly="readonly" name="doc" id="doc" /> <br/> </div> </fieldset> </form> <div id="type2"></div> </div> </div> <!--end content --> <!--end navbar --> <div id="siteinfo"> <?php include( 'footer.php');?> </div> <br /> </div>

but after clicking submit button, dialog box not opening. error console gives message "uncaught exception: cannot phone call methods on dialog prior initialization; attempted phone call method 'open'".

also unable focus cursor in usin input box. before trying simple alert() method in jquery post instead of modal dialog. alert working, focus not working @ time also. hence thought using modal help.

either way, (using jqueryui modal or alert) want cursor in usin input box after submitting form. rest of parts working including info update

if finish html within body, don't have element of id dialog-message , perchance initialised dialog on wrong selector , hence error when seek open dialog.

as per code:

jquery("#dialog-message").dialog({ autoopen: false, modal: true, buttons: { ok: function () { jquery(this).dialog("close"); jquery('#usin').focus(); } } });

you should replace selector:

jquery("#dialog").dialog({ autoopen: false, modal: true, buttons: { ok: function () { jquery(this).dialog("close"); jquery('#usin').focus(); } } });

doing not throw error when open dialog using:

jquery('#dialog').dialog('open');

here working demo: http://jsfiddle.net/lotusgodkk/gcu2d/193/

modifications:

i changed selector in jquery('#dialog-message').dialog('open');

added temporary dialog div seemed missing:

<div id="dialog-message">hello</div>

and worked fine.

jquery jquery-ui uncaught-exception

svn - How to unversion a Visual Studio Solution committed with AnkhSVN -



svn - How to unversion a Visual Studio Solution committed with AnkhSVN -

i using vs2012, asp.net 4.5

i have tried initial commit failed. files seem committed ie have bluish ticks. start over, need unversion current solution (several projects), , start again. want solution had before started seek , commit svn.

i have hunted solution this, still confused.

many thanks.

edit

i have deleted solution trunk in repository using repo browser.

copy folder location. delete .svn folder @ root of folder structure, if exists. try adding , committing folder.

if doesn't work need find out why not. why didn't work first time?

svn visual-studio-2012 ankhsvn

c# - mail attachment contains corrupt file -



c# - mail attachment contains corrupt file -

while sending email using c#, getting issue.

code

//profileuploadcontrol file upload command attachment fileattach = new attachment(profileuploadcontrol.postedfile.inputstream, savedfilename,profileuploadcontrol.postedfile.contenttype);

i using fileattach object parameter send email function , sending email file corrupted , no content in file. something, missing here. help appreciated.

please note code working fine if saved file in server , access path in file attach. sample :

profileuploadcontrol.saveas(server.mappath("~/en/companyprofiles/") + savedfilename); attachment fileattach = new attachment(server.mappath("~/en/companyprofiles/") + savedfilename);

but don't want save file.

c# .net

Deleting rows in Excel based on criteria via Access VBA -



Deleting rows in Excel based on criteria via Access VBA -

i working on module format excel spreadsheet import access. spreadsheet comes source 7 rows of header data, info need, , 4 rows of jibberish below data. far have gotten through deleting header info:

sub excelformat() dim excelapp object dim excelwb object dim excelws object set excelapp = createobject("excel.application") set excelwb = excelapp.workbooks.open("z:\data\test.xlsx") excelapp.screenupdating = true excelapp.visible = true set excelws = excelwb.worksheets("testdata") excelws.rows("1:7").delete

i having problem selecting first blank cell in , deleting , 4 rows beneath it. in advance.

first delete lastly 4 rows , after header;

with activesheet lastrow = .cells(.rows.count, "a").end(xlup).row .rows(lastrow - 4 & ":" & lastrow).delete .rows("1:7").delete end

excel vba excel-vba access-vba

android - process_begin: CreateProcess(NULL, cp file dir, ...) failed error while building application on eclipse and using cygwin -



android - process_begin: CreateProcess(NULL, cp file dir, ...) failed error while building application on eclipse and using cygwin -

i trying re-create header files source file dir include dir android.mk. building application in eclipse running on top of windows using cygwin generate linux env. getting error

process_begin: createprocess(null, cp jni/core/source/serialize.h jni/core/include, ...) failed.

android.mk file looks like:

local_src_files := ... file_path := $(my_jni_dir)/core/include/ file := $(my_jni_dir)/core/source/serialize.h $(shell cp $(file) $(file_path)) include $(build_static_library)

can tell me doing wrong? in advance.

android eclipse

ruby on rails - Locations in range -



ruby on rails - Locations in range -

i have location model each location has lat , lon coordinate in degrees, trying have location instance homecoming locations within range of specified distance based on http://www.mullie.eu/geographic-searches/:

def in_range(distance) earth_radius = 3958.75587 maxlat = self.lat + to_deg(distance / earth_radius) minlat = self.lat - to_deg(distance / earth_radius) maxlon = self.lon + to_deg(distance / earth_radius / math::cos(to_rad(self.lat))) minlon = self.lon - to_deg(distance / earth_radius / math::cos(to_rad(self.lat))) location.where("lat > ? , lat < ? , lon > ? , lon < ?",minlat,maxlat,minlon,maxlon) end

when create location , request range:

l1 = location.find_by_post_code("sw11")

this returns lat of 51.4663 , lon of -0.165543 maxlat,minlat,maxlon,minlon values far little when request:

l1.in_range(10) maxlat = 51.466344087822264 minlat = 51.46625591217773 maxlon = -0.1654722301720378 minlon = -0.1656137698279622

so think calculation these values wrong having problem finding more resources on this, know right way obtain max , min coordinate values?

edit - subsequently answered, total working code below:

class location < activerecord::base earth_radius = 3958.75587 def in_range(distance) maxlat = self.lat + rad2deg(distance / earth_radius) minlat = self.lat - rad2deg(distance / earth_radius) maxlon = self.lon + rad2deg(distance / earth_radius / math.cos(deg2rad(self.lat))) minlon = self.lon - rad2deg(distance / earth_radius / math.cos(deg2rad(self.lat))) locations = location.where("lat > ? , lat < ? , lon > ? , lon < ?",minlat,maxlat,minlon,maxlon).to_a locations.each |location| if self.distance_to(location) > distance locations.delete(location) end end locations end def distance_to(location) lat_source_rad = deg2rad(self.lat) lat_destination_rad = deg2rad(location.lat) lat_delta = deg2rad(location.lat - self.lat) lon_delta = deg2rad(location.lon - self.lon) = math::sin(lat_delta/2.0) * math::sin(lat_delta/2.0) + math::cos(lat_source_rad) * math::cos(lat_destination_rad) * math::sin(lon_delta/2.0) * math::sin(lon_delta/2.0) b = 2 * math::atan2(math::sqrt(a), math::sqrt(1.0-a)) c = earth_radius * b end private def rad2deg(rad) rad / math::pi * 180.0 end def deg2rad(deg) deg / 180.0 * math::pi end end

i think problem lies on code didn't post, specifically, to_deg , to_rad method. maybe have wrote integer partition instead of float partition somewhere in 2 methods? note 3/2==1 3/2.0==1.5 in ruby.

class location radius = 3958.75587 attr_accessor :lat, :lng def initialize(lat, lng) @lat = lat @lng = lng end def ranges(distance) maxlat = @lat + rad2deg(distance / radius) minlat = @lat - rad2deg(distance / radius) maxlng = @lng + rad2deg(distance / radius / math.cos(deg2rad(@lat))) minlng = @lng - rad2deg(distance / radius / math.cos(deg2rad(@lat))) [[minlat, maxlat], [minlng, maxlng]] end private def rad2deg(rad) rad / math::pi * 180.0 end def deg2rad(deg) deg / 180.0 * math::pi end end l = location.new(51.4663, -0.165543) p l.ranges(10) #=> [ # [51.32156821710003, 51.611031782899964], # [-0.39786664062357346, 0.06678064062357347] # ]

ruby-on-rails ruby

Python instance attribute not being recognized -



Python instance attribute not being recognized -

this question has reply here:

i maintain on getting type error 2 answers

i have next code in python:

class state: def _init_(self): self.x=list([]) self.possiblechests=list([]) self.visitedchests=list([]) def checkkeys(self): print self.x def addkey(self,x): self.x.append(key) current_state=state() future_state=state() current_state.addkey(4)

when run next error:

attributeerror: state instance has no attribute 'x'

why 'x' not beingness recognized instance attribute?

you need double underscores around __init__:

def __init__(self):

otherwise, python treat function normal method , not __init__ special method.

python attributes instance

c# - how to return results that have a date of yesterday and before -



c# - how to return results that have a date of yesterday and before -

i returning results using llblgen adapter model. using break points because cannot them populate kendo grid yet, can see coming back. need homecoming results have date property of yesterday , prior. not familiar @ using kendo grid nor llbl adapter. bulk of other examples out there using entity framework. here have far. there no error messages because stuck @ how setup filter?

controller

public actionresult bundlestatus() { homecoming view(); } [httppost] public actionresult bundlestatusread([datasourcerequest] datasourcerequest request) { var span = datetime.today.adddays(-1); dataaccessadapter adapter = new dataaccessadapter(); entitycollection allbundles = new entitycollection(new carrierbundleentityfactory()); adapter.fetchentitycollection(allbundles, null); var results = allbundles; homecoming json(results.todatasourceresult(request)); } }

view

@{ viewbag.title = "bundlestatusget"; } <div> @(html.kendo().grid<zoomaudits.dal.entityclasses.carrierbundleentity>() .name("grid") .columns(columns => { columns.bound(c => c.bundleid).width(140); columns.bound(c => c.carrierid).width(190); columns.bound(c => c.date); columns.bound(c => c.issent).width(110); }) .htmlattributes(new { style = "height: 380px;" }) .scrollable() .groupable() .sortable() .pageable(pageable => pageable .refresh(true) .pagesizes(true) .buttoncount(5)) .selectable(selectable => selectable .mode(gridselectionmode.multiple) .type(gridselectiontype.cell)) //.events(events => events.change("onchange").sync("sync_handler"))) .datasource(datasource => datasource .ajax() .read(read => read.action("bundlestatusread", "bundlestatus")) //.update(update => update.action("editinginline_update", "grid")) ) )

update controller

public actionresult bundlestatusread([datasourcerequest] datasourcerequest request) { var span = datetime.today.adddays(-1); dataaccessadapter adapter = new dataaccessadapter(); entitycollection allbundles = new entitycollection(new carrierbundleentityfactory()); relationpredicatebucket filter = new relationpredicatebucket(carrierbundlefields.date == span); adapter.fetchentitycollection(allbundles, filter); var results = allbundles; homecoming json(results.todatasourceresult(request));

it not returning results? see when open break point @ var results llbl enumeration yielded no results

hi haven't used llblgen in while , prior adapter. however, found this documentation on using entitycollection<t> class, adapter llblgen. hope helps.

by way, can utilize [httpget] , set action result allow get.

return json(results.todatasourceresult(request)), jsonrequestbehavior.allowget);

if trying yesterday , prior use:

relationpredicatebucket filter = new relationpredicatebucket(carrierbundlefields.date <= span);

c# asp.net-mvc kendo-grid llblgenpro

Rails: Credit Card Validator gem - need good example of how to use it -



Rails: Credit Card Validator gem - need good example of how to use it -

i looking utilize credit card validator gem validate credit card numbers , types. i'm still relatively new rails , though i've taken @ github documentation still trying work out how best utilize gem. need set code model? if so, how exactly? need utilize validate_with?

i've done few google searches can't seem find examples of how best utilize gem , set code.

seems reputation getting shot on here :(

here did. in creditcard model added next line:

validates_with validatecreditcard

i created file lib/validate_credit_card.rb follows:

class validatecreditcard < activemodel::validator def validate(record) if !creditcardvalidator::validator.valid?(record.card_number.to_s) record.errors[:base] << "the credit card number not valid." end end end

i had set next line config/application.rb

config.autoload_paths += %w( #{config.root}/lib )

this seems working, however, if best way of doing this?

also, though can see error message when come in invalid credit card number, credit card field doesn't surrounded in red, need whole errors[:base] , how works.

would appreciate feedback in regards beingness right way of doing type of validation.

many thanks.

here how got work.

i added next lines creditcard model:

validate :validate_credit_card private def validate_credit_card if !creditcardvalidator::validator.valid?(:card_number.to_s) errors.add(:card_number, "is not valid.") end end

ruby-on-rails credit-card

android - Sl4a recognize speech in background -



android - Sl4a recognize speech in background -

i started programming sl4a (in qpython) , great. tried utilize droid.recognizespeech function. 1 works fine too, in background listening keyword, google's 'ok google'. looked around, cannot find anything. don't know how can implement it. inquire you, can tell me, if possible, how create recognize speech listening in background waiting keyword?

i've toyed thought of doing this, never found useful practical application it. here's summary of research, hope it's plenty started: 1. speech recognizer facade has multiple parameters. usually, puts "none" in of them except first. here's facade in it's actuality:

recognizespeech: recognizes user's speech , returns result. prompt (string) text prompt show user when asking them speak (optional) language (string) language override inform recognizer should expect speech in language different 1 set in java.util.locale.getdefault() (optional) languagemodel (string) informs recognizer speech model prefer (see android.speech.recognizeintent) (optional) returns: (string) empty string in case speech cannot recognized.

so you're looking languagemodel in case, alternative restricted 2 types. web search model , free-form speech model. you're looking free-form speech model in case. here's little more info on model horse's mouth: google on free-form language model

once you've looked @ free-form speech model, should help chrome's continuous speech recognition model, should share lot of same characteristics of free-form language model. hope helps set on right direction

android python speech-recognition sl4a qpython

using multiple textures in libgdx efficiently -



using multiple textures in libgdx efficiently -

im new libgdx i've been using 2 weeks. problem understanding how texture loading works.

i managed load first texture (a player) using gdx.files.internal(player.png) or along lines , worked fine, added functionality create him move side side if key pressed command stuff , works too.

my problem comes when loading in texture, want create enemy player. have minimal knowledge on how this. thought if did "gdx.files.internal(enemy.png)" load in enemy texture doesn't, instead loads in player.png texture.

my question how load in enemy.png. have seen useful tutorials followed keeps loading player 1 time again , 1 time again every time.

please can help me understand, have been stuck on 3 days

i can show code if needed in case doing wrong. helpful if explain how efficiently utilize multiple textures because sense way i'm doing inst best practice

bundle com.mohamed.junglefighter; import com.badlogic.gdx.game; import com.badlogic.gdx.gdx; import com.badlogic.gdx.input; import com.badlogic.gdx.graphics.gl20; import com.badlogic.gdx.graphics.orthographiccamera; import com.badlogic.gdx.graphics.texture; import com.badlogic.gdx.graphics.g2d.sprite; import com.badlogic.gdx.graphics.g2d.spritebatch; import com.badlogic.gdx.graphics.g2d.textureregion; //i'm extending libgdx's built in game class implements activity listener public class junglefightermain extends game { private orthographiccamera camera; private spritebatch sbatch; private texture player; private texture enemy; //private spritebatch enemybatch; private sprite sprite; //just setting game heighty , width public static int gamewidth = 500, gameheight = 500; @override public void create () { //camera related photographic camera = new orthographiccamera(gamewidth, gameheight); //end of photographic camera related sbatch = new spritebatch(); player = new texture(gdx.files.internal("plane.png")); sprite = new sprite(player); enemy = new texture(gdx.files.internal("enemy.png")); sprite = new sprite(enemy); } public void dispose() { sbatch.dispose(); player.dispose(); enemy.dispose(); } @override public void render () { gdx.gl.glclearcolor(1, 1, 1, 1); gdx.gl.glclear(gl20.gl_color_buffer_bit); // photographic camera related sbatch.setprojectionmatrix(camera.combined); //keyboard functions if(gdx.input.iskeypressed(input.keys.left)){ if(gdx.input.iskeypressed(input.keys.control_left)) sprite.translatex(-1f); else sprite.translatex(-20.1f); } if(gdx.input.iskeypressed(input.keys.right)){ if(gdx.input.iskeypressed(input.keys.control_left)) sprite.translatex(1f); else sprite.translatex(20.1f); } sbatch.begin(); //sprite.setposition(-200, -200); sprite.draw(sbatch); sbatch.end(); } public void resize(int width, int height){ } public void pause(){ } public void resume(){ } }

i think found problem

player = new texture(gdx.files.internal("plane.png")); sprite = new sprite(player); enemy = new texture(gdx.files.internal("enemy.png")); sprite = new sprite(enemy);

see, have 1 sprite. if want have enemy load him, if want both, create 2 sprites..

player = new texture(gdx.files.internal("plane.png")); sprite1 = new sprite(player); enemy = new texture(gdx.files.internal("enemy.png")); sprite2 = new sprite(enemy);

and remember if want draw texture can use

batch.draw(texturename,xpos,ypos);

libgdx textures sprite 2d-games sprite-sheet

Ruby and Python sending data over serial behaving differently -



Ruby and Python sending data over serial behaving differently -

i trying create ruby library lcd. have written little amount of python code sends image, , derived illustration code. code works. updates lcd screen bitmap image provided.

import serial import io import sys import os import time import re ser1 = serial.serial() #initialize serial connection ser1.baudrate = 115200 #set baud rate ser1.port = '/dev/ttyacm0' #set port print ser1.port #print out port verification ser1.open() #start serial connection bmp1 = open('image.bmp', 'rb') #open bitmap file sending data1 = bmp1.read() #store info in variable bmp1.close() #close bitmap file ser1.write(data1) #send info on serial lcd

however, when converted code ruby, running not display on lcd. running 1 time again wouldn't display anything. running 3rd time, however, cause lcd filled 3 copies of image, overlapping each other. if cleared screen , ran again, final result of overlapped images not same previous time.

the next ruby code:

require 'serialport' port = "/dev/ttyacm0" baud = 115200 puts "connecting lcd on port #{port}, baud #{baud}" lcd = serialport.new(port, baud) bmp = file.open("image.bmp", "rb") info = bmp.read bmp.close puts "sending data..." lcd.write(data)

i can't seem figure out why behave differently, or how create ruby code work expected. have tried adding lcd.flush end of file, still doesn't display on first run of program.

python ruby lcd

android - Should I use [Service w/ Timer] or [Service w/ Thread] for a long running service? -



android - Should I use [Service w/ Timer] or [Service w/ Thread] for a long running service? -

i'm trying create app reads current running application , log how long it's active throughout day.

i've decided utilize activitymanager (since apparently it's way this). i've found/thought of various implementation, , have questions in deciding way best way go in respect battery consumption since service running entire time phone on. example, finding way in service doesn't poll when screen off

1) service w/ timer. think way poll activitymanager, if it's running in service won't service block app's main thread?

2) having service shoot off thread, poll activitymanager , sleep 2 seconds

3) service w/ pendingintent , alarmmanager

in short, method efficient , why?

android

javascript - how to redirect in jquery fancybox pop up to next page...in jquery -



javascript - how to redirect in jquery fancybox pop up to next page...in jquery -

i m using jquery fancy box popup window....for pop up.... when submit ...my form redirect in same window.....in popup.. want redirect page open window....not in same popup...

i used target blank ..but work every..time on click...i need redirect when got login done.... m creating project in codeigniter.....

my controller....

public function login() { if ( $this->input->post('action') ) { $this->form_validation->set_rules('user_name', 'username','required|valid_email'); $this->form_validation->set_rules('password', 'password', 'required|'); if ($this->form_validation->run() == true) { $username = $this->input->post('user_name'); $password = $this->input->post('password'); $rember = ($this->input->post('remember')!="") ? true : false; if( $this->input->post('remember')=="y" ) { set_cookie('username',$this->input->post('user_name'), time()+60*60*24*30 ); set_cookie('pwd',$this->input->post('password'), time()+60*60*24*30 ); } else { delete_cookie('username'); delete_cookie('pwd'); } $this->auth->verify_user($username,$password); if( $this->auth->is_user_logged_in() ) { if( $this->session->userdata('ref')!="" ) { redirect($this->session->userdata('ref'),''); } else { redirect('members/myaccount','refresh'); } } else { $this->session->unset_userdata(array("ref"=>'0')); $this->session->set_userdata(array('msg_type'=>'error')); $this->session->set_flashdata('error',$this->config->item('login_invalid')); redirect('users/login', ''); } } else { $data['heading_title'] = "login"; $this->load->view('users_login',$data); } } else { $data['heading_title'] = "login"; $this->load->view('users_login',$data); } } class="lang-js prettyprint-override">$(window).load(function (e) { $("#back-top").hide(); $(function () { $(window).scroll(function () { if ($(this).scrolltop() > 100) { $('#back-top').fadein(); } else { $('#back-top').fadeout(); } }) }); $(".login").fancybox({ 'width': 367, 'height': 600, 'autoscale': false, 'type': 'iframe' }); $(".fotget").fancybox({ 'width': 425, 'height': 286, 'autoscale': false, 'type': 'iframe' }); $(".profile").fancybox({ 'width': 700, 'height': 505, 'autoscale': false, 'type': 'iframe' }); $(".details").fancybox({ 'width': 400, 'height': 200, 'autoscale': false, 'type': 'iframe' }); $(".enquiry").fancybox({ 'width': 359, 'height': 450, 'autoscale': false, 'type': 'iframe' }); $(".contact").fancybox({ 'width': 317, 'height': 353, 'autoscale': false, 'type': 'iframe' }); $(".map").fancybox({ 'width': 425, 'height': 355, 'autoscale': false, 'type': 'iframe' }); });

the reason happening because popup content iframed... send message parent window redirect in main browser window, google on iframe communication it's parent window should info need this, hinges on having command of page beingness iframed!

example:...where ever redirects are...replace with...

echo "<script type=\"text/javascript\">window.top.postmessage('logged_in', '*');</script>"; exit; //make sure here, stop php execution!!

then in parent window (the 1 intitializing fancyboxes...)

window.onmesage = function(e){ if(e.data == 'logged_in'){ window.location.href = 'http://pathtopage'; } }

note: 'logged_in' json string

'{ "action":"something","redirect":"http://url" }'

just utilize

json.parse(e.data);

in listener extract json object

edit: crap... misunderstood question... don't see element using submit form... e.preventdefault(); on element before letting redirect anywhere....so illustration using anchor tag...

$('a.form-submit').on('click',function(e){ e.preventdefault(); var redir = $(this).attr('href'); var formdata = $('#theform').serialize(); $.post('http://formhandler/route',formdata,function(){ //open new window... window.open(redir); //or send info parent window... window.top.postmessage(redir,'*'); }); });

javascript jquery ajax fancybox-2

json - Filter by sender Outlook OData web service api -



json - Filter by sender Outlook OData web service api -

i trying filter outlook 365 inbox sender address. looking @ odata spec have throught involve querying complex type such

https://outlook.office365.com/ews/odata/me/folders('inbox')/messages?$filter=from/address eq 'some@address.com'.

unfortunately returns property 'address' invalid.

i can confirm can access data

looking json if query inbox see e-mail

...

"from": { "name": "some one", "address": "some@address.com" },

...

any help query string appreciated

(p.s. have dummied address)

i can repro failure , stacktrace, should service issue. odatalib can back upwards filter of complex type (you can check http://services.odata.org/v4/odata/odata.svc/persondetails?$filter=address/city eq 'boise'), the exchange service not.

"stacktrace": " @ microsoft.exchange.services.odata.model.odatafilterconverter.getentityproperty(querynode querynode)\r\n @ microsoft.exchange.services.odata.model.ewsfilterconverter.convertfilternode(querynode querynode)\r\n @ microsoft.exchange.services.odata.model.ewsqueryadapter.getrestriction()\r\n @ microsoft.exchange.services.odata.model.messageprovider.find(string parentfolderid, messagequeryadapter queryadapter)\r\n @ microsoft.exchange.services.odata.model.findmessagescommand.internalexecute()\r\n @ microsoft.exchange.services.odata.odatacommand`2.execute()\r\n @ microsoft.exchange.services.odata.odatatask.execute(timespan queueanddelaytime, timespan totaltime)"

json web-services outlook odata outlook-web-app

ruby on rails - Remove Http header response -



ruby on rails - Remove Http header response -

i working on project requires client create api phone call rails application , homecoming xml without http header info.

its returning:

http/1.1 200 ok cache-control: no-cache, no-store, max-age=0, must-revalidate pragma: no-cache expires: fri, 01 jan 1990 00:00:00 gmt content-type: application/xml; charset= x-ua-compatible: ie=edge x-request-id: c5602cd7eb23ca8137bef8bb1f0a4f8a x-runtime: 0.027900 server: webrick/1.3.1 (ruby/1.9.3/2013-11-22) date: wed, 18 jun 2014 05:27:48 gmt content-length: 529 connection: keep-alive set-cookie: _session_id=a8039d615674feec206e6c55a7a7afc8; path=/; httponly <?xml version="1.0" encoding="utf-8"?> <cxml> <response> <status code="200" text="ok"/> <startpage> <url>http://localhost:3000/foobar/bah7ddonymfza2v0awrji... </startpage> </response> </cxml>

can help remove http headers within controller or config? below section.

http/1.1 200 ok cache-control: no-cache, no-store, max-age=0, must-revalidate pragma: no-cache expires: fri, 01 jan 1990 00:00:00 gmt content-type: application/xml; charset= x-ua-compatible: ie=edge x-request-id: c5602cd7eb23ca8137bef8bb1f0a4f8a x-runtime: 0.027900 server: webrick/1.3.1 (ruby/1.9.3/2013-11-22) date: wed, 18 jun 2014 05:27:48 gmt content-length: 529 connection: keep-alive set-cookie: _session_id=a8039d615674feec206e6c55a7a7afc8; path=/; httponly

i using nginx @ moment.

i have says kind of nonsense request, since http servers definition uses header talk 1 another. have been informed w3 think otherwise.

http://www.w3.org/protocols/rfc2616/rfc2616-sec4.html#sec4

i have googled around hours attempting other solutions changing rails controller without success. lastly resort perchance changing config in nginx , wouldn't effect whole rails application , not api calls or there way single out 1 call?

thanks in advance.

t

this nonsense request, yeah. can utilize httpheadersmore module remove of response headers. should it:

location /your/api/path { more_clear_headers '*'; }

however, can't remove connections header without patching nginx. , if could, can't remove first line of response ("http/1.1 200 ok", in case). without line, isn't http response. you're going have hard time convincing http server send non-http responses.

to you're describing, think you'll need custom server communicates on bare tcp sockets. this tutorial might help out. or maybe implement part of app in node.js (or tool)?

ruby-on-rails nginx http-headers xmlhttprequest httpresponse

javascript - location.href and fallback for page not available -



javascript - location.href and fallback for page not available -

is there way when reload page javascript have fallback if target page not available?

example:

i doing

location.href = 'http://www.google.com'

but maybe google downwards (or maybe url not exist anymore or malformed, etc...) , in case, avoid reloading. possible?

you can't recognize happens after visitor leaves page. thing. maybe check before redirect, if can connect (client side) javascript if website available , perform redirect. have check before redirect, not after fallback.

javascript

javascript - calculating value of cookie using jquery -



javascript - calculating value of cookie using jquery -

there 2 textboxes , user input value , store in java script variable after have persist value storing value in > blockquote cookies, 1 time again when user input new value want add-on of value lastly value

if understand question correctly seek append new value lastly value on same cookie?

if i'm right first of seek utilize plugin simplify handling of cookies.

https://github.com/carhartl/jquery-cookie

then seek this:

$("#yourinput").on("change", function() { var actualval = parseint($(this).val(), 10); var yourcookie = $.cookie('yourcookie') if( yourcookie ) { var newval = parseint(yourcookie, 10) + actualval; $.cookie('yourcookie', newval); } else { $.cookie('yourcookie', actualval); } });

edit based in code, seek parseint radix integer value. if have float value, seek parsefloat on inputs.

$(document).ready(function () { $('.ok').click(function () { var v_qty = parseint($('.qty').val(), 10); var v_hrs = parseint($('.hrs').val(), 10); var loadwatt = parseint($('.loadwatt').val(), 10); var total = 0; var check = 0; $.cookie('b_total'); check = $.cookie('b_total'); var count = parseint($.cookie('b_total'), 10); alert(count); var total = (v_qty * loadwatt) * v_hrs; total = parseint(total, 10) + count; var date = new date(); var minutes = 1; date.settime(date.gettime() + (minutes * 60 * 1000)); $.cookie("b_total", total, { expires: date }); check = $.cookie('b_total'); alert(check); }); });

javascript php jquery

regex - Query to replace a string with matching pattern -



regex - Query to replace a string with matching pattern -

i have string below.

'comp' "computer",'ms' "mouse" ,'keybr' "keyboard",'mont' "monitor",

is possible write query result as

'comp' ,'ms' ,'keybr' ,'mont' ,

i can replace string "as" empty string using replace query. how remove string within double quote?

can help me doing this? in advance.

select replace( regexp_replace('''comp'' "computer"' , '(".*")' ,null) ,' ' ,null) dual

the regex '(".*")' selects text whatever in double quotes.

edit:

the regex replaced entire length of matching pattern. so, might need tokenise string first using comma delimiter , apply regex. later bring together it.(listagg)

with str_tab(str1, rn) (select regexp_substr(str, '[^,]+', 1, level), -- delimts level (select '''comp'' "computer",''comp'' "computer"' str dual) tab connect level <= length(str) - length(replace(str, ',')) + 1) select listagg(replace( regexp_replace(str1 , '(".*")' ,null) ,' ' ,null), ',') within grouping (order rn) new_text str_tab;

edit2:

a cleaner approach @eatapeach

with x(y) ( select q'<'comp' "computer",'ms' "mouse" ,'keybr' "keyboard",'mont' "monitor",>' dual ) select y, regexp_replace(y, 'as ".*?"' ,null) x;

regex oracle replace

qt - Calling C++ method from QML -



qt - Calling C++ method from QML -

here qt project minimal skeleton show problem (check console after run project) http://uloz.to/xqxrxpdl/qtproject-zip

i seek phone call public slot qml

component.oncompleted: print(model.activate())

still getting error:

typeerror: property 'activate' of object qqmldmobjectdata(0x7fa35dd89eb0) not function

if tried phone call method dynamically c++, works:

auto item = new treeitem<mainmenuitem>(new mainmenuitem("kyklop")); qmetaobject::invokemethod(item, "activate");

if seek access regular property of treeitemtemplatebackend class qml (for instance level), works, problem if calling method. thinking subclass/template class.

registering qml:

qmlregistertype<treeitemtemplatebackend>("engine.ui", 1, 0, "treeitemtemplatebackend"); qmlregistertype<treeitem<inspectoritem>>("engine.ui", 1, 0, "inspectortreeitem"); qmlregistertype<treeitem<mainmenuitem>>("engine.ui", 1, 0, "mainmenutreeitem");

treeitem.h

#ifndef treeitem_h #define treeitem_h #include <qobject> #include "treeitemtemplatebackend.h" template <typename t> class treeitem : public treeitemtemplatebackend { public: explicit treeitem(qobject * parent = null); explicit treeitem(t * data, qobject * parent = null); explicit treeitem(treeitem<t> & other); void addchild(treeitem<t> * child); ~treeitem() {} }; #endif // treeitem_h

treeitemtemplatebackend.h

#ifndef treeitemtemplatebackend_h #define treeitemtemplatebackend_h #include <qlist> #include <qqmllistproperty> class treeitemtemplatebackend : public qobject { q_object q_property(qobject * info read info write setdata notify datachanged) q_property(qqmllistproperty<treeitemtemplatebackend> childs read childs notify childschanged) q_property(int level read level write setlevel notify levelchanged) public: explicit treeitemtemplatebackend(qobject * parent = null); qobject * data() const; void setdata(qobject * data); qqmllistproperty<treeitemtemplatebackend> childs() const; void addchild(treeitemtemplatebackend * child); int level() const; void setlevel(int level); void dump(qstring propertyname) const; ~treeitemtemplatebackend() {} signals: void activated(); void datachanged(); void childschanged(); void levelchanged(); public slots: void activate(); // trying phone call protected: qobject * m_data; qlist<treeitemtemplatebackend *> m_children; int m_level; static void append_function(qqmllistproperty<treeitemtemplatebackend> * property, treeitemtemplatebackend * item); static treeitemtemplatebackend * at_function(qqmllistproperty<treeitemtemplatebackend> * property, int index); static void clear_function(qqmllistproperty<treeitemtemplatebackend> * property); static int count_function(qqmllistproperty<treeitemtemplatebackend> * property); }; #endif // treeitemtemplatebackend_h

qqmldmobjectdata wrapper actual object used in delegates. original object accessible via property modeldata, model.modeldata.activate() should work.

qt qml qtquick2

vertical alignment - Centering Text with Unknown Heights Issues -



vertical alignment - Centering Text with Unknown Heights Issues -

i realize questions have been asked , answered; i've searched on multiple sites , have not found solution i've been able create work me. need vertically center text unknown heights; i've tried pseudo elements , different display types, including table , table-cell (which still in css).

you can see my site current result.

i have altered code in jsfiddle, real code below. also, i've noticed jfiddle code looks different result i'm getting on site. same code, jfiddle version doesn't text-align center. maybe other css or jquery helping site's code.

the actual code:

<div class="pinbin-image"> <div class="rollover-item"> <div id="hover"> <div class="link-text"> <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2> </div> </div> <a href="<?php the_permalink() ?>"><?php the_post_thumbnail( 'summary-image' ); ?></a> </div> </div>

the css:

#post-area .pinbin-image { display:inline-block; } .rollover-item { position:relative; overflow:hidden; } #hover { transition: 0.2s linear; -moz-transition: 0.2s linear; -webkit-transition: 0.2s linear; -o-transition: 0.2s linear; opacity: 0; } #hover { background-color: #fff; position: absolute; text-align: center; vertical-align: middle; text-decoration: none; } #hover { height: 90%; left: 6.38%; top: 4.8%; width: 87%; } #hover:hover { opacity: 0.75; } .link-text { position: absolute; text-align: center; vertical-align: middle; display: table; } .link-text h2 a:link { color: #333333; font-family: "century gothic", centurygothic, applegothic, sans-serif; font-size: 23px; line-height: 23px; text-decoration: none; padding: 20% 20px; width: 100%; display: table-cell; vertical-align: middle; text-align: center; } .rollover-item:hover .description { top:0; }

table , table-cell works fine me.

html:

<div id="parent"> <span id="child">vertically centered</span> </div>

css:

#parent { height:100%; display: table; } #child { display: table-cell; vertical-align: middle; }

and may not position link absolute

try next in jsfiddle.

css:

#post-area .pinbin-image { display:inline-block; } .rollover-item { position:relative; overflow:hidden; } #hover { transition: 0.2s linear; -moz-transition: 0.2s linear; -webkit-transition: 0.2s linear; -o-transition: 0.2s linear; opacity: 0; } #hover { background-color: #fff; position: absolute; text-align: center; vertical-align: middle; text-decoration: none; } #hover { padding:50% 0; left: 6.38%; top: 4.8%; width: 87%; display:table;} #hover:hover { opacity: 0.95; } .link-text { position: static; text-align: center; vertical-align: middle; display: table-cell; } .link-text h2 a:link { color: #333333; font-family: "century gothic", centurygothic, applegothic, sans-serif; font-size: 23px; line-height: 23px; text-decoration: none; padding: 20% 20px; width: 100%; display: table-cell; vertical-align: middle; text-align: center; } .rollover-item:hover .description { top:0; }

html:

<div class="pinbin-image"> <div class="rollover-item"> <img src="http://neoqueenhoneybee.com/blog/wp-content/uploads/2014/03/1381568_549239698487215_587096537_n-750x561.jpg" alt=""/> <div id="hover"> <div class="link-text"> <h2><a href="<?php the_permalink() ?>">pokemon: snivy</a></h2> </div> </div> <a href="<?php the_permalink() ?>"><?php the_post_thumbnail( 'summary-image' ); ?></a> </div> </div>

btw. code hard read. seek not repeat same selectors.

--

from here: http://www.vanseodesign.com/css/vertical-centering/

scroll downwards to: css table method

vertical-alignment

asp.net - JQuery Dialog doesn't seem to work with large amount of data -



asp.net - JQuery Dialog doesn't seem to work with large amount of data -

jquery code in .ascx page <script type="text/javascript"> function showdialog(title, message) { $("#warrantcjisresponse").find("#dialogmessage").appendto(message); $("#warrantcjisresponse").dialog(); } </script> <!-- button within of <asp:repeater> --> <asp:button id="qdpbutton" type="button" text="qdp" runat="server"/> <div id="warrantcjisresponse" > <pre id="dialogmessage"></pre> </div> //code behind setting click handler , params button.onclientclick = "showdialog('qdp','" + message + "')";

if set "message" little amount of info "test", works. if set big amount of data, doesn't work, page flashes , nil happens.

if you're trying append 'message' #dialogmessage, you're using wrong function. switch appendto() append().

http://api.jquery.com/append/

http://api.jquery.com/appendto/

jquery asp.net

android - Trouble with logging my data with crashlytics -



android - Trouble with logging my data with crashlytics -

i'm trying logs service info crashlytics in android application. don't see logs in dashboard. used this:

string mylog = getservicedata(); //mylog not null , non-empty crashlytics.log(mylog);

and this:

string mylog = getservicedata(); //mylog not null , non-empty crashlytics.log(log.error, getstring(r.string.app_name), mylog);

i tried generate exception in application , handle it, have no results:

try { int = 0; = 1/a; } grab (exception e) { crashlytics.log(mylog); }

also read on crashlytics log not sent need initialize crashlytics before log data. set crashlytics.start(this) in onstart() event of activity didn't see logs in dashboard again. @ lastly tried set crashlitycs.start(this) straight before logging data, still have no logs in dashboard.

plase, tell me wrong , how custom logs in crashlytics dashboard?

i had similar situation. experimenting, able deduce rules crashlytics' behavior.

crashlytics upload crash study "to dashboard" if fatal exception occurs. in other words, when app crashes. , nil shows unless , until crash study uploaded.

if log non-fatal exception, using crashlytics.logexception(e), crash study not uploaded till next time app restarted. not see exception in crashlytics dashboard till app restart.

you can tell when upload occurs because you'll see sort of message in logcat:

07-17 19:30:41.477 18815-18906/com.foo.bar i/crashlytics﹕ crashlytics study upload complete: 55a9ba0c01d7-0001-462d-b8b4c49333333.cls

a crashlytics log message must associated fatal or non-fatal exception show in dashboard.

furthermore, log messages aren't associated exception do not survive app restart.

so, if log few messages, restart app, app throws exception, or logs non-fatal exception using crashlytics.logexception(), log messages lost. not show in dashboard.

if want log messages without fatal exception, utilize 1 or more crashlytics.log() statements followed crashlytics.logexception().

to verify works, have code run, restart app. in dashboard, should see logs associated issue created non-fatal exception. in wild, you'll have trust users restart app regularity.

android logging crashlytics

How to make sure PHP version is above a certain version in order to run code? -



How to make sure PHP version is above a certain version in order to run code? -

i'm making script used on multitude of servers, in install file, need find version server running file can determine whether or not install script.

instead of using array versions allowed , running through loop see if matches, what's easier way create sure they're running new plenty version of php?

run check between current version , whatever version requirement have.

define("required_version", "5.5.13"); if(!version_compare(php_version, required_version, "<")) { // current php version < required version }

php version