Posts

Showing posts from May, 2015

R - XML of natural language corpus into dataframe -

i handling xml file in r using xml package. final goal create dataframe containing following information. luwpos luwdictionaryform luwlemma orthographictranscription phonetictranscription plainorthographictranscription devoiced moraid toneclass moraid 動詞 ダイスル 題する 題し ダイシ 題し 1 3 accent 1 luwpos, luwdictionaryform, luwlemma atts of luw node. orthographictranscription, phonetictranscriptio, plainorthographictranscription in suw, daughter of luw. devoiced in phone node, descendant of suw. moraid att of mora node, grandmother of phone. toneclass attribute of node xjtobilabeltone, descendant of phone. second moraid closest ancestor of xjtobilabeltone containing toneclass=accent. not phone nodes contain att devoiced. in case, don't need first moraid. when xjtobilabeltone not contain toneclass="accent", don't need second moraid either. so far, following: doc= xmlinternaltreeparse(file="a01f0122.xml") #opens file luw <- xpathsapply(doc, "//luw

c - Field ' ' could not be resolved -

currently trying compile kernel module in userspace. module is aes_generic.c so far commented kernel headers , started fixing compile errors u8 not available simpyl replaced uint8_t these errors gone now i struggling error field '' not resolved this error appears in various fields here's example: #define loop8(i) { \ loop8tophalf(i); \ t = ctx->key_enc[8 * + 4] ^ ls_box(t); \ ctx->key_enc[8 * + 12] = t; \ t ^= ctx->key_enc[8 * + 5]; \ ctx->key_enc[8 * + 13] = t; \ t ^= ctx->key_enc[8 * + 6]; \ ctx->key_enc[8 * + 14] = t; \ t ^= ctx->key_enc[8 * + 7]; \ ctx->key_enc[8 * + 15] = t; \ } while (0) error: field 'loop8(i)' not resolved more code same error message: int crypto_aes_expand_key(struct crypto_aes_ctx *ctx, const uint8_t *in_key, unsigned int key_len) { const __le32 *key = (const __le32 *)in_key; uint32_t i, t, u, v, w, j; if (key_

latex - Automatically launch a command with Emacs when it's a .tex file -

i want launch command when start emacs .tex file. command is: m-x flyspell-mode is possible , how? perhaps can add hook latex-mode . can add following line .emacs file. (add-hook 'latex-mode-hook 'flyspell-mode) i didn't test this, however, think should work. enable flyspell-mode whenever enter latex-mode .

python - Prioritizing Greenlet workers for parallel read/writes/db access -

i need read 3 csv files of size 10gb each , write parts of file 3 files. in middle, there minor conditions involved , mongo query(6bil collection, indexed) each row. i thinking using gevent pools task not sure how prioritize read tasks on writes,ensuring read finished before writers exit out. i dont want block writers until read finished. i can spawn 3 readers put in queue. i can spawn 20-25 io-processors read queue, mongodb call , write writer queue. i can spawn 3 writers read write queue , write files. i can joinall on pool. now can keep queue timeout in io-processors , writers. ensure of readers have put complete data in queue? or possible put join on readers @ end of io-processors? in short, want learn if there optimal approach use perform task efficiently.

ruby on rails - How can the value get updated in update_attribute -

i have test, needs set database-state: before site.first.update_attribute(:primary_domain, @params[:order][:primary_domain]) end but, reason, modifies @params: before @params[:order][:primary_domain].must_equal "example.com" site.first.update_attribute(:primary_domain, @params[:order][:primary_domain]) @params[:order][:primary_domain].must_equal "example.com" end this fails, second @params[:order][:primary_domain].must_equal "example.com" fails, updates @params[:order][:primary_domain] there. weird, have expected update_attribute(name, value) not touch value , somehow, does. it can circumvented .dup . interested cause this. maybe scope issue? fact normalising site.primary_domain on save , maybe? # override primary_domain setter. # allows normalise domain def primary_domain=(primary_domain) return primary_domain unless primary_domain.is_a?(string) write_attribute(:primary_domain, site.parse_uri(primary_domain.dup).host) end

search from json datasource through jsp and servlets -

how search json data source through jsp , servlets. sorry question being broad , not adhering stack overflow rules, yet kindly me if u can. web-links/ links of tutorials helpful. thank ! this blog json jsp & servlets. json-jsp-servlets and if looking particular search functionily json. use ajax , parse json response ajax , easy use , fast too.

javascript - JS drawing a line from the edge of a circle to another circle edge -

i'm trying draw line edges of 2 circles in html5 canvas. so, know coordinates of centers of 2 circles , radius. circles drawn randomly. line should move edge of 1 circle other. please help! p.s. sorry english :) update: i'm trying this, how know angle? from_line_x = circle1.x + circle1.radius * math.cos(math.pi * angle); from_line_y = circle1.y + cirlce1.radius * math.sin(math.pi * angle); to_line_x = circle2.x - circle2.radius * math.cos(math.pi * angle); to_line_y = circle2.y - circle2.radius * math.sin(math.pi * angle); update2: i think found how find angle. circle drawn randomly, line drawn not true. how should algorithm? sorry english again. here's solution achieve you've asked for. i've declared 3 'classes' make things clearer read. first, define generic shape class. next, define basic circle class. finally, define vec2 class. extend have done, , add other shapes inherit shape class - i.e square triangle, etc. i cr

c# - Antlr generated classes access modifier to internal -

i building library contains parsers. these parsers internally built antlr4. since generated classes public, users of library able see classes not need see. sandcastle documentation contains these classes. there way can tell antlr make generated classes internal instead of public? we have not implemented public/private on generated classes yet don't think.

matplotlib - Python: Return coordinate info on mouse click -

i display image in python , allow user click on specific pixel. want use x , y coordinates perform further calculations. so far, i've been using event picker: def onpick1(event): artist = event.artist if isinstance(artist, axesimage): mouseevent = event.mouseevent x = mouseevent.xdata y = mouseevent.ydata print x,y xaxis = frame.shape[1] yaxis = frame.shape[0] fig = plt.figure(figsize=(6,9)) ax = fig.add_subplot(111) line, = [ax.imshow(frame[::-1,:], cmap='jet', extent=(0,xaxis,0,yaxis), picker=5)] fig.canvas.mpl_connect('pick_event', onpick1) plt.show() now function onpick1() return x , y can use after plt.show() perform further calculations. any suggestions? a lesson gui programming go object oriented. problem right have asynchronous callback , want keep values. should consider packing together, like: class myclickableimage(object): def __init__(self,frame): self.x = none self.y

sqlite3 - sqlite boolean 't' and 'f' with rails active record -

i use mysql on production , sqlite3 on development. when querying database on development e.g. @follow_ups = followup.where(is_complete: false) i sql below in console select "follow_ups".* "follow_ups" "follow_ups"."is_complete" = 'f' sqlite evaluates 'f' truthy value no follow_ups.is_complete = false returned. in database stored true/false. investigations found. https://github.com/rails/rails/issues/10720 rails 3 sqlite3 boolean false what should boolean filters working? have thought happening more people. see schema below create_table "follow_ups", force: true |t| t.integer "contact_id" t.integer "owner_id" t.datetime "due_date" t.string "comment" t.boolean "is_complete", default: false t.integer "created_by_user_id" t.integer "updated_by_user_id" t.datetime "created_at"

java - Single Stateless Servlet in Spring Maven App -

i have 1 spring maven application, i want add new servlet, have added that, need servlet stateless, i.e. example, simple servlet souts hello, user needs login that, if user not logged in redirects login page offcourse due session validation, so question can exclude 1 particular servlet session check?? possible? if yes how? just add new servlet mapping url exclusion urls not need session validation. per question login.jsp must configured not require authentication token present in session, add new servlet url configuration

java - How to update a text file based on values within it -

i want edit values(a row values) of csv file based on specific value of row (an id). able read , write (append) values in cannot figure out how edit , delete them. here small fragment of code doing reading file , appending values: filewriter writer = new filewriter("file.csv", true); try { fileinputstream fstream = new fileinputstream("file.csv"); bufferedreader br = new bufferedreader(new inputstreamreader(fstream)); string strline; while ((strline = br.readline()) != null) { string[] fields = strline.split(","); if (fields[1].equals("value") { fields[1] = "different value"; } writer.append(fields); } catch(...) } but can't work out how write values same spot in file. unfortunately can't open single file both reading , writing @ same time. need read file , close before opening writing. the potential solutions are: write out

php - Register & Login password hashing method the same but not working -

i saw similar questions here don't think answers apply me, i'm sorry if do.. heres sniplet of code containing both procedures: note: the login , register works fine without hashing element. if (isset($_post['username']) && ($_post['password'])) { $username = trim($_post['username']); $username = strtolower($username); $password = trim($_post['password']); $salt = hash('md5', "$username"); $password = hash('sha256', "$password"."$salt"); $stmt = $dbh->prepare("select `id` `1_users` username=? , password=? limit 1"); $stmt->bindvalue(1, $username, pdo::param_str); $stmt->bindvalue(2, $password, pdo::param_str); $stmt->execute(); if ($stmt->rowcount()) { // match $results = $stmt->fetch(pdo::fetch_assoc); $_session['id'] = $results['id']; $_session['logged_in'] =

javascript - Posting data to PHP using AJAX -

i new ajax , javascript please forgive me if acting stupid trying pass variable routemid php page processing.php(preferable automatically 1 routemid has been calculated) tried out code breaks entire webpage. attached snippet ajax part having trouble , php code on next page appreciated. again in advance! <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script> <script type ="text/javascript" src="http://www.geocodezip.com/scripts/v3_epoly.js"></script> <script type="text/javascript"> var directiondisplay; var directionsservice = new google.maps.directionsservice(); var map; var polyline = null; var infowindow = new google.maps.infowindow(); var addresses = <?php echo json_encode($addresses); ?>; function createmarker(latlng, label, html) { var contentstring = '<b>'+label+'</b><br>'+html; var marker = ne

c# - Sending screenshots taking too much memory -

i trying make small application serve screenshot of entire screen through network. want able serve 1 every 1-2 seconds through lan. thought won't big problem, chose c# , nancy www self host (as easiest option). now, speed allright needs, seems taking way memory, , grows time. seems settle on taking 3.5 gb ram , no longer grows, that's not acceptable amount - big resolution (mine 2560x1440). is code bad, or nancy not suitable handling many big responses, or maybe c# method of capturing screen poorly optimized , should try pinvoke methods? or maybe it's terrible way , should try more advanced, using vnc library? currently code looks this: public class homemodule : nancymodule { private bitmap bitmapscreencapture; private graphics graphics; private object lockme = new object(); private memorystream memorystream = new memorystream(); public homemodule() { get["image"] = parameters => { lock (lockme)

c# - Stream to byte array conversion -

i have selected image stream , want convert byte. how can that? void photochoosertask_completed(object sender, photoresult e) { if (e.taskresult == taskresult.ok) { messagebox.show(e.chosenphoto.length.tostring()); var image = new bitmapimage(); image.setsource(e.chosenphoto); /// ???? //code display photo on page in image control named myimage. //system.windows.media.imaging.bitmapimage bmp = new system.windows.media.imaging.bitmapimage(); //bmp.setsource(e.chosenphoto); //myimage.source = bmp; } }

android - Emulator stops responding, tables not created -

the application starts , database created. application stops responding when table created. error message: table magazine has no column named key_m_name. here code helper: import com.example.projectdbms.model.magazine; import android.content.contentvalues; import android.content.context; import android.database.sqlite.sqlitedatabase; import android.database.sqlite.sqliteopenhelper; public class helper extends sqliteopenhelper { // logcat tag private static final string log = "helper"; // database version private static final int database_version = 1; // database name private static final string database_name = "magazine publishers db"; // table names private static final string table_magazine = "magazine"; private static final string table_article = "article"; private static final string table_editor = "editor"; private static final string table_author = "author"; pri

jquery not working after ajax post asp.net mvc4 -

here jquery function not working after jquery ajax call. here code ajax call <input type="button" value="comment" class="submitcomment" onclick="additem(this);" /> and <script type="text/javascript"> function additem(data) { postdata = $(data).parents().find("textarea"); var input = { "prdhierkey": postdata.parents().find('input[data-attr="prodkey"]').val(), "geohierkey": postdata.parents().find('input[data-attr="geokey"]').val(), "period": postdata.parents().find('input[data-attr="period"]').val(), "comment": postdata.val() }; $.ajax({ url: '@url.action("addcomments", "card")', type: "post", data: json.stringify(in

c# - How to make continuous WebJob? -

i create azure webjob shown in following script dequeues item azure storage queue, , stores azure table. process finished running within 1 or 2 seconds, runs few times in minute (and halted in approximately 10 minutes). overall, not work well. what missing? maybe i'm mixing trigger job , continuous job, hard find appropriate sample. class program { static void main(string[] args) { console.writeline("started @ {0}", datetime.now.tostring("s")); // continuous job should have infinite loop. while(true){ var host = new jobhost(); host.runandblock(); } } public static void processqueuemessage([queueinput("blogqueue")] string json) { var storageaccount = cloudstorageaccount.parse(configurationmanager.connectionstrings ["storageconnectionstring"].connectionstring); var tableclient = storageaccount.createcloudtableclient(); // store azur

java - What happens if a thread opens a socket and the main program exits? -

this question has answer here: termination of program on main thread exit? 2 answers what happens if thread opens socket , main program exits? have seen threads run second or 2 after main program exits, socket thread opened closed when main program exits, or when thread cleans dies? when program (ie. jvm process) stops, resources released. if there system.exit() call made, jvm stops. if on other hand, main thread finish execution, jvm continues run until there no more non-daemon threads running. if thread handles socket communication non-daemon thread, continue run.

jsp - How to pass a Map<ObjectA, List<ObjectB>> to action in Struts 2 -

i have event object, inside there map<objecta, list<objectb>> , objecta label, , list<objectb> table rows. following code, can display tables correctly, when submit form action class, map null inside event. jsp code: <s:iterator value="event.planmap" var="map" > <h4>plan type: <s:property value='key' /></h4> <table id="plan"> <s:iterator value="value" status="stat" var="detail" > <tr> <td><input type="text" id="name" name="event.planmap['%{#map.key}'][%{#stat.index}].name" value="<s:property value='name'/>"/></td> <td><input type="text" id="text" name="event.planmap['%{#map.key}'][%{#stat.index}].text" value="<s:property value='text'/>"/></td>

android - Should PreferenceCategories have keys? -

i have android app, in use preference s. grouped preferencecategory 's. my preferencecategory 's have keys ( android:key="setting" ), ones in official tutorial settings (which used myself learn & make mine). but recommended way of doing preferences, convention, or happen way in tutorial? don't have refer of categories in code, preferences inside, see no real reason have keys of them. but recommended way of doing preferences, convention, or happen way in tutorial? no, don't need set keys preferencecategories , if you're not doing them. you can add preferences preferencecategory accessing findpreference(your_preference_category_key) , calling addpreference(...) on it. since you're not doing don't need set key it.

sql server - SQL returning 'Subquery returned more than 1 value' error -

okay bit of code thats giving me error: select orderid, requireddate, ( select datediff(dd,requireddate,shippeddate) sales.orders shippeddate > requireddate ) 'dayslate' sales.orders and "subquery returned more 1 value. not permitted when subquery follows =, !=, <, <= , >, >= or when subquery used expression." error. i'm not quite sure how fix it, when click on error message highlights select orderid, requireddate bit. is there wrong i'm not catching? try below sql select orderid, requireddate , case when shippeddate > requireddate datediff(dd,requireddate,shippeddate) else 0 end 'dayslate' sales.orders the case..when statement can replace subquery

javascript - CSS column-count elements jumping across columns -

i'm trying dynamic amount of elements show across 5 elements using css3 column-count , when expand list item heights on hover, causes jumping (an element going next column). you can see behavior here i'm assuming it's because column-count uses height calculate item goes or something...how can have work intended? if try increase height of <ol> , become 4 columns or 3 columns because elements fill first column, start 2nd column, , on. in short, css3 columns not right solution trying do. (if understand correctly, want hovered element overflow parent container going outside box. however, css3 columns designed such overflow continue @ top of next column, , there's no way i'm aware of change behavior). i recommend using different approach achieve ui you're after, such using jquery insert wrappers around each column. however, if you're set on using column-count, may able hack doing this: jsfiddle: http://jsfiddle.net/p6r9p/ css

ios7 - Getting iCloud account details -

i want know icloud account configured ios device, there api icloud account details in ios 7? thanks no. have no access account details. can is find out if icloud configured calling [nsfilemanager ubiquityidentitytoken] find out if account has changed calling method again see if value has changed or observing nsubiquityidentitydidchangenotification . you not find out user's account name or other details account. none of relevant using icloud.

Auto Versioning with Git in Visual C++ -

i have c++ project in vs2013. in past on similar projects i've used subwcrev subversion auto generate version numbers. had template file : #define major_version 2 #define minor_version 2 #define micro_version 0 #define build_version $wcmods?$wcrev$+1:$wcrev$$ #define quote_(x) #x #define quote(x) quote_(x) #define build_version_string quote(major_version.minor_version.micro_version.build_version) then ran subwcrev pre-build step generate header file included in project define version numbers. i'm using git , want similar. know git doesn't have equivalent of revision number head sha fine. it doesn't seem there's equivalent way git , need scripting isn't strong point. git guru point me in right direction achieve this? i've found useful batch file way more need : https://github.com/thell/git-vs-versioninfo-gen it similar job subwcrev , generates header file can include in vs project set version strings. afte

How to retain the data in ListView without using Database in VB6 -

is possible retain data listed in listview without using database ? using vb6 , want retain data listed in listview if users re-open program. if possible, how can that? you don't have use database store data outside of application. the best way store in simple text file. use built-in vb file access statements - write # save file, , input # load data in. you use msxml library persist xml, although overkill. if small amounts of data, store in registry using savesetting / getsetting functions.

GTK/Glade text entry string to global variable in C -

i creating menu gui game using glade , gtk in c. have text entry box , button. when button pressed, value inside text entry needs saved global variable. don't know how value inside text entry i'm bit stuck. great. function void on_okbutton_clicked (gtkbutton *object, gpointer user_data) { //??????? } edit: this current code looks like #include <stdio.h> #include <gtk/gtk.h> #include <python2.7/python.h> void on_window1_destroy (gtkobject *object, gpointer user_data) { gtk_main_quit(); } void on_okbutton_clicked (gtkbutton *object, gpointer user_data) { gchar *entry_value;//this can global variable, too, of course entry_value = gtk_entry_get_text(//get text function gtk_entry(//use gtk_entry widget (gtkwidget *) user_data //cast gtkwidget pointer ) ); } int main(int argc, char *argv[]) { gtkbuilder *gtkbuilder; gtkwidget *window; gtkwidget *quit; gtkwidget *ok; gtkwidget *entry = gtk_entry_new(); gtk_

How to manually override CSS @media queries? -

i have made mobile optimised style sheet site client using: <link rel="stylesheet" type="text/css" media="screen , (max-device-width : 768px)" href="css/mobile.css" /> this works fine have requested link show site original, full page format. does know way re-load site , override media query above? way javascript? personally favour solution whereby stylesheet link conditionally rendered via logic in code behind of page triggered user selection. it's not clean, possibly achieve using javascript too. maybe along lines of giving stylesheet link id: <link id="mobilestyles" rel="stylesheet" type="text/css" media="screen , (max-device-width : 768px)" href="css/mobile.css" /> then calling function disable stylesheet button event handler: jquery $("#mobilestyles").remove(); plain js document.mobilestyles[0].disabled = true; you store user'

php - Codeigniter add new item to current session userdata array -

so have array: $data = array( 'item_1' => $this->input->post('item_1'), 'item_2' => $this->input->post('item_2'), 'item_3' => $this->input->post('item_3') ); $this->session->set_userdata( 'items', $data ); and want add new item array, updated array of userdata this: $data = array( 'item_1' => $this->input->post('item_1'), 'item_2' => $this->input->post('item_2'), 'item_3' => $this->input->post('item_3'), 'item_4' => $this->input->post('item_4') ); $this->session->set_userdata( 'items', $data ); how that, thank you follow these steps add data current session: $data = $this->session->userdata('items'); $data['item_4'] = $this->input->post('item_4'); $this->session->set_userdata(

jquery - Android stock browser on Xperia Z does not render html correctly -

i have html page displayed correctly in devices , browser except stock android browser in xperia z. on particular device running android 4.2.2, using jquery v1.7.2, , using $('div').slideup , $('div').slidedown methods only, , results in text distortion (it in english, suppose not related specific font), text appears horizontal lines appear fraction of second while sliding up/ down. i have tried turning debug mode on about:debug in stock browser, , javascript console shows no error/ warning messages. i tried changing user agent string iphone, , surprise, text rendered expected. i have searched similar issue, , came across android stock browser crashing , points jquery bug slideup/ slidedown have problems in android stock browser (please note jquery , android versions different in reported bug). my questions are: is known issue? has faced similar problem before? is there workaround resolve it? i'd appreciate if point me in right direction.

AngularJS ui-router initial route -

i have page contains 2 different sub-pages. the search state main container , search.list automatically when loads. when user navigates search.detail invoke last route till contained within search main frame. problem can't search.list load default. $stateprovider.state('search', { url: '/search/{appid}{reportid:(?:/[^/]+)?}', templateurl: 'app/search/search.tpl.html', controller: 'searchctrl', resolve: { app: function($stateparams, appsmodel) { return appsmodel.findone($stateparams.appid); } } }); $stateprovider.state('search.list', angularamd.route({ controller: 'listctrl', templateurl: 'app/search/list/list.tpl.html' })); $stateprovider.state('search.detail', { url: '/detail/{recordid}', title: "search", views:{ '': {

ios - CocoaPods spec fails even when problems are fixed -

recently i've released networking wrapper cocoapods. since have released few versions , of them released without problem. when try validate .podspecs file fails following errors: -> jbmessage (1.0.6) - error | [xcodebuild] jbmessage/jbmessage/jbmessage/jbmessage.m:237:39: error: incompatible block pointer types sending 'void (^)(nsuinteger, nsinteger, nsinteger)' parameter of type 'void (^)(nsuinteger, long long, long long)' - note | [xcodebuild] afnetworking/afnetworking/afurlconnectionoperation.h:262:133: note: passing argument parameter 'block' here - error | [xcodebuild] jbmessage/jbmessage/jbmessage/jbmessage.m:244:41: error: incompatible block pointer types sending 'void (^)(nsuinteger, nsinteger, nsinteger)' parameter of type 'void (^)(nsuinteger, long long, long long)' - note | [xcodebuild] afnetworking/afnetworking/afurlconnectionoperation.h:269:128: note: passing argument parameter 'block' her

how to add an on keyup function with jquery -

i need add onkeyup function input field cannot edit. field looks this. <input id="billing_addr_zipname" type="text" maxlength="50" value="" name="billing_addr_zipname"> i need add ... onkeyup="return addresscountedit(this,'spaneditaddress', event)" ... id using jquery. anyone know how that? basic jquery: $("#billing_addr_zipname").keyup(function() { //do stuff });

button - VBA get list of files from file browse window -

i have following code not able list of files (when selecting multiple files) browse window, have started playing around vb please excuse obvious mistakes. private sub cmdbrowse_click() dim success boolean success = browsefiles(me.txtfile) end sub public function browsefiles(tbx textbox) boolean dim filedlg office.filedialog dim thefile variant ' clear textbox contents. tbx.value = "" ' instantiate file dialog. set filedlg = application.filedialog(msofiledialogfilepicker) filedlg ' set title of dialog box. ' .title = "please select 1 or more files" ' clear filters , add ones want.' .filters.clear '.filters.add "access databases", "*.accdb" '.filters.add "access projects", "*.adp" '.filters.add "text files", "*.txt" '.filters.add "csv files", "*

c - cmd.exe parsing bug leads to other exploits? -

before continue, please note rather lengthy infosec notice windows command prompt have found bug might exploitable using simple batch files. bug prevalent in versions of windows 2000 , works on 64 , 32-bit machines, , being it's batch file parsing bug, requires no additional software install ( cmd.exe default part of windows) , can initiated user level of privilege (assuming can run cmd.exe , parse batch files). included in summary assembly of bug happens (with breakdown of code flow show why). isn't rce level bug (not i've been able find yet), dos type , require user run (or have startup item), given simplicity of , ubiquity of windows systems, figured deserved second look. please note i'm not responsible if run of these bug enabling batch files , crash system (task manager , kill pid works on runaway script in case run them). tldr : batch file line ^ nul<^ cause massive memory leak, while batch file line ^|^ causes command prompt crash due 'infinite r