Posts

Showing posts from January, 2015

eclipse - How to access controls(views)in tabs from another one in android? -

Image
i'm working on application in eclipse have 5 tab , have spent time have big problem : when 1 of tabs activated next tab , prev tab loading , oncreated() method called don't need need calling oncreated() method when switching tabs this project files mainactivity.java package info.androidhive.tabsswipe; import info.androidhive.tabsswipe.adapter.tabspageradapter; import ir.zinoo.mankan.r; import android.app.actionbar; import android.app.actionbar.tab; import android.app.fragmenttransaction; import android.graphics.color; import android.graphics.drawable.colordrawable; import android.view.menu; import android.view.menuitem; import android.widget.toast; import android.os.bundle; import android.support.v4.app.fragmentactivity; import android.support.v4.view.viewpager; import android.content.sharedpreferences; public class mainactivity extends fragmentactivity implements actionbar.tablistener { private viewpager viewpager; private tabspageradapter

android - How can i design a "family tree" -like UI? -

Image
i want create dynamic interactive tree structure shown in image? all found can done using fragments can show me how implement top 2 nodes links using fragments? rest try make myself , upload answer. have horizontal linearlayout each row , put each row in vertical linearlayout. create 1 view base each image , text included , use ´include´ use base view each image\text. if use id each included view can grab each id , configure them separately in java if needed.

ios - Have string represent integer value - Obj C -

i have situation there either 4 options or less. options a,b,c,d (or a,c or a,c,d...ect). , each option associated integer value 0 - 4000. , if 4 options a,b,c,d available want represent 0-999, b represent 1000-1999...ect. if options a,c,d want = 0-999, c = 1000-2999 & d = 3000-4000, , on different types of options, can input values depending on options available (not spilt evenly). bunch of if statements seems impractical. if (a & b & c & d) { = 0-999; b = 1000-1999; ... } else if(a & c & d) { ... } //and on , on lot of combinations there must better way set up, , more efficient bunch of if statements, how go doing this? thanks in advance. keep options in array, nsarray *options=@[@"a",@"b",@"c"]; int i=-1; (nsstring *s in options) { // assign options value i++; // s = i+999 stuff assign value option. i=i+999; } if want do.

php - Laraver FindOrNew with multiple parameters -

i'm using laravel findornew() entry 2 parameters, or create new one: $option = \app\option::findornew(['user_id' => $this->id , 'option_name' => $optionname]); i want option user has name in $optionname. problem checks user_id, , not create new 1 when option_name not exist.. instead "finds" 1 not match $optionname value.. can i'm doing wrong? how can achieve this? tl;dr: you're using wrong method. you're looking firstornew() method, not findornew() . explanation: the findornew() extension of find() method, works on ids only. takes 2 parameters, first being id (or array of ids) find, , second being columns retrieve. it's treating array you've passed in array of ids find. the firstornew() method takes 1 parameter: array of attributes search for. turn array clause, , call first() on query builder. if no results returned, returns new instance attributes filled in.

Non-Blocking raw_input() in python -

after digging around in while, still haven't found answer hope common need. need main thread "stuff" until receives input , act on input, return original "stuff". problem every time seems program execution seems halt @ raw input, whether call in thread or anywhere else. forwarning i'm pretty novice python, i'd hope shouldn't nasty implement. here i'm playing (pulled other question threading question answered handily) so i'm trying write program looks keyboard presses , in main program based upon user inputs. i'm trying run keyboard listening in thread , compare whats in variable in main loop, don't ever seem getting threaded keyboard input. in below code, print maybe updating line never happens, else block main while loop. need main loop aware of keys pressed user? import threading import time kbdinput = '' playingid = '' def kbdlistener(): global kbdinput kbdinput = rawinput() print "maybe u

android - Open file manage and get selected file -

using delphi xe 8 , building android app, can browse files in device opening file manager app installed on device , selected file name , path ? you can use jfiledialog check below link http://bluexmas.tistory.com/427

vb.net - .NET Framework compatibility issue -

we have 1 vb.net winform application built against .net framework 1.1 uses referenced assemblies (class library) .net 1.1 gac location , works fine. but later have migrated referenced assembly files .net 4.0 , deployed locally in application executable's folder. so manifest file of main application in .net 1.1 has referenced assemblies in .net framewok 4.0 and application works if have .net framework 1.1 installed on client machine , if remove .net framewok 1.1 application crashes while getting data referenced assemblies. client machine has .net framewok 4.0 installed , .net runtime supports backward compatibility why application crashes after removing .net 1.1 framework. please shed light on issue. thanks. first of all, .net backward compatibility not guarantee correct behavior. means later version of runtime (4.0) can run assembly of earlier version (1.1). since correct behavior not guaranteed, 4.0 runtime not implicitly run assemblies built earlier version

How to update my android app -

i sure simple answer but: i want update android app on play market. if upload new .apk same keystore , package name play store automatically inform user of new update or there need types of notifications? in manifest, need change build number. if don't, rejected anyway play store.

android - LibGdx Camera starts from mid screen -

i using libgdx game development. new this. have setup camera public void create() { camera = new orthographiccamera(game.screen_width, game.screen_height); } i drawing background have shown below. public void render(spritebatch sb) { sb.draw(background, 0, 0,1080,1920); sb.draw(background,0,1920,1080,1920); sb.draw(background,0,3840,1080,1920); } with setup getting screen image starts width/2,height/2 instead of (0,0). please let me know code needs correction.

ember.js - Ember-cli server does not start, no error message -

i'm unsure why ember not start. when type ember server , see ps c:\users\lzc\ember-prototype> ember s version: 0.2.3 new version of ember-cli available (0.2.7). install it, type ember update. livereload server on port 35729 serving on http://localhost:4200/ ps c:\users\lzc\ember-prototype> i'm pretty sure not outdated cli, because working pas week. when type ember build , instantly reads 'building...` finishes. builds 60 80 seconds. can't identify whether compile issue or settings flaw. shouldn't ember-cli give error message if went wrong this? has experienced before? can't run `--verbose', no command in cli. issue when liquid modal tried register transitions, 1 of path strings incorrect. no error messages given.

symfony - display the name but insert the id whit entity field type -

the form entity services namespace main\homebundle\form; use symfony\component\form\abstracttype; use symfony\component\form\formbuilderinterface; use symfony\component\optionsresolver\optionsresolverinterface; class servicestype extends abstracttype { /** * @param formbuilderinterface $builder * @param array $options */ public function buildform(formbuilderinterface $builder, array $options) { $builder ->add('techid', 'entity', array( 'class' => 'mainhomebundle:technical', 'property' => 'id', )) ->add('status', 'choice', array( 'choices' => array( 'pending' => 'pending', 'finished' => 'finished',

VBA/Excel Application-defined or object-defined error -

getting application-defined or object-defined error in excel vba macro , i'm not sure why. i'm guessing has how calling cell reference. i've looked @ of other similar questions this. similar, missing mistake is. here's code: set alliancesheet = worksheets(2) dim yearbeginrange range dim yearendrange range dim year integer dim beginrow long dim endrow long dim countryrange range 'dim ws worksheet 'dim wsname string year = 1965 'wsname = "ally-" & year set yearbeginrange = alliancesheet.range("c1", alliancesheet.range("c1").end(xldown)).find(what:=year, after:=alliancesheet.range("c1"), lookin:=xlformulas, _ lookat:=xlwhole, searchorder:=xlbyrows, searchdirection:=xlnext, _ matchcase:=false, searchformat:=false) if yearbeginrange nothing msgbox year & "begin year not found" else 'msgbox year & "begin year found!" 'debu

excel - VBA Importing multiple XML children under a single parent node -

i'm trying import data xml response excel sheet , having difficulty repeated child nodes under single parent node. need able import categoryid, categoryname, , categoryparentname lines each category. i've been able first 2 cant figure out categoryparentname since repeated. xml follows. <getsuggestedcategoriesresponse xmlns="urn:ebay:apis:eblbasecomponents"> <timestamp>2010-01-19t22:08:02.568z</timestamp> <ack>success</ack> <version>647</version> <build>e647_core_bundled_10438248_r1</build> <suggestedcategoryarray> <suggestedcategory> <category> <categoryid>18871</categoryid> <categoryname>memory cards</categoryname> <categoryparentid>625</categoryparentid> <categoryparentid>3327</categoryparentid> <categoryparentid>18866</categoryparentid> <categ

ipython - Jupyter notebook with bibtex citations -

i have .ipynb file containing markdown text. have bibtex file called library.bib references. wish cite 1 of these references in markdown cell. i've found information on how render when nbconvert, how can have references in browser window in raw ipynb format? have @ https://github.com/takluyver/cite2c witch notebook extension.

c# - Unity WaitForSeconds stuck -

i tried create simple splashscreen. @ first waitforseconds working, after few week code doesn't want work. tried using debug.log "before wait" , "after wait" doesn't appear after 5 minutes. using unity 4.5, why happen? void start () { guitexture.pixelinset = new rect (0, 0, screen.width, screen.height); startcoroutine (loadnextscene ()); } ienumerator loadnextscene(){ debug.log ("before wait"); yield return new waitforseconds (delaytime); debug.log ("after wait"); if (nextlevel != "") { application .loadlevel (nextlevel ); } } your code perfect. means 1 of 2 things: delaytime excessively large (debug out) or, more likely: the gameobject destroyed coroutine nolonger running. try this: void start () { guitexture.pixelinset = new rect (0, 0, screen.width, screen.height); startcoroutine (loadnextscene ()); } ienumerator loadnextscene(){ debug

Python: returning an instance of derived class from a base class method -

assume following situation. there base class holding data , derived class assumes data has additional characteristic allows running algorithm . base class has algorithm processes data in generic way , returns copy result of processing. now, processing not affect specific characteristic of data , therefore can safely assume returned value should of type of derived class. my current implementation: class genericdata: def __init__(self, d): self._d = d def process(self): # process data in way compatible # specialization. then, return instance # of specific derived class. return type(self)(some_processing(self._d)) class specificdata(genericdata): """this class gathering of algorithms make assumptions d.""" def __init__(self, d): super().__init__(d) def algorithm(): # stuff assuming characteristic of data pass my question is: good/pythonic way of handlin

html - Font Awesome icons not rendering when I use PHP echo? -

i'm trying set menu list pulls array mysql query , uses foreach echo out each list element. i'm using font awesome , , reason when place <i> elements inside of echo line, icons not render. other icons on same page rendering fine. i've verified of css files being included properly. here block of code, can see generating icon names using str_replace() , there other icons in echo static. i'm pulling hair out here. $result = mysqli_query($con,"select * outageupdates order timestamp"); while($row = mysqli_fetch_array($result)) { $time = strtotime($row[timestamp]); $time = date("h:i", $time); $icon = str_replace("internal", "fa-user", $row[type]); $icon = str_replace("external", "fa-user-times", $row[type]); echo '<li><a href="outageupdates.php"><i class="fa ' . $icon . '"></i>' . $row[agentname] . ' - ' . $row[

Call Perl script from Thunderbird Javascript -

i wrote perl script handles data automatically. however, face problem when try call script thunderbird extension naturally written in javascript. var file = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsilocalfile); file.initwithpath("/usr/bin/perl"); // create nsiprocess var process = components.classes["@mozilla.org/process/util;1"] .createinstance(components.interfaces.nsiprocess); process.init(file); // run process. // if first param true, calling thread blocked until // called process terminates. // params used pass command-line arguments // process var args = ["package/myperlscript.pl", "some arguments]; process.run(true, args, args.length); i guess have perl script placed @ wrong location. tried various ones, not work. if major mistake, base path javascript file expects?

Can tkinter button click not issue a leave event? -

i use tkinter leave event tell when mouse hovers away button, fine, clicking button issues leave event though mouse still hovering on button. can configure button not issue leave event when clicking button? alternatively, can leave event handler check know mouse still on button? sample code showing clicking button undesirably runs leave event: #!/usr/bin/env python3 tkinter import * def handle_click(e): print("click") def handle_leave(e): print("leave") root = tk() b = button(root, text="button") b.pack() b.bind('<button-1>', handle_click) b.bind('<leave>', handle_leave) root.mainloop()

amazon web services - Why is this python boto S3 multipart upload code not working? -

i trying upload 10 gb file aws s3, , said use s3 multipart upload, stumbled upon someone's github gist: import os import sys import glob import subprocess import contextlib import functools import multiprocessing multiprocessing.pool import imapiterator optparse import optionparser boto.s3.connection import s3connection #import rfc822 import boto aws_access_key_id = 'key id here' aws_secret_access_key = 'access key here' def main(transfer_file, bucket_name, s3_key_name=none, use_rr=true, make_public=true, cores=none): if s3_key_name none: s3_key_name = os.path.basename(transfer_file) conn = s3connection(aws_access_key_id, aws_secret_access_key) bucket = conn.lookup(bucket_name) if bucket none: bucket = conn.create_bucket(bucket_name) mb_size = os.path.getsize(transfer_file) / 1e6 if mb_size < 10: _standard_transfer(bucket, s3_key_name, transfer_file, use_rr) else: _multipart_upload(b

BigInteger memory leak causes stack overflow in Java -

i trying write optimized fibonacci assignment able compute fib(300) , fib(8000). here have far (map hashmap). public static biginteger fibmemo(int n) { if (n <= 1){ return biginteger.valueof(n); } if (!map.containskey(n)){ map.put(n, fibmemo(n-1).add(fibmemo(n-2))); } return map.get(n); } when call system.out.println("300: " + fibonaccimemo.fibmemo(300)); on own, works fine. also, system.out.println("8000: " + fibonaccimemo.fibmemo(8000)); works fine if comment out previous call fib(300). if keep both calls stack overflow on recursive fibmemo. seems strange me. please clarify situation? in advance. here code: import java.util.hashmap; // import java's hashmap can use import java.math.biginteger; public class fibonaccimemo { private static hashmap<integer, biginteger> map = new hashmap<integer, biginteger>(); /** * classic recursive implementation no memoization. don

html - Controlling container width based on content of one of the objects -

Image
i think fluke, works on chrome. how can chrome across browsers? ideally container width set chinese text , possibly pinyin, rubydef wraps. jsfiddle: http://jsfiddle.net/tofutim/a10xm9s5/ <style> #container { border: 1px solid #f00; margin: 0px; display:inline-block; display: table; } .text { margin: 0px; display: table-row; width:auto; font-size:36pt; line-height:115%; background: #ffcccc; } .pinyin { margin: 0px; display: table-cell; width: 1px; text-align: center; background: #ccccff; } .rubydef { margin: 0px; display: table-cell; width: 1px; text-align: center; font-style: italic; background: #ccffcc; } </style> <p> <div id='container'> <div class='pinyin'>tái bāo</div> <div class='text'>台胞</div> <div class='rubydef'>tomato fruit wish eat week</div> </div> i think thing miss

WKHTMLTOPDF - Allow page break in table row -

i'm running wkhtmltopdf 0.12.2.1 (with patched qt) on ubuntu server , can generate pdfs fine. i've been using wkhtmltopdf generate table several columns , 1 of columns has lot of text. my problem this: want table rows able span multiple pages without leaving white space before/after row. wkhtmltopdf of work me, leaves unwanted white space before row if row has lots of text because wkthmltopdf tries keep entire row on 1 page. for example, page might half way full of table when wkhtmltopdf encounters row take 3/4 of page 1 row. wkthmltopdf leaves bottom half of first page empty , starts long row on next page. i'd have happen that wkhtmltopdf starts long row on first page, , finishes long row on next page. how can this? i've thought using divs , spans, need table borders still show up, seems using table best option. advice? after thinking on issue, seems best thing change format of report use divs , spans rather use table. i've gone ahead , done ,

security - oauth: Open access to anyone with the Access token -

i setting oauth2 web application. imagine case, entity abc authenticated , received access token web application. is necessary ensure subsequent requests containing access token entity abc indeed coming in entity abc having validation fields abc aware of. or, should grant access access token no matter are, believing has access token indeed entity abc? it's responsibility secure access token transmission entity abc if you're using bearer scheme authentication, grant access in possession of valid access token. no additional info required. see also: http://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html

Getting error while running query on hive over tez -

getting error while running query on hive on tez. per logs, hive failing while copying tez jars hdfs location on start of tez session .below complete log obtained hive log file : 2015-06-19 01:23:52,289 info [hiveserver2-background-pool: thread-41]: ql.driver (sessionstate.java:printinfo(852)) - query id = saurabh_20150619012323_f52f1d6c-2adb-4edc-8ba4-b64d7d898325 2015-06-19 01:23:52,289 info [hiveserver2-background-pool: thread-41]: ql.driver (sessionstate.java:printinfo(852)) - total jobs = 1 2015-06-19 01:23:52,289 info [hiveserver2-background-pool: thread-41]: log.perflogger (perflogger.java:perflogend(148)) - </perflog method=timetosubmit start=1434657232288 end=1434657232289 duration=1 from=org.apache.hadoop.hive.ql.driver> 2015-06-19 01:23:52,290 info [hiveserver2-background-pool: thread-41]: log.perflogger (perflogger.java:perflogbegin(121)) - <perflog method=runtasks from=org.apache.hadoop.hive.ql.driver> 2015-06-19 01:23:52,290 info [hiveserver2-ba

r - Add legend category to ggplot2 line plot with two y-axes -

i'm trying make graph using ggplot2 2 different y-axes (appropriate , not misleading, promise). i've got legend first graph, can't seem able add 1 second. nor can label axis. my code quite long-winded i've abbreviated coding of p1 don't think need change that. p1 <- p + theme(legend.position = "top") p2 <- ggplot(concb.only.for.r, aes(concb.ml, concb)) geom_line(colour = "#000099") + theme_bw() + theme(panel.background = element_rect(fill = na)) + theme(legend.position = "top") g1 <- ggplot_gtable(ggplot_build(p1)) g2 <- ggplot_gtable(ggplot_build(p2)) pp <- c(subset(g1$layout, name == "panel", se = t:r)) g <- gtable_add_grob(g1, g2$grobs[[which(g2$layout$name == "panel")]], pp$t, + pp$l, pp$b, pp$l) ia <- which(g2$layout$name == "axis-l") ga <- g2$grobs[[ia]] ax <- ga$children[[2]] ax$widths &

iboutletcollection - Swift outlet collection - 'IBOutlet' property cannot be an array of non-'@objc' class type -

i'm trying setup outlet collection in swift. problem getting following error : 'iboutlet' property cannot array of non-'@objc' class type '[badge]' here code : import uikit class badgemodulecell: uitableviewcell { @iboutlet var badges: [badge]! } is there doing wrong ? seems same in apple documentation ( here ). i figured out going wrong. had class called "badge" custom uiview. fine. renamed "badgeview" allow me declare new class called "badge" scratched. here outlet collection supposed contain object not outlet, has no sense. renamed @iboutlet var badges: [badge]! @iboutlet var badges: [badgeview]! , working now.

Going to source of a method in ASP classic -

in vs 2013 have opened asp classic project , example here source code it: case "wsf_last" call lastname() i have clicked f12 on method name , goes source code of method have never seen or worked on asp classic project , nothing when f12 it. if search-all on lastname() other thing find this: <%sub lastname()%> <tr> <td width="1%" align="right" class="inputboxeslabel" nowrap> last/inst name&nbsp;&nbsp;</td> <td width="99%"><input type="text" name="physicianname" size="20" maxlength="35" value="<%=pn%>"></td> </tr> <%end sub so code coming from? you've found it... right there subroutine definition. it's not recommend

Counting factor observation via aggregate in R -

my vector name s1 s1 s1 s2 s2 s3 i need count number of occurrences of each value. expected output this names no. s1 3 s2 2 s3 1 i using aggregate function aggregate(case2$name,by=list(names =case2$name),table) it gives me correct result in diagnol matrix form instead of vector in expected output. if try aggregate function count, here aggregate(case2$name,by=list(names =case2$name),count) it gives me error error in usemethod("group_by_") : no applicable method 'group_by_' applied object of class "factor" not sure shall that? agreed table(name) straight forward approach reference correct syntax using aggregate same result is: aggregate(name, by=list(name), length)

Batch file runs on local desktop but not on file server -

i new .bat files have been working on process 2 days. simple , works fine on desktop (thanks code snippet found on internet), when try run through shared drive on our file server, processing not occur. @echo off rem batch file process daily flat file , replace " empty space upload access/sql server ren c:\users\desktop\filejuly17.txt filequotes.txt /f "tokens=* delims= " %%a in (c:\users\desktop\filequotes.txt) ( set s=%%a set s=!s:"=! >> c:\users\desktop\finalfile.txt echo.!s! ) i have had switch ren copy on file server, have verified can copy 1 file using process. assured have path correctly. however, no matter options have tried, unable have batch file strip out double quotes randomly in file user entry. need strip these out , replace them empty spaces in order have data migration process load flat file our database. thank guidance. if helps, laptop running on windows 7, server remote connect running on windows server 2008.

How do I use eclipse spring IDE to create a Spring boot application that runs on wildfly? -

i have eclipse setup use either wildfly or tomcat, when create new spring-boot application, defaults tomcat, how can change this? also, there other settings i'll have modify? everytime configure spring core jsf on wildfly there bunch of erros have deal with. don't wildfly @ have use new job. be sure have installed jboss tools plugin eclipse marketplace. go right click on project > debug (or run as) > run on server > manually define new server > choose wildfly > download , install runtime > select desired version (i.e. wildfly 8.0). wait until wildfly downloads. next, next... finish.. , application should start on wildfly server.

android - ImageView giving glib error -

Image
when try launch image_view window display shows , freezes . the terminal output follows : (image_view:29293): glib-gobject-warning **: invalid uninstantiatable type '(null)' in cast 'gtkwidget' (image_view:29293): glib-gobject-warning **: instance of invalid non-instantiatable type '(null)' (image_view:29293): glib-gobject-critical **: g_signal_connect_data: assertion 'g_type_check_instance (instance)' failed i'm running ubuntu 14.04.2 release using ros-indigo a similar error reported on this site no fix also rqt_image_viewer works given in link above uncompressed images , hence cannot view images sent on other camera devices eg android-camera since compressed shown below rebuilding opencv qt4 or qt off in cmake fixes problem more info in this. link

javascript - Start using Wunderlist SDK -

i using wunderlist sdk sample app im developing academic purposes. from wunderlist's docs have following code working: $(document).ready(function(){ var wunderlistsdk = window.wunderlist.sdk; wunderlistapi = new wunderlistsdk({ 'accesstoken': access_token, 'clientid': client_id }); wunderlistapi.initialized.done(function () { wunderlistapi.http.lists.all().done(handlelistdata).fail(handleerror); }); function handlelistdata(data){ $("#tasks").append("<button onclick='lookup_tasks(" + data.id + ")'>search tasks list</button>"); } function handleerror(error,event){ alert("error: "+ json.stringify(error)); } }); i confused on using the rest of api because cant figure out how can perform other requests using rest api for instance if want search tasks list_id trying following wont work: function lookup_tasks(list_id){ $.get("ht

php - LinkedIn Companies endpoint error -

i'm using linkedin api , access companies i'm running vague error haven't been able figure out. i'm using php , php libracy 'happyr\linkedin\linkedin' access api. current application has 'rw_company_admin' permission attached it. when make call api endpoint ' /v1/people/~:(id,first-name,last-name) ', correct response. but when make call ' /v1/companies?format=json&is-company-admin=true ' endpoint following error: "invalid company query request" when perform exact same query in linkedin rest console, response i'm looking for. ideas? figured out after hours of debugging. the issue specific php package mentioned in question. linkedin library in use automatically appending 'format=json' query call sparked error. by removing default output setting in library, call worked fine.

python - how to manage sys.path globally in pycharm -

Image
i have bunch of unittests import stuff not /python2.7/site-packages/ different directory. do monkey-patching in each test file sys.path.append make python see need. is there way append sys.path globally whole pycharm project without bothering each , every file? update: setting default working directory doesn't help. example, if set working directory /users/1111/_projects/_empty_dir/ so: and run this import sys p in sys.path: print p what see this /users/1111/.virtualenvs/blesk/bin/python /users/1111/_projects/_testing_pycharm/importer.py /users/1111/_projects/_testing_pycharm /users/1111/.virtualenvs/blesk/lib/python2.7/site-packages/six-1.9.0-py2.7.egg /users/1111/.virtualenvs/blesk/lib/python2.7/site-packages/parse-1.6.6-py2.7.egg /users/1111/_projects/_testing_pycharm /users/1111/.virtualenvs/blesk/lib/python27.zip /users/1111/.virtualenvs/blesk/lib/python2.7 /users/1111/.virtualenvs/blesk/lib/python2.7/plat-darwin /users/1111/.virtualenvs/blesk/lib/python2

C++ struct memory allocation -

this question has answer here: struct members memory layout 5 answers in c++ if define structure this struct complexfloat { float r; float i; }; and declare 2 variables this struct complexfloat cf; float *f=(float*)cf; can safely assume following condition true (&(cf.r)==&(f[0]) && &(cf.i)==&(f[1])) ? in other words, can safely assume in struct containing floats, elements occupy contiguous positions in memory , ordered according order in appear in definition of struct? i tested , case gcc 4.8.2 on ubuntu, want make sure valid. no cannot assume in right place unless control alignment of data in struct. there might alignment padding between r , i

html - Ruby on rails links, navigation -

i have problem ruby on rails link effects. current code is: <header class="navbar navbarfixed navbar-default navstyle> <%= link_to "cocktails",root_path, class:"btn btn-lg", id: "logo" %> <nav class="cl-effect-5 container"> <a href="#"><span data-hover="new">new</span></a> <a href="#"><span data-hover="test">test</span></a> <a href="#"><span data-hover="test">test</span></a> </nav> </header> so need convert current html link style ruby, effect still there(cl-effect-5). tried using this solution , syntax error reason, though double checked everything... one difference noted code , linked solution have hovers in <span> versus in <a> tag. = link_to '#', data: { hover: 'test' } 'test' i think that's may looking (not span

regex - mod_rewrite is appending rule to unrelated links ( side-effect ) -

rewriterule ^products/([^/]*)$ /products.cgi?id=$1 [l] will rewrite /products.cgi?id=$1 /products/$1 expected. appending /products/ links in page. suppose have link in products page is: <a href="/contact-us.cgi">contact</a> then products page link to: /products/contact-us.cgi that not desire. want keep /contact-us.cgi

sockets - Python 3.4 listening to selected server and port -

this code can create socket, connect selected server , port, , print reply. have question, how can listening port longer 1 moment? e.g. want listen selected port 20 seconds , print packets come @ time. possible code? import socket import sys try: s = socket.socket(socket.af_inet, socket.sock_stream) except socket.error msg: print("failed create socket. error code: " + str(msg[0]) + ' , error message : ' + msg[1]) sys.exit(); print('socket created') host = #server port = #port try: remote_ip = socket.gethostbyname( host ) except socket.gaierror: print('hostname not resolved. exiting') sys.exit() print('ip address of ' + host + ' ' + remote_ip) s.connect((remote_ip , port)) print('socket connected ' + host + ' on ip ' + remote_ip) reply = s.recv(4096) print(reply) you try setting timeout socket should fit requirement if understand correctly need wait 1 time 20 seconds. s.s

html - How to make atom detect .jade correctly? -

i want see jade highlighting when open .jade file on mac. have https://atom.io/packages/language-jade installed, when open .jade file atom detect html. install https://atom.io/packages/file-types , add config file (atom->open config): "file-types": jade: «source.jade» it don't change @ all. think default atom language-html plugin override settings. if disable language-html, atom detect .jade correctly , highlight properly. without language-html plugin atom detect html plain text , don't highlight @ all. should to both html , jade proper highlighting? with best regards. anton.

jquery - Krajee JqueryPlugin file input - disable validation -

i'm using krajee jqueryplugin bootstrap , have modal edit form. file selected, when submit form, have following error message: "you must select @ least 1 file upload " how disable validation upload? not want send image. this code: $('#file-0a').fileinput({ showupload: false, allowedfileextensions: ['jpg', 'png'], initialcaption: 'img48.png', initialpreview: [ "/images/img48.png" ], overwriteinitial: true }); find input tag (id="file-0a") , add attribute data-min-file-count="1" 0 this <input id="file-0a" data-min-file-count="0"/>

javascript - Attaching images to HTML form onclick -

i've been searching endlessly on internet way attach image html form onclick(). that's possible? have webpage created displays images , want specific images attached html form page when clicked can emailed me once form submitted. need sample code , take there. thanks.

Open Partial View on click of Edit button of Kendo Grid -

my grid has fileupload control in it. after successful upload of file, displaying imported records. on edit button click need display partialview . there many add edit functionality on partial grid. on close of partialview , main grid should refresh. please let me know how call partialview kindo grid on click of edit button. take @ this example blog post kendo. let use custom popup editor grid. can override events happen when custom pop closed. also @ this excellent article brad wilson custom templates in asp.net mvc. if still not meet needs please elaborate question , add code.

ruby on rails - How do I resolve: Pundit::NotDefinedError in PostsController#show? -

whenever run below program , try view posts (in show view) user, introduced error page: pundit::notdefinederror in postscontroller#show unable find policy of nil within error page: def show @post = post.find(params[:id]) authorize @posts # <- error highlights line end i'm not sure how around dilemma i'm learning pundit policy rules , new rails , ruby. appreciated. below policy pages , related pages: user.rb model class user < activerecord::base # include default devise modules. others available are: # :confirmable, :lockable, :timeoutable , :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable has_many :posts def admin? role == 'admin' end def moderator? role == 'moderator' end def member? role == 'member' end def guest? role == 'guest' end end application controller cl

swift UIWebView Into Alert -

Image
i want open alert within uiwebview programmatically. created message, action , setted own size uialert. the following code: var title = "pp" var message = "\n\n\n\n\n\n\n\n\n\n\n\n"; var alert = uialertcontroller(title: title, message: message, preferredstyle: uialertcontrollerstyle.alert); var cancel = uialertaction(title: "chiudi", style: uialertactionstyle.destructive, handler: nil) var height:nslayoutconstraint = nslayoutconstraint(item: alert.view, attribute: nslayoutattribute.height, relatedby: nslayoutrelation.equal, toitem: nil, attribute: nslayoutattribute.notanattribute, multiplier: 1, constant: self.view.frame.height * 0.90) alert.view.addconstraint(height); alert.view.frame.size.height = self.view.frame.height * 0.90 var web = uiwebview(frame: cgrect(x: 15, y: 60, width: self.view.frame.size.width * 0.8 - 15, height: self.view.frame.size.height * 0.8 - 95)) let requesturl = nsurl(string: "http://ww

function - Make jQuery Wait For $.post to complete updating page -

i calling function refresh part of current page jquery.post - , after function completes need execute function updates google map on page, using updated html written out $.post i cannot nest functions because dogooglemap() won't work within scope of refreshsubdivisionlist() function. how make wait $.post finish writing updated html page before calls dogooglemap() function? function refreshsubdivisionlist() { var formactionscript = jquery("#refreshsubdivisionform").attr('action'); jquery.post(formactionscript, jquery("#refreshsubdivisionform").serialize()).done(function(data) { jquery(".subdivision-list").html(data).show(); }, 'text'); return true; } jquery("#refreshsubdivisionform").submit(function(event) { event.preventdefault(); jquery.when( refreshsubdivisionlist() ).done(function(){ jquery('#map_canvas').gmap('destroy'); dogooglemap(); }

encoding - Remove all characters which cannot be decoded in Python -

Image
i try parse html file python script using xml.etree.elementtree module. charset should utf-8 according header. there strange character in file. therefore, parser can't parse it. opened file in notepad++ see character . tried open several encodings don't find correct one. as have many files parse, know how remove bytes can't decode. there solution? i know how remove bytes can't decode. there solution? this simple: with open('filename', 'r', encoding='utf8', errors='ignore') f: ... the errors='ignore' tells python drop unrecognized characters. can passed bytes.decode() , other places take encoding argument. since decodes bytes unicode, may not suitable xml parser wants consume bytes. in case, should write data disk (e.g. using shutil.copyfileobj() ) , re-open in 'rb' mode. in python 2, these arguments built-in open() don't exist, can use io.open() instead. alternatively, can dec

jquery - Unexpected pagecontainer change behavior -

so have page, want load using next function: //function redirect add page function redirectadd() { $("body").pagecontainer("change", "#add", { transition : "fade" }); } and have page want redirected. @ moment redirect it, redirected main page. $(document).on("pagecreate", "#home", function() { //redirections $('#addrun').on("tap", redirectadd); $('#home').on("tap", redirecthome); $('#editrun').on("tap", redirectedit); //function redirect home page function redirecthome() { $("body").pagecontainer("change", "#home", { transition: "fade" }); } //function redirect add page function redirectadd() { $("body").pagecontainer("change", "#add", { transition: "fade" }); } }); <!doc

raspberry pi - Set priority for I/O jobs -

i wonder there api or hack increase apps process priority on raspberry pi2 make sure there no io change missed. , should busy wait time sensetive jobs? you may consider using async , await in code. if specify method async method using async or async modifier, enable following 2 capabilities. the marked async method can use await or await designate suspension points. await operator tells compiler async method can't continue past point until awaited asynchronous process complete. in meantime, control returns caller of async method. the suspension of async method @ await expression doesn't constitute exit method, , blocks don’t run. the marked async method can awaited methods call it. you can learn more here: https://msdn.microsoft.com/en-us/library/hh191443.aspx

ios - Why are Storyboards Disappearing in Xcode -

Image
i have had issue storyboards disappearing main.storyboard on occasion. able 1 storyboard toggling size classes on , off. have tried playing width , height values , nothing seems working. any getting storyboards show again appreciated.

javascript - How to detect timeout on an AJAX (XmlHttpRequest) call in the browser? -

i'm looking on web, documentation hard come by. know basic ajax call using browser's built-in xmlhttprequest object (assume modern browser here): var xmlhttp = new xmlhttprequest(); // assumes native object xmlhttp.open("get", "http://www.example.com", false); xmlhttp.send(""); var statuscode = xmlhttp.status; // process it, , i'd love know if request timed out so, there way can detect ajax call timed out inspecting xmlhttprequest object in browser? advised window.settimeout(function() { xmlhttp.abort() }, 30000);? thanks! -mike update: here's an example of how can handle timeout: var xmlhttp = new xmlhttprequest(); xmlhttp.open("get", "http://www.example.com", true); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readystate == 4 && xmlhttp.status == 200) { cleartimeout(xmlhttptimeout); alert(xmlhttp.responsetext); } } // we're ready h