Wednesday, 15 August 2012

Is there a way to determine the root cause for 'Unsupported get request' when accessing a Facebook Page -



Is there a way to determine the root cause for 'Unsupported get request' when accessing a Facebook Page -

this stack overflow question illustrates various reasons why facebook graph api may limit access facebook page: graph api returns 'false' or 'unsupported request' accessing public facebook page

however, question ways figure out exact root restriction cause (graph api, facebook ui, etc.) when can access facebook page user access token , not app access token. i'm scraping info facebook pages , want able tell page owners specific restriction needs adjusted create page visible our app.

these restrictions mentioned in stack overflow thread:

age restriction country restriction alcohol unpublished - "is_published" field in page

are there others? how check first 3 if restrictions in effect?

fyi, current facebook page i'm trying figure out why user access token works , not app access token "forestsociety" facebook page.

https://developers.facebook.com/tools/explorer?method=get&path=forestsociety&version=v2.0

thank in advance!

no, reason cannot access piece of content intentionally not revealed -

you should able access piece of content via id if received object id api phone call (e.g. if inquire user's feed , post id, post id should accessible directly), if seek access arbitrary id , don't have permission to, reason intentionally not revealed

facebook facebook-graph-api

c# - Condition a to appear in ASP.NET from a List -



c# - Condition a <div> to appear in ASP.NET from a List -

i have list total of categories, want ones "featured" appear. code:

<div class="categories"> <% (int = 0; < lista.count; i++){ %> <% var categorias = lista[i]; %> <div id="cats"><a id="categoriabtn" href="#" title="button"><%= categorias.name %></a></div> <%} %> </div>

this generates list shows of categories names, implementing "featured categories" option, want skip ones have boolean alternative false:

categorias.featured == false

i tried this:

<div class="categories"> <% (int = 0; < lista.count; i++){ %> <% var categorias = lista[i]; %> <% if (categorias.featured == true){ %> <div id="cats"><a id="categoriabtn" href="#" title="button"><%= categorias.name%></a></div> <br /> <%} else{ this.visible = false; } } %> </div>

while writing create work, think there wrong in it. want create sure there no problems before publishing change.

this code has fundamental problem. giving multiple html elements same id. each 1 should unique. i'd this:

<div class="categories"> <% (int = 0; < lista.count; i++){ %> <% var categorias = lista[i]; %> <% if (categorias.featured == true){ %> <div id="cats<%=i%>"><a id="categoriabtn<%=i%>" href="#" title="button"><%= categorias.name%></a></div> <br /> <%} } %> </div>

c# html asp.net

lua - Pointer to number -



lua - Pointer to number -

it seems there's know such thing reference number/boolean/lightuserdata in lua. however, easiest way set global in lua points c++ native type (e.g. float) , have update automatically when alter corresponding global in lua?

class="lang-c prettyprint-override">int foo = 2; //imaginary lua function want lua_pushnumberpointer(state,&foo) lua_setglobal(state,"foo") class="lang-lua prettyprint-override">-- later, in lua script foo = 5;

the lastly line should automatically update foo on c++ side. easiest way accomplish this?

take @ meta tables, tags __index , __newindex. if set them suitable functions, have total command happens when new index set / unset index queried.

that should allow asked for.

it might advantageous set __newindex custom function , save interesting entries in table set on __index.

example handler __newindex , companion definition of __index. consider implementing on native side though, performance, , because __hidden_notify_world() native.

do local meta = getmetatable(_env) or {} setmetatable(_env, meta) local backing = {} _env.__index = backing function _env:__newindex(k, v) if backing[k] ~= v backing[k] = v __hidden_do_notify_world(k, v) end end end

if using lua < 5.2 (2011), must utilize _g instead of _env.

lua lua-api

coffeescript - Reuse Meteor template - Isolating events -



coffeescript - Reuse Meteor template - Isolating events -

i tried:

template.skillssearch = $.extend template.skillssearch, rendered: -> session.set('s' + @_id, null) session.set('searchfocused' + @_id, null)

@_id worked before, think because within each statement. not have loop , @ {}(no _id in object).

suppose have this:

body +mytemplate +mytemplate

how unique id per template instance? or, how can create unique session keys when reusing template?

this how solved it:

template(name='father1') 'father1' +reusedtemplate template(name='father2') 'father2' +reusedtemplate template(name='reusedtemplate') h1 #{avariable}

then in coffeescript:

template.reusedtemplate = $.extend template.reusedtemplate, rendered: -> # here @data contains whatever pass in # i.e. 'father1' , 'father2' respectively avariable: -> # here @ contains whatever pass in # i.e. 'father1' , 'father2' respectively

coffeescript meteor jade

c# - Bing Map on Windows Phone 8.1 -



c# - Bing Map on Windows Phone 8.1 -

i'm trying alter viewport of map within windows phone 8.1 app. have set center (that works) , lowerleft/upperright coordinates set bounds of map, have zoomlevel property can't help me set bounds of map precision.

this have:

xaml

xmlns:maps="using:windows.ui.xaml.controls.maps" ... <maps:mapcontrol x:name="mymap" mapservicetoken="<token>"/>

code

this.mymap.center = new geopoint(new basicgeoposition() { latitude = 46.85, longitude = 8.94});

now want set upperright , lowerleft corner set bounds. saw article here doesn't work me.. convertgeocoordinatetoviewportpoint doesn't exist namespace windows.ui.xaml.controls.maps , don't know why.

thank you.

you have specific method set bounds of current mapcontrol trysetviewboundsasync, see:

http://msdn.microsoft.com/en-us/library/windowsphone/develop/dn637065.aspx

and might interested in geoboundingbox class:

http://msdn.microsoft.com/en-us/library/windowsphone/develop/windows.devices.geolocation.geoboundingbox.aspx

and here illustration (map mapcontrol):

list<basicgeoposition> basicpositions = new list<basicgeoposition>(); basicpositions.add(new basicgeoposition() { latitude = 50, longitude = 3 }); basicpositions.add(new basicgeoposition() { latitude = 55, longitude = 8 }); basicpositions.add(new basicgeoposition() { latitude = 42, longitude = 0 }); this.map.trysetviewboundsasync(geoboundingbox.trycompute(basicpositions), null, mapanimationkind.default);

c# bing-maps windows-phone-8.1

c++ - Windows Phone 8 save data -



c++ - Windows Phone 8 save data -

i have mutiplatform game. save user progress use:

nsuserdefaults - ios android.content.sharedpreferences - android ::regcreatekeyex - win32

what should utilize windows phone 8 store app?

if want work files , folders in local folder, can utilize isolatedstoragefile or if want work key/value pairs in local folder, can utilize isolatedstoragesettings.

for more refrence can go here data windows phone 8

c++ windows-phone-8 save

android - Namespace of element declaring a namespace? -



android - Namespace of element declaring a namespace? -

in xml such as:

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:orientation="vertical" <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="24dp" android:text="@string/question_text" /> </linearlayout>

what namespace of linearlayout , textview elements?

would http://schemas.android.com/apk/res/android namespace? or not in namespace @ all?

lastly, attributes have explicitly define namespace belong to, if any?

with widgets supplied android, not need utilize total bundle declaration bare class names (ex linearlayout, textview, etc.). if create custom widget, you'll have utilize bundle based declaration (ex. com.example.android.myawesomewidget).

only root widget requires android xml namespace (xmlns:android="http://schemas.android.com/apk/res/android") because of kid elements inherit namespace. means 1 time define namespace in root element not need place in kid elements.

and finally, attributes must explicitly utilize namespace prefix avoid confusion , collision. ex: android:layout_width="match_parent" valid layout_width="match_parent" not.

android xml

Javascript download attribute not working when saving image dataUrl -



Javascript download attribute not working when saving image dataUrl -

i using chrome.

this code.

var save = document.createelement('a'); save.href = fileurl; save.download = filename; alert(save.download); save.click();

it works doesn't alter image name. saves "download.png".

what wrong?

it help see fileurl , filename set guessing problem. in firefox , chrome have utilize relative path image. not work on remote images.

mdn says:

in firefox 20 attribute honored links resources same-origin.

i have tested in chrome , firefox , works if utilize relative path image:

save.href = "images/wonky-download-121938718712348891912.jpg"; save.download = "coolname.jpg";

i ralative path because using mysite.com/image.jpg didn't work while image.jpg did.

update

whatwg.org says:

in cross-origin situations, download attribute has combined content-disposition http header, attachment disposition type, avoid user beingness warned of perchance nefarious activity.

javascript download data-url

Using nctoolbox for a list of files in a matlab for-loop -



Using nctoolbox for a list of files in a matlab for-loop -

i have piece of code

sumrain=zeros(881,1121); run('d:\nctoolbox-nctoolbox-3161fee\setup_nctoolbox.m') j=1:m nc=ncgeodataset(lsf(j,:)); %lsf list of file names dirvar=nc.geovariable('total_precipitation_surface_1_hour_accumulation'); g=dirvar.grid_interop(1,:,:); dir=dirvar.data(1,:,:); dir=reshape(dir,[881 1121]); sumrain=sumrain+dir; clear nc dirvar end

the problem is, seems nctoolbox never works (for me) unless activated before reading each file. if set line runs install file within loop works fine, code slow. when maintain run setup line outside loop error:

"warning: netcdf-java cdm contains no coordinate info associated variable. returning ncvariable instead of ncgeovariable object. (methods rely on coordinate info 'grid' or 'geosubset' not available. in ncgeodataset>ncgeodataset.geovariable @ 459 in ncgeodataset>ncgeodataset.subsref @ 622 in s4processing @ 16 "

i set lines run setup function in startup.m (i see beingness activated everytime run matlab), didn't work either.

that warning getting isn't error , has nil setup_nctoolbox. need run setup_nctoolbox once; adjusts matlab's path , javaclasspath include dependencies needed run nctoolbox. running multiple times within loop isn't doing anything.

that warning telling dataset reading missing coordinate variable information. that's problem dataset, not nctoolbox.

matlab for-loop grib

python - Can't assign proper value to QCombBox using PySide -



python - Can't assign proper value to QCombBox using PySide -

since pyside can't pickled, i've decided manually write scheme parameters file that, when opened via qfiledialog, can used populate qwidgets appropriate data...so far, works except 1 of qwidgets, databox, qcombobox in separate class.

as you'll see in next code, set print lines see values of list stores parameters. in stdout, can see values should be, qcombobox.setedittext() method doesn't assign value combo box displays text set it...the images linked show 2 things "openfile" case: text displayed in qcombobox (databox) positioned strangely (it works, should centered), , 2 separate instances of figurecanvas display info showing same info (since boxes beingness assigned same value first value in dictionary/qcombobox). these 2 instances of databox should have da_0 & da_1 in them, both have da_0.

i tried different method of qcombobox class, setitemtext(), didn't display info or populate databox.

here links screenshots of gui in both savefile case , openfile case.

here's relevant code & full code. apologize formatting in gist...copying textedit didn't work will.

this method, openfile, pulls appropriate info file, setedittext() method doesn't set databox show it. clear, value da_1 prints right before added combo box, 1 time it's added combo box, goes wrong...these 2 of import lines of code observe:

print "databox value ", self.graphvalues[x] # works fine self.opts[opt].databox.setedittext(self.graphvalues[x]) # doesn't work @ all

self.opts dictionary of strings (names of figures/plots) paired instances of class handles setting graphing options

databox qcombobox holds strings (names of figures/plots)

# read parameters file , sets sim/graphvalues (1.1) def openfile(self): self.filepath, _= qfiledialog.getopenfilename(self, 'open file', \ '~/', 'c files (*.c);;simulations (*.sim)' ) fullpath = self.filepath.split("/") title = fullpath[-1] self.w.setwindowtitle(title) if self.filepath[-4:] == ".sim": open(self.filepath, 'r') f: self.simvalues = [""] value = f.readline() while 1: if value != "\n": self.simvalues.append(value) value = f.readline() else: break self.graphvalues = [""] value = f.readline() while 1: if value != "\n": self.graphvalues.append(value) value = f.readline() else: break self.files = f.readlines() self.numsim.settext(self.simvalues[1]) self.numtrials.settext(self.simvalues[2]) self.numticks.settext(self.simvalues[3]) self.numgraphs.settext(self.simvalues[4]) self.dirpath = self.simvalues[5] x = 1 opt in self.opts: self.opts[opt].styleselect.setedittext(str(self.styles[opt])) self.opts[opt].databox.additems(self.files) if self.opts[opt].styleselect.currenttext() == "1": print "databox value ", self.graphvalues[x] self.opts[opt].databox.setedittext(self.graphvalues[x]);x+=1 print "xlabel value ", self.graphvalues[x] self.opts[opt].xlabel.settext(self.graphvalues[x]);x+=1 print "ylabel value ", self.graphvalues[x] self.opts[opt].ylabel.settext(self.graphvalues[x]);x+=1 print "xrange value ", self.graphvalues[x] self.opts[opt].xrange.settext(self.graphvalues[x]);x+=1 print "yrange value ", self.graphvalues[x] self.opts[opt].yrange.settext(self.graphvalues[x]);x+=1 elif self.opts[opt].styleselect.currenttext() == "2": pass else: pass self.plot()

this method, savefile, not necessary show, wanted clear issue not writting data.

# saves sim & graph values , writes them file (1.2) def savefile(self): self.filepath, _= qfiledialog.getsavefilename(self, 'save file', \ '~/', 'simulations (*.sim)' ) fullpath = self.filepath.split("/") title = fullpath[-1] self.w.setwindowtitle(title) self.simvalues = [str(self.numsim.text()),str(self.numtrials.text()), \ str(self.numticks.text()),str(self.numgraphs.text())] self.simvalues.append(self.dirpath) self.graphvalues = [] opt in self.opts: self.styles[opt] = self.opts[opt].styleselect.currenttext() if self.opts[opt].styleselect.currenttext() == "1": self.graphvalues.append(self.opts[opt].databox.currenttext()) self.graphvalues.append(self.opts[opt].xlabel.text()) self.graphvalues.append(self.opts[opt].ylabel.text()) self.graphvalues.append(self.opts[opt].xrange.text()) self.graphvalues.append(self.opts[opt].yrange.text()) elif self.opts[opt].styleselect.currenttext() == "2": pass else: pass open(self.filepath, 'w') f: item in self.simvalues: f.write(item+"\n") f.write("\n") item in self.graphvalues: f.write(item+"\n") f.write("\n") item in self.files: f.write(item+"\n")

here stdout print lines:

databox value da_1 xlabel value other ylabel value things xrange value len(data) yrange value y range databox value da_0 xlabel value ylabel value stuff xrange value len(data) yrange value y range

python pyside

jquery - Show/Hide div based on another div's state without refreshing the page -



jquery - Show/Hide div based on another div's state without refreshing the page -

i trying show/hide 'link2' based on state of div. if it's open, hide link2, if it's closed, show link2.

both link1 , link2 trigger close or open panel div. since using sessions remember state of div, want corresponding link show well.

http://jsfiddle.net/9kua5/

$('#panel').toggleclass('hidden', sessionstorage.getitem('form_visible') != 'true'); $('#flip, #flip_slip').click(function() { $('#panel').slidetoggle('slow', function() { $(this).toggleclass('hidden'); }); sessionstorage.setitem('form_visible', $('#panel').hasclass('hidden')); }); $('#flip_slip')[ $('#panel').is(':visible') ? "hide" : "fadein" ]();

html:

<div id="panel"> test <div id="flip">link1</div> </div> <div id="flip_slip">link2</div>

edit:

example, if click on link1 -> panel div fades ou -> link2 appears since session saves state of panel div, on page refresh, link2 should visible

demo fiddle pretty simplified code. jquery code

$(function () { if(sessionstorage.getitem('form_visible')===null){ sessionstorage.setitem('form_visible', 'false');//initiate first time }; checksessionstorage(); //call alter #panel display $('#flip_slip,#flip').click(function () { sessionstorage.setitem('form_visible', (sessionstorage.getitem('form_visible') == 'false' ? 'true' : 'false')); //change sessionstorage checksessionstorage(); //call alter #panel display }); function checksessionstorage() { if (sessionstorage.getitem('form_visible') == 'true') { $('#panel').slidedown(); $('#flip_slip').fadeout(); } else { $('#panel').slideup(); $('#flip_slip').fadein(); } } });

jquery

javascript - AJAX success callback alert not working? -



javascript - AJAX success callback alert not working? -

i've checked out various other posts on so, don't seem see problem, , hoping if help me shed lite on issue. basically, i'm doing microblogging appliation , inserting tweet when button clicked, calls jquery ajax function. here's respective code:

home.js

this ajax jquery call

function sendtweet(single_tweet) { var tweet_text = $("#compose").val(); tweet_text = tweet_text.replace(/'/g, "&#39;"); tweet_text = tweet_text.replace(/"/g, "&#34;"); var postdata = { author : $("#username").text().split("@")[1], // careful of @! - @username tweet : tweet_text, date : gettimenow() }; $.ajax({ type : 'post', url : '../php/tweet.php', info : postdata, datatype : 'json', success : function(data) { alert(data.status); } }) }

the ajax phone call works successfully, , tweet inserted, can't alert phone call fireback under success parameter. tried basic alert('abc'); didn't work either.

tweet.php

this wrapper, looks this:

<?php include 'db_functions.php'; $author = $_post['author']; $tweet = $_post['tweet']; $date = $_post['date']; insert_tweet($author, $tweet, $date); $data = array(); $data['status'] = 'success'; echo json_encode($data); ?>

this inserts tweet database, , wanted seek sending simple json formatted info back, data.status didn't work on success callback.

db_functions.php

this insert_tweet function in, , looks this:

function insert_tweet($author, $tweet, $date) { global $link; $author_id = get_user_id($author); $query = "insert tweets (`author id`, `tweet`, `date`) values ('{$author_id}', '{$tweet}', '{$date}')"; $result = mysqli_query($link, $query); }

i've tested it, , i'm pretty sure runs fine. uncertainty cause of problem, if is, i'm ears. i've tested $link, defined in file included in top of db_functions.php file, , works.

would appreciate advice regarding this, thanks!

update

changed success complete, , works. however, data object seems bit odd:

data.status pops 200 in alert

i tried changing json array element name data['success'] in php, , accessed in front end end data.success, , outputted in alert box:

function () { if ( list ) { // first, save current length var start = list.length; (function add( args ) { jquery.each( args, function( _, arg ) { var type = jquery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // inspect recursively add( arg ); } }); })( arguments ); // need add together callbacks // current firing batch? if ( firing ) { firinglength = list.length; // memory, if we're not firing // should phone call right away } else if ( memory ) { firingstart = start;…

what mean??

update 2

okay, don't know if helps, i've printed console log chrome's inspector, , if i'm not mistaken, json info sent fine. here's entire log:

object {readystate: 4, getresponseheader: function, getallresponseheaders: function, setrequestheader: function, overridemimetype: function…} abort: function ( statustext ) { always: function () { complete: function () { arguments: null caller: null length: 0 name: "" prototype: object __proto__: function empty() {} <function scope> done: function () { error: function () { fail: function () { getallresponseheaders: function () { getresponseheader: function ( key ) { overridemimetype: function ( type ) { pipe: function ( /* fndone, fnfail, fnprogress */ ) { progress: function () { promise: function ( obj ) { readystate: 4 responsejson: object status_success: "success" __proto__: object responsetext: "{"status_success":"success"}" status_success: "success" __proto__: object responsetext: "{"status_success":"success"}" setrequestheader: function ( name, value ) { state: function () { status: 200 statuscode: function ( map ) { statustext: "ok" success: function () { then: function ( /* fndone, fnfail, fnprogress */ ) { __proto__: object __definegetter__: function __definegetter__() { [native code] } __definesetter__: function __definesetter__() { [native code] } __lookupgetter__: function __lookupgetter__() { [native code] } __lookupsetter__: function __lookupsetter__() { [native code] } constructor: function object() { [native code] } hasownproperty: function hasownproperty() { [native code] } isprototypeof: function isprototypeof() { [native code] } propertyisenumerable: function propertyisenumerable() { [native code] } tolocalestring: function tolocalestring() { [native code] } tostring: function tostring() { [native code] } valueof: function valueof() { [native code] } __proto__: function __proto__() { [native code] } set __proto__: function __proto__() { [native code] }

update 3

console error scrn shot

try this:

$.ajax({ type : 'post', url : '../php/tweet.php', info : postdata, datatype : 'json', finish : function(data) { alert(data.status); } })

javascript php jquery ajax twitter

Maven Archetypes for Scala web app -



Maven Archetypes for Scala web app -

is there maven archetype building reactive web app with, akka, , nosql database mongo db deploy in sbt?

archetype not important. project must have right anatomy.

for example:

project |_build.properties <= specifies version of sbt utilize |_build.scala <= dependencies , project config set in here |_plugins.sbt <= sbt plugins can added here src |_ main | |_ scala | | | |_scalatrabootstrap.scala <= mount servlets in here | | |_org | | |_ yourdomain | | |_ projectname | | |_ myscalatraservlet.scala | |_ webapp | |_ web-inf | |_ views | | |_ hello-scalate.scaml | |_ layouts | | |_ default.scaml | |_ web.xml |_ test |_ scala |_ org |_ yourdomain |_ projectname |_ myscalatraservletspec.scala

scala maven akka reactive-programming

Changing a css attribute starting with a dash using Javascript -



Changing a css attribute starting with a dash using Javascript -

i'm trying utilize ussual method of changing css property javascript. problem webkit based attributes start dash making javascript invalid.

document.getelementbyid('circle1').style.-webkit-animation = 'updown 15s infinite';

how can modify code valid.

refer to question:

test.style.webkitanimationname = 'colorchange'; // had trailing space here not trimmed test.style.webkitanimationduration = '4s';

javascript css html5 css3 animation

c++ - Can I have a heap-like contiguous layout for complete trees based on a depth first order rather than breadth first? -



c++ - Can I have a heap-like contiguous layout for complete trees based on a depth first order rather than breadth first? -

the heap classical info construction puts finish binary (or d-ary generalized version) tree contiguous array, storing elements in breadth-first traversal order. in way, elements same level of tree stored contiguous 1 after other.

i'm implementing info construction which, under hood, finish balanced tree of fixed grade d, , want store tree in contiguous form free space of node pointers. thought of putting nodes breadth-first order used in heaps, i'm worried cache performance of typical search root downwards leaf, since @ each level l, jump on lot of elements.

is there way obtain compact contiguous representation of d-ary finish tree, based on depth-first order instead?

this way, nodes touched during search of leaf seem me more found closer each other. problem how retrieve index of parent , children of node, i'm wondering operations on tree in general efficient in setting.

i'm implementing thing in c++, in case matters @ all.

for simplicity, i'm going limit give-and-take binary trees, holds true n-ary trees, too.

the reason heaps (and trees in general) stored in arrays breadth-first because it's much easier add together , remove items way: grow , shrink tree. if you're storing depth-first, either tree has allocated @ maximum expected size, or have lot of moving items around when add together levels.

but if know you're going have complete, balanced, n-ary tree, selection of bfs or dfs representation largely matter of style. there isn't particular benefit 1 on other in terms of memory performance. in 1 representation (dfs) take cache misses front, , in other case (bfs) take cache misses @ end.

consider binary tree 20 levels (i.e. 2^20 - 1 items) contains numbers 0 (2^20 - 1). each node occupies 4 bytes (the size of integer).

with bfs, incur cache miss when first block of tree. have first 4 levels of tree in cache. next 3 queries guaranteed in cache. after that, you're guaranteed have cache miss when node index greater 15, because left kid @ x*2 + 1 @ to the lowest degree 16 positions (64 bytes) away parent.

with dfs, incur cache miss when read first block of tree. long number you're searching in left subtree of current node, you're guaranteed not cache miss first 15 levels (i.e. continually go left). branch goes right incur cache miss until downwards 3 levels above leaves. @ point, entire subtree fit cache , remaining queries incur no cache misses.

with bfs, number of cache misses straight proportional number of levels have search. dfs, number of cache misses proportional path taken through tree , number of levels have search. on average, number of cache misses incur when searching item same dfs bfs.

and math computing node positions easier bfs dfs, when want find parent of particular node.

c++ data-structures tree heap

How to throttle search (based on typing speed) in iOS UISearchBar? -



How to throttle search (based on typing speed) in iOS UISearchBar? -

i have uisearchbar part of uisearchdisplaycontroller used display search results both local coredata , remote api. want accomplish "delaying" of search on remote api. currently, each character typed user, request sent. if user types particularly fast, not create sense send many requests: help wait until has stopped typing. there way accomplish that?

reading documentation suggests wait until users explicitly taps on search, don't find ideal in case.

performance issues. if search operations can carried out rapidly, possible update search results user typing implementing searchbar:textdidchange: method on delegate object. however, if search operation takes more time, should wait until user taps search button before origin search in searchbarsearchbuttonclicked: method. perform search operations background thread avoid blocking main thread. keeps app responsive user while search running , provides improve user experience.

sending many requests api not problem of local performance of avoiding high request rate on remote server.

thanks

try magic:

-(void)searchbar:(uisearchbar *)searchbar textdidchange:(nsstring *)searchtext{ // limit network activity, reload half sec after lastly key press. [nsobject cancelpreviousperformrequestswithtarget:self selector:@selector(reload) object:nil]; [self performselector:@selector(reload) withobject:nil afterdelay:0.5]; }

ios search

angularjs - How to create 'Tree view inside a drop down box ' using angular directive -



angularjs - How to create 'Tree view inside a drop down box ' using angular directive -

i created tree view construction , custom drop downwards using angular directive need drop-down box tree structured view using angular directive.

am new angular framework please help-me solve problem.

you can utilize link create tree construction within select dropdown box. uses grouping within ng-options click here

angularjs jquery-ui jquery-plugins

java - Apache Commons Net - System.getProperty("line.separator") - does not work in Android -



java - Apache Commons Net - System.getProperty("line.separator") - does not work in Android -

i utilize apache commons api append new line file using ftpclient class. when run next code in java, new line appended file on ftp server. however, when run same code in android, string appended file without new line.

why new line using - system.getproperty("line.separator") - not transferred via ftp under android?

also, new line correctly displayed in logcat not work in txt file on ftp server. maybe there difference in character encoding between java , android?

thank much.

string log = system.getproperty("line.separator") + "blablabla"; boolean done = ftpclient.appendfile("log.txt", new bytearrayinputstream(log.getbytes("utf-8"))); system.out.println("log: " + log);

as file on server, wouldn't think you'd want client's value of system.getproperty("line.separator"); want know line separator on server is, you're working (apparently) in binary mode , ftp middle layer can't line-ending conversions you. (which once — perchance still is — quite mutual thing ftp clients , servers do; called "ascii" mode. [ah, halcyon days, when thought assume text in ascii, despite knowing, deep down, that wasn't sustainable... two-digit years...])

you either query info server, or take utilize particular line separator in server-side log file. if latter, \n selection if you're using *nix-based server. if you're on microsoft stack on server, \r\n improve choice.

java android ftp apache-commons-net

rotation - unity3d. How to get the result of transform.rotate without actually changing the gameobjects transform -



rotation - unity3d. How to get the result of transform.rotate without actually changing the gameobjects transform -

in unity3d i'm entering transforms position, rotation , scale matrix4x4 in order draw gizmos. i'd rotation quaternion entered matrix rotated amount of euler angles (angle) attempt, making re-create of transform (temp) , calling rotate() on , passing rotation quaternion matrix.

transform temp = transform; temp.rotate(new vector3(0f,0f,angle)); matrix4x4 rotationmatrix = matrix4x4.trs(transform.position,temp.rotation,transform.lossyscale);

unfortunately when rotates original transform , not temporary re-create of intended. how can add together amount of euler angle rotation quaternion?

i think i've answered question doesnt prepare problem...

matrix4x4 rotationmatrix = matrix4x4.trs(transform.position,transform.rotation*quaternion.angleaxis(angle,vector3.forward),transform.lossyscale);

rotation unity3d quaternions

eclipse - IBM RAD - Java Compiler & Project Facets Mismatch -



eclipse - IBM RAD - Java Compiler & Project Facets Mismatch -

i have installed both java 1.6 & 1.7 on system. using ibm rad 8.5 (built on top of eclipse) development , trying see errors/warnings in case compiler java 1.6 build project java 1.7 compiler.

if go "project->properties->java compiler" able see version "1.7" among listed compiler compliance levels. when go "project->properties->project facets" able see facets upto 1.6 , 1.7 not listed there.

when seek compile project keeping project facets 1.6 , compiler 1.7 project facets mismatch error. error says: - java compiler level not match version of isntalled java project facet.

please suggest changes need "1.7" becomes visible under installed java project facets. thanks.

edit:

did not read question enough......

may seek going org.eclipse.wst.common.project.facet.core.xml located in .settings folder of project , edit manually 1.7 this:

<installed facet="java" version="1.7"/>

looks have faceted project, maybe seek going project->properties->project facets , if java set 1.7.

else if using maven set

<properties> <maven.compiler.target>1.7</maven.compiler.target> <maven.compiler.source>1.7</maven.compiler.source> </properties>

java eclipse facets ibm-rad

sql - Look for count when selecting a variable -



sql - Look for count when selecting a variable -

declare @tmdate datetime ,@nbranchid int select @tmdate = getdate() ,@nbranchid = 3483 select strmessage = case when xpr.frevaluationprice <> d.fupplupenranta d.strinstrument +' in ' + f.strshortname + ' has not been saved. has wrong fixing in xp_results: ' + convert(varchar, xpr.frevaluationprice) + ' should be: ' + convert(varchar, d.fupplupenranta) else '' end dbo.deals d inner bring together dbo.xp_results xpr on 1=1 , xpr.strpaperid = convert(varchar, d.ntransactionid) , xpr.ninstrid = d.ninstrid , xpr.tmdate = convert(datetime, d.strmotpartkikod) --'20140404' inner bring together dbo.folders f on 1=1 , f.nid = d.nfolderid 1=1 , d.nbranchid = @nbranchid , d.ninstrid = 11 , d.ninternaltrans = 3 , d.nindex = 1

is possible somehow check count , else within case? problem one thousand rows selected , mixed up, , wan't see how many of each there is

you can set case within count this

select count(case when xpr.frevaluationprice <> d.fupplupenranta 1 else null end) select count(case when xpr.frevaluationprice <> d.fupplupenranta null else 1 end) from...

sql sql-server tsql

ruby on rails - Convert time zone of datetime returned by f.datetime_select -



ruby on rails - Convert time zone of datetime returned by f.datetime_select -

when utilize f.datetime_select in rails form, returns datetime controller in utc, e.g.

2014-06-18t11:00:00+00:00

my local time zone set melbourne (+10) specified in application.rb file:

config.time_zone = 'melbourne'

so when retrieve datatimes database automatically converted melbourne (+10) timezone, e.g.

2014-06-17 19:00:00 +1000

i want compare datetime returned f.datetime_select field in database. how can this?

i.e. how can alter time zone of datetime returned f.datetime select 'melbourne' (+10) without changing actual time? i.e. convert:

2014-06-18t11:00:00+00:00

to

2014-06-18t11:00:00+10:00

all dates stored in database in utc time. when app new date 'params' have 2 options: save activerecord model, , during ar perform heavylifting of deciding of timezone meant. if don't want save info model, have deal yourself. date select command homecoming 3 specially formatted strings in params hash. let's named field in form 'birthdate'. controller like:

"<your_model_name>" => {... , "birthdate(3i)" => "<day>", "birthdate(2i)" => "<month>", "birthdate(1i)" => "<year>", ...}

so deal info like:

time.zone.parse("#{ params[:model]['birthdate(3i)'] }-#{ params[:model]['birthdate(2i)'] }-#{ params[:model]['birthdate(1i)'] }")

and yeah know looks ugly, , after research surprised there no 'out of box' solution )

ruby-on-rails datetime

erb - Rails form_tag in tag -



erb - Rails form_tag in <tr></tr> tag -

i have form_tag in lastly row of table

<tr> <%= form_tag(emails_path, method: :post) %> <td><%= text_field_tag 'email', nil, class: "form-control" %></td> <td><%= submit_tag "add", class: "btn btn-small btn-success" %></td> <% end %> </tr>

which render following

<tr> <form accept-charset="utf-8" action="/emails" method="post"></form> <!-- close here --> <td><input class="form-control" id="email" name="email" type="text"></td> <td><input class="btn btn-small btn-success" name="commit" type="submit" value="add"></td> </tr>

the "add" button not working because form tags not wrapping input controls in it.

but when seek take form out of table this

<%= form_tag(emails_path, method: :post) %> <p><%= text_field_tag 'email', nil, class: "form-control" %></p> <p><%= submit_tag "add", class: "btn btn-small btn-success" %></p> <% end %>

the form render correctly , "add" button works.

how can it? , remember used work....

you can't this.

your form tag cannot exist there, interspersed markup of table. has go within <td>. you're producing invalid markup, , browser interpreting best can.

you should utilize sec option, <p> tags, or rethink need have form span multiple table cells, or wrap entire table in single <form>.

ruby-on-rails erb

html - Add text inside the DIV on top image -



html - Add text inside the DIV on top image -

i trying add together text "post" in center of div on top of image , adds next image:

html:

<div id="post"> <span class="post">post <img src="images/ask_post.png" /> </span> </div>

css:

#post { position:absolute; background-image:url('../images/ask_post.png') no-repeat; left:741px; top:157px; }

first remove image div element, text wont go on top of image, background. second, play around background properties until looks want to.

my guess need adjust background-size or background-position.

<div id="post"> <span class="post">post</span> </span>

see if background-size:cover; need. you'll have adjust height , width of div want.

html css

schema.org - How can I include an articleBody that is outside of the Article's itemscope? -



schema.org - How can I include an articleBody that is outside of the Article's itemscope? -

i attempting modify existing html include microdata using schema.org ontology.

due historic reasons, html not structured in proper hierarchy allow utilize of single itemscope. in example, articlebody separate name, author, , datepublished.

here simple snippet demonstrate illustration of problem , trying accomplish:

<html> <body> <div itemscope itemtype="http://schema.org/newsarticle"> <h1 itemprop="name">example news article page</h1> <span itemprop="datepublished">january 1, 2014</span> <span itemprop="author">john doe</span> </div> <div itemprop="articlebody"> <p> lorem ipsum </p> </div> </body> </html>

obviously, articlebody not contained within itemscope , hence parser have no clue fragment related to.

i attempted utilize itemref relate articlebody actual newsarticle.

<html> <body> <div itemscope itemtype="http://schema.org/newsarticle" id="myarticle"> <h1 itemprop="name">example news article page</h1> <span itemprop="datepublished">january 1, 2014</span> <span itemprop="author">john doe</span> </div> <div itemprop="articlebody" itemref="myarticle"> <p> lorem ipsum </p> </div> </body> </html>

this didn't appear work. modified utilize variations of adding itemscope, redeclaring itemtype, etc... unfortunately, none of methods seemed work. i'm assuming not right usage of itemref.

i made effort itemid. example:

<html> <body> <div itemscope itemtype="http://schema.org/newsarticle" itemid="foo"> <h1 itemprop="name">example news article page</h1> <span itemprop="datepublished">january 1, 2014</span> <span itemprop="author">john doe</span> </div> <div itemprop="articlebody" itemscope itemtype="http://schema.org/newsarticle" itemid="foo"> <p> lorem ipsum </p> </div> </body> </html>

again, didn't seem work. in both cases, google's structured info tester doesn't show expected results (the body either non-existent or not related article, itself) , yandex gives me error unable determine affiliation of these fields. there 2 possible reasons: fields incorrectly placed or orphan itemprop attribute indicated

i'm not quite sure if it's possible attempting accomplish. reason attempting things way have lot of pre-existing , complex html templates along massive amount of javascript. attempting refactor or otherwise modify existing html, aside adding annotations, become nightmare.

is possible attempting implement? if so, can show me simple code illustration or point out flaw in attempts?

thanks!

update

i got articlebody work using itemref. problem had using reference backwards -- referring newsarticle articlebody instead of other way around. here snippet:

<html> <body> <div itemref="content" id="articleheader" itemscope itemtype="http://schema.org/newsarticle"> <h1 itemprop="name">example news article page</h1> <span itemprop="author">john doe</span> </div> <div id="content" itemprop="articlebody"> <p> lorem ipsum blah blah blah </p> </div> </body> </html>

unfortunately, not appear scalable. let's want reference copyrightholder labeled in footer of page. if add together itemref article, appears blow , articlebody not related newsarticle. e.g.

<html> <body> <div itemref="content" itemref="company" id="articleheader" itemscope itemtype="http://schema.org/newsarticle"> <h1 itemprop="name">example news article page</h1> <span itemprop="author">john doe</span> </div> <div id="content" itemprop="articlebody"> <p> lorem ipsum blah blah blah </p> </div> <div id="company" itemprop="copyrightholder"> awesome company </div> </body> </html>

it appears on right track. problem had attempted declare itemref multiple times, each time id. according w3c, itemref expects space-separated list of id values.

here working example:

<html> <body> <div itemref="content company" id="articleheader" itemscope itemtype="http://schema.org/newsarticle"> <h1 itemprop="name">example news article page</h1> <span itemprop="author">john doe</span> </div> <div id="content" itemprop="articlebody"> <p> lorem ipsum blah blah blah </p> </div> <div id="company" itemprop="copyrightholder"> awesome company </div> </body> </html>

schema.org microdata

git archive with LibGit2Sharp -



git archive with LibGit2Sharp -

recently saw both this question , this question answers can utilize git archive retrieve single file remote git repository. great, , able emulate functionality using libgit2sharp.

i have looked @ the source code, can't find archiving. there's archiverbase class, seems it's meant derived from, , can't see derives it. objectdatabase has archive() method uses archiverbase parameter, none of archiverbase methods implemented. need derive archiverbase , overwrite methods myself? how go that? has been done in other class?

in short, how can emulate git archive using libgit2sharp retrieve single file described in linked questions?

there happen concrete archiver implementation in libgit2sharp, tararchiver, create tar archive of local git repository. however, work against repository, not work against remote endpoint, not suitable retrieve single file git archive can.

libgit2sharp not include way asking. options to:

clone repository, checking out single file use api offered git hosting provider (octokit github or rest api team foundation server) retrieve single file. execute git-archive yourself.

git libgit2sharp

robotframework - Read a file from a position in Robot Framework -



robotframework - Read a file from a position in Robot Framework -

how can read file specific byte position in robot framework?

let's have process running long time writing long log file. want current file size, execute affects behaviour of process , wait until message appears in log file. want read portion of file starting previous file size.

i new robot framework. think mutual scenario, haven't found how it.

there no built-in keywords this, writing 1 in python pretty simple.

for example, create file named "readmore.py" following:

from robot.libraries.builtin import builtin class readmore(object): robot_library_scope = "test suite" def __init__(self): self.fp = {} def read_more(self, path): # if don't know file, # set file pointer 0 if path not in self.fp: builtin().log("setting fp zero", "debug") self.fp[path] = 0 # open file, move pointer stored # position, read file, , reset pointer open(path) f: builtin().log("seeking %s" % self.fp[path], "debug") f.seek(self.fp[path]) info = f.read() self.fp[path] = f.tell() builtin().log("resetting fp %s" % self.fp[path], "debug") homecoming info

you can utilize this:

*** settings *** | library | readmore.py | library | operatingsystem *** test cases *** | illustration of "tail-like" reading of file | | # read current contents of file | | ${original}= | read more | /tmp/junk.txt | | # add together more info file | | append file | /tmp/junk.txt | new content\n | | # read new info | | ${new}= | read more | /tmp/junk.txt | | should equal | ${new.strip()} | new content

file-io robotframework

java - StringTemplate: how to detect, if variable in tempate is not explicitly set? -



java - StringTemplate: how to detect, if variable in tempate is not explicitly set? -

i using stringtemplate auto-generate configuration files , it's error, if user haven't defined of variables.

stringtemplate replace undefined variables (i mean $var$) empty string , error remain undetected. e.g.:

some_property=$some_property$

is rendered into:

some_property=

how forcefulness stringtemplate raise exception, if variable in template not explicitly defined using

stringtemplate.setattribute(key, value)

?

with stringtemplate 4 error listener informed undefined attribute. custom error-listener can handle required. example:

st tmp = new st("hello <name>!"); tmp.write(new noindentwriter(new stringwriter()), new sterrorlistener() { @override public void runtimeerror(stmessage msg) { if(msg.error == errortype.no_such_attribute) system.out.println("attribute not defined: "+ msg.arg); } @override public void compiletimeerror(stmessage msg) { } @override public void ioerror(stmessage msg) { } @override public void internalerror(stmessage msg) { } });

java string stringtemplate

Get multiple PHP date periods from a range of dates -



Get multiple PHP date periods from a range of dates -

i have array of dates this:

[room 01 - dbl] => array ( [0] => mon 23-06-2014 [1] => tue 24-06-2014 [2] => wed 25-06-2014 [3] => sat 28-06-2014 [4] => sun 29-06-2014 ) [room 02 - twn] => array ( [0] => tue 24-06-2014 [1] => wed 25-06-2014 [2] => sat 28-06-2014 [3] => sun 29-06-2014 )

you can see neither room has date th or friday. want able create date range (either datetime interval object or not - don't mind) each grouping of dates. room 02 - twn should give me 2 date periods - 1 tue-wed , sat-sun. how go this? know how create single date period of time using first , lastly items in array don't know how observe if there gap...

i'm not clear you're trying accomplish. anyway, in general case, can this.

the thought run whole array of items, , if "next" item contiguous candidate interval have, extend interval. else, candidate interval becomes standalone interval, , item failed check gives birth new candidate interval.

you need 2 functions: 1 that, given 2 items, returns whether it's true or false contiguous; other, given 2 items, returns "interval" 2 items extremes.

an empty $items homecoming empty interval.

function build_intervals($items, $is_contiguous, $make_interval) { $intervals = array(); $end = false; foreach ($items $item) { if (false === $end) { $begin = $item; $end = $item; continue; } if ($is_contiguous($end, $item)) { $end = $item; continue; } $intervals[] = $make_interval($begin, $end); $begin = $item; $end = $item; } if (false !== $end) { $intervals[] = $make_interval($begin, $end); } homecoming $intervals; }

for numbers, can use

$interv = build_intervals( array( 1, 2, 3, 5, 6, 9, 10, 11, 13, 17, 18 ), function($a, $b) { homecoming ($b - $a) <= 1; }, function($a, $b) { homecoming "{$a}..{$b}"; } ); print_r($interv);

returns

array ( [0] => 1..3 [1] => 5..6 [2] => 9..11 [3] => 13..13 [4] => 17..18 )

with dates, can maintain them datetime , datetimeintervals. if utilize timestamps, must supply contiguousness criterion that's valid timestamps. can awkward if have 2 timestamps before , after midnight next day. sure, should take times @ around midday (i.e., given 2 dates, timestamps of dates at midday. if they're less 36 hours apart, they're 2 adjacent days.

function($a, $b) { $a_ts = strtotime("{$a} 12:00:00"); $b_ts = strtotime("{$b} 12:00:00"); homecoming ($b - $a) <= (36 * 60 * 60); },

php date datetime time period

javascript - Use Browser to get GPS-Data and show pop-up and vibrate/play sound in Android -



javascript - Use Browser to get GPS-Data and show pop-up and vibrate/play sound in Android -

i programme website using javascript. website has able contantly checking gps-chip of android device.

when specific coordinates match (coordinates given remote-server , coordinates given gps-chip), user should notification sound or vibration , pop-up-window farther information. like, when device passes coffeeshop, user alerted, there coffee in area.

it has website, not app.

is such thing possible?

are there known examples services using such websites?

i hope, question accurate enough, answered.

thank in advance.

javascript android website gps notifications

java - How to assign Custom Redstone Textures? -



java - How to assign Custom Redstone Textures? -

@sideonly(side.client) public void registerblockicons(iiconregister p_149651_1_) { this.field_150182_m = p_149651_1_.registericon(this.gettexturename() + "_" + "cross"); this.field_150183_n = p_149651_1_.registericon(this.gettexturename() + "_" + "line"); this.field_150184_o = p_149651_1_.registericon(this.gettexturename() + "_" + "cross_overlay"); this.field_150180_p = p_149651_1_.registericon(this.gettexturename() + "_" + "line_overlay"); this.blockicon = this.field_150182_m; } @sideonly(side.client) public static iicon getredstonewireicon(string p_150173_0_) { homecoming p_150173_0_.equals("cross") ? modmain.bluestonewire.field_150182_m : (p_150173_0_.equals("line") ? modmain.bluestonewire.field_150183_n : (p_150173_0_.equals("cross_overlay") ? modmain.bluestonewire.field_150184_o : (p_150173_0_.equals("line_overlay") ? modmain.bluestonewire.field_150180_p : null))); }

i trying create custom redstone type don't know how assign textures. copied code original redstone file, i'm having hard time understanding it. getting errors in getredstonewireicon() method on field_ terms. saying cannot resolved or not field.

there's nil wrong code you've posted, need create sure variables match up, this:

import cpw.mods.fml.relauncher.side; import cpw.mods.fml.relauncher.sideonly; import net.minecraft.client.renderer.texture.iiconregister; import net.minecraft.util.iicon; class modmain { public static bluestonewire bluestonewire = new bluestonewire(); } public class bluestonewire { @sideonly(side.client) private iicon field_150182_m; @sideonly(side.client) private iicon field_150183_n; @sideonly(side.client) private iicon field_150184_o; @sideonly(side.client) private iicon field_150180_p; @sideonly(side.client) private iicon blockicon; public string gettexturename() { homecoming "bluestonewire"; } @sideonly(side.client) public void registerblockicons(iiconregister p_149651_1_) { this.field_150182_m = p_149651_1_.registericon(this.gettexturename() + "_" + "cross"); this.field_150183_n = p_149651_1_.registericon(this.gettexturename() + "_" + "line"); this.field_150184_o = p_149651_1_.registericon(this.gettexturename() + "_" + "cross_overlay"); this.field_150180_p = p_149651_1_.registericon(this.gettexturename() + "_" + "line_overlay"); this.blockicon = this.field_150182_m; } @sideonly(side.client) public static iicon getredstonewireicon(string p_150173_0_) { homecoming p_150173_0_.equals("cross") ? modmain.bluestonewire.field_150182_m : (p_150173_0_.equals("line") ? modmain.bluestonewire.field_150183_n : (p_150173_0_.equals("cross_overlay") ? modmain.bluestonewire.field_150184_o : (p_150173_0_.equals("line_overlay") ? modmain.bluestonewire.field_150180_p : null))); } }

java minecraft

parsing - How do I parse dates with more than 24 hours in dateutil's parser in Python 3? -



parsing - How do I parse dates with more than 24 hours in dateutil's parser in Python 3? -

i have bunch of times in column written "27:32:18", meaning waiting 27 hours, 32 minutes, , 18 seconds. maintain getting "valueerror: hr must in 0..23" whenever seek parse these values.

how should go parsing values or converting them more standard format? tried next test on single value:

time1 = "56:42:12" time2 = time1.split(':') time2 = [int(n) n in time2] time2.insert(0, time2[0] // 24) time2[1] %= 24

at point, time2 list consisting of [2, 8, 42, 12], equivalent 2 days, 8 hours, 42 minutes, , 12 seconds. how go converting python datetime representation in days, hours, minutes, , seconds in way allow python parse it? note doing unsupervised clustering on these time values, represent waiting times.

you don't have date, have time duration. may related dates , timestamps, in same units of time involved , displayed timestamps.

as such, cannot utilize dateutil parsing such values. easy plenty split out , parse yourself:

hours, minutes, seconds = map(int, time1.split(':'))

you can utilize datetime.timedelta() object represent duration:

td = datetime.timedelta(hours=hours, minutes=minutes, seconds=seconds)

this'll track delta in terms of days, seconds , microseconds:

>>> import datetime >>> time1 = "56:42:12" >>> hours, minutes, seconds = map(int, time1.split(':')) >>> datetime.timedelta(hours=hours, minutes=minutes, seconds=seconds) datetime.timedelta(2, 31332)

python parsing datetime python-3.x

swift - How to properly check if non-Optional return value is valid? -



swift - How to properly check if non-Optional return value is valid? -

i've run odd case when trying check homecoming value, , i'm wondering how "properly", in swift sense.

i have nsstatusitem (named item), , i'm trying assign nsstatusitem nsimage. when create nsimage, since pass string value image name, want create sure nsimage valid (what if mistype image name string?).

the first thing tried this:

if allow image: nsimage? = nsimage(named: "correcticonname") { item.image = image }

but gives error "bound value in conditional binding must of optional type". thought saying image: nsimage? made clear optional, guess not.

i changed this:

let image: nsimage? = nsimage(named: "correcticonname") if image { item.image = image }

which works totally fine. don't why works, while first illustration doesn't. seems more-or-less exact same thing. , since first 1 didn't compile, thought i'd seek other routes...

since nsimage(named:) homecoming nsimage , not nsimage?, thought i'd see happened if assigned homecoming value of constructor straight item:

item.image = nsimage(named: "correcticonname")

which works, doesn't allow error checking want do. if string wrong, nsstatusitem gets nil image, leads me having invisible status bar item.

next, tried this:

let image: nsimage = nsimage(named: "correcticonname") if image { item.image = image }

but gives error "type 'nsimage' not confirm protocol 'logicvalue'", guess means aren't allowed check if it's nil or not if statement.

however, can check whether nil doing following:

let image: nsimage = nsimage(named: "correcticonname") if image != nil { item.image = image }

so, here's question: how 1 supposed check homecoming value if isn't optional?

it is optional, compiler isn't showing you.

in apple's documentation working objective-c objects, says objects imported objective-c apis implicitly unwrapped optionals (like manually declare !):

in cases, might absolutely objective-c method or property never returns nil object reference. create objects in special scenario more convenient work with, swift imports object types implicitly unwrapped optionals. implicitly unwrapped optional types include of safety features of optional types. in addition, can access value straight without checking nil or unwrapping yourself. [source]

unfortunately, compiler/syntax checker doesn't treat them such. therefore, right way of checking declare image type nsimage initializer returning, implicitly unwrapped optional nsimage:

let image: nsimage! = nsimage(named: "correcticonname") if image { // }

alternate method (via @vacawama):

if allow image = nsimage(named: "correcticonname") nsimage! { // }

swift

c# - Enterprise Library Database connection close -



c# - Enterprise Library Database connection close -

we using microsoft enterprise library access sql server database.we having doubts how close db connection.code given below.

databasefactory.setdatabaseproviderfactory(new databaseproviderfactory(), false); database db = new databaseproviderfactory().create("dataconnectionstring"); string sqlcommand = ""; dbcommand dbcommand = db.getstoredproccommand(sqlcommand); dbcommand.commandtimeout = 0; seek { success = convert.toint32(db.executescalar(dbcommand)); homecoming success; } how can close database connection.

one way utilize using statements. objects implementing idisposable can used in such way, when code reaches closing bracket calls dispose() supposed rid of object.

databasefactory.setdatabaseproviderfactory(new databaseproviderfactory(), false); int success = 0; using (var db = new databaseproviderfactory().create("dataconnectionstring")) { string sqlcommand = ""; using (var dbcommand = db.getstoredproccommand(sqlcommand)) { dbcommand.commandtimeout = 0; seek { success = convert.toint32(db.executescalar(dbcommand)); } } } homecoming success;

c# visual-studio-2012 enterprise-library

java - Querying the data once and using it throughout the app like a cache -



java - Querying the data once and using it throughout the app like a cache -

i have web app(simple jsp,servlets) oracle database. have scenario need

to consult dataset (~100 rows , 4 columns) of info mathematical calculation. so,

instead of putting in database every time , reading each row every time,

thinking of querying info once, , using throughout app cache. ideas

how best implement this?

you have around 400 values.are doubles? have 1600 bytes. why not read

then array?

java jsp servlets

r - Join tables SQL command -



r - Join tables SQL command -

i have database 19 different tables.

dblisttables(con) [1] "sample_86103" "sample_87024" "sample_87082" "sample_88156" "sample_89090" "sample_90061" "sample_90186" [8] "sample_90204" "sample_91023" "sample_91_0235_2" "sample_92178" "sample_93146" "sample_93253" "sample_94049" [15] "sample_94152" "sample_94184" "sample_94286" "sample_96034" "sample_96102

i need utilize fulljoin command on each table, similar rbind in r.

since novice in sql language, have tried created data.frame first rbinding each of samples together, , write database.

however, takes much memory, , crashes r session. necessary me utilize sql database creation.

so using r, how can bring together created tables list above?

sql r rsqlite

c# - Conditionally set scrollbar button size -



c# - Conditionally set scrollbar button size -

i want alter size of scrollbars (arrow buttons , thumb) in application, dependent on condition. status bool variable (settings.touchscreenmode) in viewmodel of main window. trigger, this:

<style.triggers> <datatrigger binding="{binding datacontext.settings.touchscreenmode, relativesource={relativesource ancestortype=window}}" value="true"> <setter property="arrowbuttonwidth" value="30" /> </datatrigger> </style.triggers>

i found way set systemparameters cannot utilize in trigger, scrollbar changed , not when bool-value true:

<system:double x:key="{x:static systemparameters.horizontalscrollbarheightkey}">30</system:double> <system:double x:key="{x:static systemparameters.horizontalscrollbarbuttonwidthkey}">30</system:double> <system:double x:key="{x:static systemparameters.verticalscrollbarwidthkey}">30</system:double> <system:double x:key="{x:static systemparameters.verticalscrollbarbuttonheightkey}">30</system:double>

is there way without replacing entire command template of scrollbar?

you can leverage layouttransform accomplish same

so utilize scaletransform in layouttransform , done touch screen

eg

class="lang-xml prettyprint-override"><stackpanel orientation="horizontal"> <scrollbar margin="4" /> <scrollbar margin="4"> <scrollbar.layouttransform> <scaletransform scalex="2" scaley="2" /> </scrollbar.layouttransform> </scrollbar> </stackpanel>

result

you may perhaps utilize as

class="lang-xml prettyprint-override"> <style.triggers> <datatrigger binding="{binding datacontext.settings.touchscreenmode, relativesource={relativesource ancestortype=window}}" value="true"> <setter property="layouttransform"> <setter.value> <scaletransform scalex="2" scaley="2" /> </setter.value> </setter>> </datatrigger> </style.triggers>

c# wpf triggers

Recursion in Erlang functions -



Recursion in Erlang functions -

i'm having problem understanding piece of code:

{<<"block">>, els} -> jids = parse_blocklist_items(els, []), process_blocklist_block(luser, lserver, jids); #1 parse_blocklist_items([], jids) -> jids; #2 parse_blocklist_items([#xmlel{name = <<"item">>, attrs = attrs} | els], jids) -> case xml:get_attr(<<"jid">>, attrs) of {value, jid1} -> jid = jlib:jid_tolower(jlib:binary_to_jid(jid1)), parse_blocklist_items(els, [jid | jids]); false -> parse_blocklist_items(els, jids) end; #3 parse_blocklist_items([_ | els], jids) -> parse_blocklist_items(els, jids).

i'm not sure function getting called first.

els empty, means #3 gets called first, #2, , #3. right? why need function #3? difference #3 makes if #2 returns jid? i'm lost.

first of all, terminology: #1, #2 , #3 considered different clauses of same function.

this mutual way write recursive function. function transforms some, not all, of elements of input list else.

#1 base of operations case: if there no more input elements, homecoming accumulated output elements (jids).

in #2, first element of input list xmlel record name field <<"item">>. check jid attribute, , if has one, create jid , add together list. note we're doing using recursive call: phone call same function, first argument beingness remaining elements of input list, , sec argument beingness existing output list plus newly added element.

if first element of input list doesn't match pattern in #2, end in #3, skip on , maintain processing rest of list.

if els empty, mention in question, we'll end in clause #1, , won't nail code in #2 , #3.

clauses #2 , #3 similar in both "consume" element input list. difference clause #2 sometimes produces new element output list, while clause #3 never so. have been written single clause; it's question of style , preference.

erlang

c# - False "Sequence contains no elements" exception when using Single() -



c# - False "Sequence contains no elements" exception when using Single() -

i seem having issue false exception thrown when using .single() in linq statement. checking debugger found list contain element looking , id field matches. code throws exception

public actionresult details(int id = 0) { filterqueue filterqueue = db.filterqueues.single(f => f.filterqueueid == id); if (filterqueue == null) { homecoming httpnotfound(); } homecoming view(filterqueue); }

however, switching more verbose coding style works. this:

public actionresult details(int id = 0) { filterqueue filterqueue = null; foreach (var f in db.filterqueues) { if (f.filterqueueid == id) filterqueue = f; } if (filterqueue == null) { homecoming httpnotfound(); } homecoming view(filterqueue); }

funnily enough, if allow code run past exception, grab right item display details of.

now, of course, can switch single singleordefault , works fine; however, since first code block written automatically framework, want understand doing wrong. if making systematic mistake, right right way.

i think looking singleordefault().

in code, checking null, when null never result of single();

here's want:

public actionresult details(int id = 0) { filterqueue filterqueue = db.filterqueues.singleordefault(f => f.filterqueueid == id); if (filterqueue == null) { homecoming httpnotfound(); } homecoming view(filterqueue); }

c# linq asp.net-mvc-4

mysql - IN condition and equal condition in a select query return incorrect data -



mysql - IN condition and equal condition in a select query return incorrect data -

this query.

select * users 'imported' = 0 , (id in (select distinct(author_id) articles) or id in (select distinct(photographer_id) articles)) limit 20

i have 2 conditions in query.

'imported' = 0

and

(id in (select distinct(author_id) articles) or id in (select distinct(photographer_id) articles))

my problem info set returned contains rows imported = 1 don't want.

can 1 help me.

use backticks identifiers not single quotes

where `imported` = 0

mysql sql

c# - how to create asp.net voting system? -



c# - how to create asp.net voting system? -

i have been creating asp.net polling scheme .every thing ok there problem not why happen . illustration every time refresh page on item add together item list in buttonlist command . , every time take item show me 1 item (for illustration everi time show me terrible item). here code :

<asp:updatepanel id="updatepanel1" runat="server"> <contenttemplate> <asp:label id="lblresult" runat="server" text="label"></asp:label> <br /> <asp:radiobuttonlist id="radvote" runat="server" width="91px" datasourceid="linqdatasource1" datatextfield="id" datavaluefield="id"> <asp:listitem>perfect</asp:listitem> <asp:listitem>good</asp:listitem> <asp:listitem>bad</asp:listitem> <asp:listitem>terrible</asp:listitem> </asp:radiobuttonlist> <asp:linqdatasource id="linqdatasource1" runat="server" contexttypename="englishclass1.dataclasses1datacontext" entitytypename="" tablename="polls"> </asp:linqdatasource> <asp:button id="savebtn" runat="server" text="save" backcolor="#40e023" forecolor="blue" onclick="savebtn_click"/> <asp:button id="showbtn" runat="server" text="show" backcolor="#40e023" forecolor="blue" onclick="showbtn_click"/> &nbsp; <asp:label id="lblpoll" runat="server" text="" forecolor="red" font-italic="true" font-size="larger"></asp:label> </contenttemplate> </asp:updatepanel>

c# code :

protected void savebtn_click(object sender, eventargs e) { if (radvote.selecteditem == null) lblpoll.text = "لطفا در نظرسنجی شرکت کنید"; else countvote(radvote.selecteditem.tostring()); } protected void countvote(string thevote) { seek { string conn = configurationmanager.connectionstrings["englishdbconnectionstring"].tostring(); dataclasses1datacontext db = new dataclasses1datacontext(conn); poll po = new poll(); po.vote = thevote; db.polls.insertonsubmit(po); db.submitchanges(); lblpoll.text = "از حمایت شما متشکریم"; readxml(); } grab (exception) { lblpoll.text = "متاسفیم در حال حاضر نمیتوان انجام دهید بغدا انجام دهید"; } } private void readxml() { string conn = configurationmanager.connectionstrings["englishdbconnectionstring"].tostring(); dataclasses1datacontext db = new dataclasses1datacontext(); poll po = new poll(); var votes = vote in db.polls select vote; int acount; int bcount; int ccount; int dcount; acount = 0; bcount = 0; ccount = 0; dcount = 0; foreach (var vote in votes) { if (vote.vote == "perfect") acount++; if (vote.vote == "good") bcount++; if (vote.vote == "bad") ccount++; if (vote.vote == "terrible") dcount++; } double thetotal; thetotal = acount + bcount + ccount + dcount; double apercent; double bpercent; double cpercent; double dpercent; apercent = (acount / thetotal) * 100; bpercent = (bcount / thetotal) * 100; cpercent = (ccount / thetotal) * 100; dpercent = (dcount / thetotal) * 100; lblresult.visible = true; lblresult.text = "perfect:" + acount + "رای(" + apercent + "%).<br />"; lblresult.text = "good:" + acount + "رای(" + bpercent + "%).<br />"; lblresult.text = "bad:" + acount + "رای(" + cpercent + "%).<br />"; lblresult.text = "terrible:" + acount + "رای(" + dpercent + "%).<br />"; } protected void showbtn_click(object sender, eventargs e) { readxml(); }

every time select item, goes countvote() result lastly one:

lblresult.text = "perfect:" + acount + "رای(" + apercent + "%).<br />"; lblresult.text = "good:" + acount + "رای(" + bpercent + "%).<br />"; lblresult.text = "bad:" + acount + "رای(" + cpercent + "%).<br />"; lblresult.text = "terrible:" + acount + "رای(" + dpercent + "%).<br />";

you overwriting result lastly terrible one. need concatenate strings show all. utilize stringbuilder store result , lblresult.text= stringbuilder.tostring()

c# asp.net

parse.com - How can delete android ListView item please help So I've added a list item, and then I want to delete list item by position -



parse.com - How can delete android ListView item please help So I've added a list item, and then I want to delete list item by position -

how can delete android listview item, please help.

(http://i.stack.imgur.com/ybej8.jpg)

i'm parse.co study writing transfer know how delete text. i've added list item, , want delete list item position.

task task = mtasks.get(position);

task.deleteinbackground(new deletecallback() {

@override public void done(parseexception e) { if (e == null) { task.deleteeventually(); toast toast = toast.maketext(mcontext, "kısa süre içinde silinecektir.", toast.length_long); toast.show(); } else { toast toast = toast.maketext(mcontext, "silmede hata oluştu.", toast.length_long); toast.show(); } } });

parse.com

fortran - compiling and running a single OpenMP source file with several other non-OpenMP source files -



fortran - compiling and running a single OpenMP source file with several other non-OpenMP source files -

i'm trying compile multiple fortran source files, applied openmp directives 1 of source files. instance :

the compilation flags : compile00='ifort -o3 -openmp -openmp_report -fpconstant -fp-model precise -fpe0 -traceback -ftrapuv' compile0='ifort -o3 -fpconstant -fp-model precise -fpe0 -traceback -ftrapuv' the compiled files : $compile0 -c microprm.f90 modules.f90 $compile0 -c jernewf3p_a.f90 smax.f90 de_mott.f90 twoinitm.f90 helek03.f90 $compile00 -c helek04.f90 $compile0 -c jernewf3p_melt.f90 dmin_g.f90 $compile0 -c submelt_condevap.f90 linking : $compile00 -o tke.x *.o -lm

so source code helek04.f90 has openmp directives. beingness called submelt_condevap.f90 hasn't. right compilation practice ? how should compile using use omp_lib module ? code-safe compile 1 file openmp , link others openmp ?

the compilation aborted. when compiling $compile00 files, simulation runs, gets floating point exception, doesn't occur in serial code.

there couple of issues can arise. unfortunately description not detailed enough. recommend utilize -openmp files, don't see reason making distinction. intel fortran default not create code reentrant , if phone call subroutine has not been compiled -openmp parallel part race conditions can occur. during i/o operations problems quite likely. if have unusual reason avoid -openmp can seek -reentrancy threaded.

if there no calls other code parallel part, , not run concurrently non-parallel part, there shouldn't issues it.

it quite possible have race status or other threading problem in openmp code. utilize tools included in compiler collection debug them. intel inspector xe tool these kinds of problems. utilize options -warn -check -g -traceback have useful checks. valgrind can useful.

fortran openmp fortran90

php - Use array_multisort to arrange arrays by date -



php - Use array_multisort to arrange arrays by date -

i have built grouping of arrays trying sort 'start' date (hh:mm) using array_multisort. array looks this:

array ( [start] => 13:00 [end] => 14:00 [title] => event [day] => mon ) array ( [start] => 00:00 [end] => 06:00 [title] => event [day] => mon ) array ( [start] => 06:00 [end] => 13:00 [title] => event [day] => mon )

i order these 'start', should so:

array ( [start] => 00:00 [end] => 06:00 [title] => event [day] => mon ) array ( [start] => 06:00 [end] => 13:00 [title] => event [day] => mon ) array ( [start] => 13:00 [end] => 14:00 [title] => event [day] => mon )

i attempting using array_multisort. below finish code. have applied 'array_multisort' $monday, ignored. thought doing wrong?

foreach ($rows $row) { if ($row['day'] == 'monday') { $monday = array ( 'start' => $row['start_time'], 'end' => $row['end_time'], 'title' => get_the_title(), 'day' => $row['day'], ); } } array_multisort($monday, sort_asc); print_r($monday);

try this

function my_cmp($a, $b) { homecoming strcmp($a["start"], $b["start"]); } usort($monday, "my_cmp");

edit

you should want...

this make, except

$mondays = array(); foreach ($rows $row) { foreach ($row $day) { if ($row['day'] == 'monday') { $mondays[] = array( 'start' => $row['start_time'], 'end' => $row['end_time'], 'title' => get_the_title(), 'day' => $row['day'], ); } } } function cmp($a, $b) { homecoming strcmp($a["start"], $b["start"]); } usort($mondays, "cmp");

php arrays

sql - mySQL unique values -



sql - mySQL unique values -

i need unique values table. have single column comma separated keywords. need derive single list of keywords without duplicates. getting count of how each keyword present, too.

from have researched, unpivoting function unknown number of columns?

for example:

keywords

red, blue, yellow blue, orange, black, white brown, black, clear, pink blue, violet, orange

result

color | count

red 1 blue 3 yellow 1 orange 2 black 2 white 1 brown 1 clear 1 pink 1 violet 1

thank in advance!!

** far have tried adding explode_table type procedure, realized can't phone call dynamically view. have been experimenting performing reverse group_concat() on column. haven't been able produce code performs.

my version of echo_me's answer:

select substring_index(substring_index(skeywords, ',', n.n), ',', -1) value , count(*) counts tblpatternmetadata t cross bring together (select a.n + b.n * 10 + 1 n (select 0 n union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) a, (select 0 n union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) b order n ) n n.n <= 1 + (length(skeywords) - length(replace(skeywords, ',', ''))) grouping value

try that:

select substring_index(substring_index(t.keywords, ',', n.n), ',', -1) value , count(*) counts table1 t cross bring together ( select a.n + b.n * 10 + 1 n (select 0 n union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) ,(select 0 n union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) b order n ) n n.n <= 1 + (length(t.keywords) - length(replace(t.keywords, ',', ''))) grouping value

demo here

mysql sql count unique

android - GoogleApiClient never connected on sign out -



android - GoogleApiClient never connected on sign out -

i'm using google+ sign in on application, , followed reference such getting started , google+ sign-in android.

so situation following: have 1 loginactivity , mainactivity, both extend on baseactivity (so can share instance of googleapiclient, , necessary interfaces implementations) , when sign in, loginactivity following:

public void onconnected(bundle connectionhint) { super.onconnected(connectionhint); msigninclicked = false; launchmain(); } private void launchmain() { intent = new intent(this, mainactivity.class); startactivity(i); finish(); }

and mainactivity launch, great!

but when want sign out mainactivity following:

protected static googleapiclient mgoogleapiclient; public void signout() { if (mgoogleapiclient.isconnected()) { plus.accountapi.cleardefaultaccount(mgoogleapiclient); mgoogleapiclient.disconnect(); mgoogleapiclient.connect(); intent = new intent(getapplicationcontext(),loginactivity.class); i.setflags(intent.flag_activity_new_task| intent.flag_activity_clear_task); startactivity(i); } }

the mgoogleapiclient.isconnected() check false, , i'm never able disconnect.

besides i'm confused why should connect right after disconnect.

so i'll answering own question:

on baseactivity doing this:

protected void onstop() { super.onstop(); if (mgoogleapiclient.isconnected()) { mgoogleapiclient.disconnect(); } }

meaning when tried disconnect, disconnected. main thing here follow rules in this answer , in situation rule this:

implement in baseactivity, , have others extend that. connect/disconnect in each activity, code in 1 place.

android google-plus google-play-services

Get Data from Text File to Multidimensional Array Javascript -



Get Data from Text File to Multidimensional Array Javascript -

i have little bit of issue javascript function needs read info textfile (something js limited with) , process tha textfile info multidimensional array (another thing js doesn't nativelly suport).

with in mind, have text file in format:

1, name, data, serial 2, name, data, serial 3, name, data, serial

and on.

so, objective same info , set it, that, array.

i suppose that, i've been reading, need array of array, segmenting first 1 lines [/n] , sec 1 commas [,]. however, given "by-default" limitations, i'm confused @ point. suppose need jquery, however.

i tried this:

var fs = require('fs'); var array = fs.readfilesync('file.txt').tostring().split("\n"); for(i in array) { var array = fs.readfilesync('file.txt').tostring().split(","); for(f in array) { } }

with little success, because don't know how store it, objective beingness multidimensional array replicates format of text file, latter used search index or instance next user input results.

i appreciate help.

at first glance seems trying read in csv file. if indeed case recommend node-csv:

http://www.adaltas.com/projects/node-csv/

https://github.com/wdavidw/node-csv

javascript arrays node.js multidimensional-array text-files

performance - Speed up a oracle sql delete query -



performance - Speed up a oracle sql delete query -

this question has reply here:

delete left bring together in oracle 10g 3 answers

i wondering best alternative query query. (from aspect of performance)

delete cdr anum not in (select msisdn subs) or bnum not in (select msisdn subs)

also nice if can introduce multiple queries can work in same way. please consider anum , bnum can not null.

maybe one:

delete (select cdr.* cdr left outer bring together subs on a.msisdn = cdr.anum left outer bring together subs b on b.msisdn = cdr.bnum a.msisdn null or b.msisdn null);

or

delete cdr rowid <>all (select cdr.rowid cdr bring together subs on a.msisdn = cdr.anum bring together subs b on b.msisdn = cdr.bnum)

or

delete cdr not exists (select 'x' cdr bring together subs on a.msisdn = cdr.anum bring together subs b on b.msisdn = cdr.bnum)

the problem query on not exist, it's hard utilize index.

sql performance oracle query-optimization

ios - Parsing JSON using SBJSON, issue -



ios - Parsing JSON using SBJSON, issue -

i getting json response in predicted form. tree looks this:

{ "data":{ "img":"image":"http:\/\/testingpage.com\/images\/frog_320x480_23.jpg", "link":"http:\/\/google.com","verbose":"hi there"}, "figures":[ { "id":"16","type":"sailor","color":"1e90fffa","icon":"sailor"}, {"id":"32","type":"pilot","color":"32cd32bc","icon":"pilot"} ] } }

i using sbjson library. getting values with

nsstring *jsonstring = [[nsstring alloc] initwithdata:idata encoding:nsutf8stringencoding]; nsdictionary *results = [jsonstring jsonvalue];

and getting keys need with:

results objectforkey:@"keyname"]

so far good.

what happened getting response different provider , result different in it's nature:

[ { "tempvalues": { "temp1": 13.2, "temp2":11.1, "temp3":11.2, "temp4":13.4 }, "semipath":"pollution", "value":"axt" }, { "tempvalues": { "temp1":19.3, "temp2":12.1, "temp3":10.8, "temp4":13.1}, "semipath":"pollution", "value":"aut" } ]

i have 2 problems here:

i don't know how access these values in root, array. , array has no key can refer to. should approach kind of structure? if need temp1 of first object of tempvalues in array.

whenever seek value using results objectforkey:@"keyname"] sigabrt because results recognised array

you u have create similar this.

-(void) retrievedata{ nsmutableurlrequest *request=[nsmutableurlrequest requestwithurl:[nsurl urlwithstring:@"yoururl"]]; [request sethttpmethod:@"get"]; [request setvalue:@"application/json;charset=utf-8" forhttpheaderfield:@"tempvalues"]; nserror *err; nsurlresponse *response; nsdata *responsedata = [nsurlconnection sendsynchronousrequest:request returningresponse:&response error:&err]; nsarray *jsonarray = [nsjsonserialization jsonobjectwithdata:responsedata options: nsjsonreadingmutablecontainers error: &err]; variable=[[jsonarray objectatindex:0]objectforkey:@"keyname"]; }

ios objective-c json xcode

ruby - How to Pass object into filters method in rails -



ruby - How to Pass object into filters method in rails -

i want pass object filter , want alter object attributes using after_filter on create action . have product model having attributes name,title,price.once product has been added want set alter cost using after_filter how can pass created @product object filter method , alter cost .

class productscontroller < applicationcontroller before_action :set_product, only: [:show, :edit, :update, :destroy] after_action :change_price, only: [:create] //what should here..? # /products # /products.json def index @products = product.all end # /products/1 # /products/1.json def show end # /products/new def new @product = product.new end # /products/1/edit def edit end # post /products # post /products.json def create @product = product.new(product_params) respond_to |format| if @product.save format.html { redirect_to @product, notice: 'product created.' } format.json { render action: 'show', status: :created, location: @product } else format.html { render action: 'new' } format.json { render json: @product.errors, status: :unprocessable_entity } end end end .. //rest of code .. private # utilize callbacks share mutual setup or constraints between actions. def set_product @product = product.find(params[:id]) end # never trust parameters scary internet, allow white list through. def product_params params.require(:product).permit(:name, :category_id) end def change_name //what should here..? no status want alter every cost 10$ end end

you should utilize model callback after_create accomplish this

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

ruby - Rails app which connects users to telnet server -



ruby - Rails app which connects users to telnet server -

right there few mud clients date; graphically outdated , not user friendly.

i want create rails app users can login , connect different muds (aka telnet servers). know ruby has 'net/telnet' library not sure how works or how implement rails.

i unsure of how allow user interact , 4th telnet server. suggestions on how go doing this?

i able find one source on throughout internet, documentation poor , not suitable purposes. help appreciated, thanks!

adding:

require 'net/telnet'

is plenty utilize it. can follow documentation:

http://ruby-doc.org/stdlib-1.9.3/libdoc/net/telnet/rdoc/net/telnet.html#class-net::telnet-label-examples

to implement rails can create class in libs allows users stablish connection desired host:

class telnetclient require 'net/telnet' def self.new_connection(data_hash) net::telnet::new("host" => data_hash["host"], "timeout" => data_hash["timeout"], "prompt" => /[$%#>] \z/n) end end class connectionscontroller < applicationcontroller def new_connection $localhost = telnetclient.new_connection(connection_params) #whatever need end def interactive_shell $localhost.cmd(params[:string]) #other actions end private def connection_params params.require(:connection).permit(:host, :timeout) end end

and create nice interactive shell javascript in view allow users interact controller via ajax.

ruby-on-rails ruby telnet