Posts

Showing posts from April, 2012

How do you write a Rails model method to return a list of its associations? -

what i'm trying write method return of model's outing_locations, has has_many relationship. class outing < activerecord::base attr_accessible :description, :end_time, :start_time, :title, :user_id belongs_to :user has_many :outing_locations has_many :outing_guests has_one :time_range, :foreign_key => "element_id", :conditions => { :element_type => "outing" } validates :title, :presence => true validates :start_time, :presence => true # regex validates :end_time, :presence => true # regex def host_name return user.find(self.user_id).full_name end end i'm trying block in particular work. there's model called outinginvite, contains id of particular outing. need use grab proper outing , pull said outing's associated outing locations. here's rough sample: <%@outing_invites.each |invite|%> ... <% @party = outing.where(:id => invite.outing_id) %> <% @party.out...

Access inner array in php -

i have folowing array: outerarray{ "id": "20154", "from": { "name": "xyz", "id": "10004" }} now how access element name ? it json , decode first using json_decode() , access: $arr = json_decode($yourjson, true); echo $arr['from']['name']; // xyz or $arr = json_decode($yourjson); echo $arr->from->name; // xyz http://php.net/manual/en/function.json-decode.php

android - How to prevent screen autorotation but prevent activity from rotating -

this may sound newbie question anyway i'm new android development. basically need prevent activity changing rotation meanwhile need detect device orientation change i.e. if device orientation has been changed top botton, or top left-portrait etc. in ios there analogue - (bool)shouldautorotatetointerfaceorientation can handle device orientation change , tell view if want autorotate or not. please pay attention no manual data handling of accelerometer data. so want detect device's orientation change , prevent activity rotating. i'm playing data sensor detect shake. internally android filtration of signals in order decide when rotate ui. need catch event. can ? simple formulation of question : i need detect android device orientation change without playing manually sensor data, while keeping activity orientation stick orientation this need if want fix 1 orientation landscape, go androidmanifest , in activity <activity android:label="@strin...

HTML5 Video in Safari -

little bit confused @ moment, have 2 .mp4 files, both h.264 encoded video. | #safari | video 1 | video 2 | | windows | failed | played | | osx | played | played | my code <video width="550" height="400" controls> <source src="test/charlie.mp4" type="video/mp4" /> <source src="test/charlie.ogv" type="video/ogg" /> nope. </video> video 1 status: http/1.1 200 ok date: wed, 27 jun 2012 09:19:02 gmt server: apache/2.2.22 (debian) last-modified: wed, 27 jun 2012 08:06:41 gmt etag: "aff04e8-49c7f3-4c36fb1f12640" accept-ranges: bytes content-length: 4835315 connection: close content-type: video/mp4 video 2 status: http/1.1 200 ok date: wed, 27 jun 2012 09:18:37 gmt server: apache/2.2.22 (debian) last-modified: mon, 28 dec 2009 05:06:33 gmt etag: "aff04eb-45de48-47bc2de762840" accept-ranges: bytes content...

mysql - Including a php file in Joomla! 1.5 that calls another php file -

i include php program joomla! article, program calls different php files used display want, have tried install different plugins such jumi, directphp , others, keep getting following error: application raised exception class edatabaseerror message 'cannot connect database server:mysql error: [0: connection error server '' user ''] in connect(, '', ' * *', ) ' the program runs fine standalone, not work when i'm running on joomla. the connection parameters obtained include "config.php" seems won't includes included php file. also when try include menu have made, works standalone, redirects me index.php of joomla! root dir. thanks. i've done things similar this, have had install couple of extensions them work. first, use jce wysiwyg. installed place anywhere (which lets place modules inside articles) create new module, type=custom html code php there... i know isn't you're describing, it'...

c++ - Strange runtime error when iterating over std::deque -

consider following piece of code: 1 typedef std::deque<int> mydeque_t; 2 mydeque_t mydeque; 3 4 mydeque_t::iterator start = mydeque.begin(); 5 6 (int = 0; != 1000; ++i) 7 mydeque.push_back(i); 8 9 (mydeque_t::iterator myint = start; myint != mydeque.end(); ++myint) 10 *myint += 1; when executing runtime error on line 10 (live example: http://ideone.com/juqaa ). when change line 6 for (int = 0; != 100; ++i) code works fine. the code fixed moving start definition (line 4) behind first loop, in example need stay before it. think should run fine, can explain me why not? after call push_back() , iterators invalidated. deque::push_back() : appends given element value end of container. all iterators invalidated . no references invalidated. guess : code works fine 100 , not 1000 internal storage of deque did not have reallocated accomodate 100 elements resulting in begin() iterator remaining valid.

java execution by inheriting from file from shared folder -

i have 2 files, 1 in local machine , in shared folder(from machine). my class on localmachine has inherit class in file in shared folder. how can perform inheritance? i tried giving set classpath=%classpath%;//(machineno)/(foldername); did not work. the urlclassloader can used develop application capable of loading classes , resources remote servers. first, need define urls searched classes. url ends '/' assumed refer directory, otherwise url assumed refer jar file opened needed. once instance of urlclassloader constructed, loadclass(string name) method of classloader class used load class specified name. once class has been loaded, instance can created (this means constructor invoked). import java.net.*; import java.io.*; public class myloader { public static void main (string argv[]) throws exception { urlclassloader loader = new urlclassloader(new url[] { new url("http://www.javacourses.com/classes/") }); // load class clas...

c# - Bind Combo Box based on another Combo Box's selected item - MVVM WPF -

i have combo box populated artist names , need bind once artist selected. these set follows in view: <combobox height="23" horizontalalignment="left" margin="65,81,0,0" name="combobox1" itemssource="{binding artists}" selecteditem="{binding selectedartist}" verticalalignment="top" width="120" /> <combobox height="23" horizontalalignment="left" margin="65,115,0,0" name="combobox2" verticalalignment="top" itemssource="{binding albums}" selecteditem="{binding selectedalbums}" width="120" /> in viewmodel have following: private void initialiseartists() { musicdataclassesdatacontext dataclasses = new musicdataclassesdatacontext(); artistlist = (from m in dataclasses.tblartists select m.artistname).tolist(); } public list<string> artists { { ...

PHP mySQL RLIKE similar expanded + or - 5 -

using rlike able find people similar surnames or telephone numbers. mysql_query("select * electors (surname rlike '$surname' or telephone rlike '$telephone') limit 9"); 1 - problem need priorities surnames , go telephone numbers second total limit of 9 records. 2 - want concatenate first line of address address1 , postcode find similar records this way if house number 14 , postcode zz18mp find nearby houses. eg. 12 zz18mp. households aren't in system can't increment 1, needs closest match. how this. you can use full text search functions , ranks suranmes , telephone numbers. based on rank, filter our data. here tutorial start http://devzone.zend.com/26/using-mysql-full-text-searching/ note : full-text searches supported myisam tables only

php - Using Inner Join and mysql_num_rows() is Always returning 1 less row -

i checked throught existing topics. have fix problem know not right fix , i'm more interested making work right, creating workaround it. i have project have 3 tables, diagnosis, visits, , treatments. people come in visit, treatment, , treatment diagnosis. for displaying information on page, want show patient's diagnosis, show time came in visit, visit info can clicked on show treatment info. to made function in php: <? function returntandv($dxid){ include("db.info.php"); $query = sprintf("select treatments.*,visits.* treatments left join visits on treatments.tid = visits.tid treatments.dxid = '%s' order visits.dos desc", mysql_real_escape_string($dxid)); $result = mysql_query($query) or die("failed because: ".mysql_error()); $num = mysql_num_rows($result); for($i = 0; $i <= $num; ++$i) { $v[$i] = mysql_fetch_array($result mysql_assoc); ++$i; } return $v; } ?> t...

ruby on rails - Can you add a find_or_create to the before_save call back on ActiveRecord? -

i have model see if object exists before saving. , if does, not create new object, use existing one. is possible add directly before_save activerecord class of model ? i believe impossible because can not change value of self. activerecord provides functionality. can like: user.find_or_initialize_by_email('some@email.com') this return user database, if found, or new user email set passed parameter. can use object otherwise , call save when done (which update or create needed). more info on http://api.rubyonrails.org/classes/activerecord/base.html (search page find_or_initialize_by_)

objective c - Accessing NSProgressIndicator located in NSPersistentDocument from another class -

in application build, i've created terminalcontroller subclass of nspersistentdocument. in terminalcontroller there outlet of nsprogressindicator connected instance of progress indicator in main window nib. progress indicator serve determinate progress placed in terminalcontroller class, because want various classes use in process of uploading or downloading data server. there 1 class used uploading images - imageuploader - suppose trigger progress indicator located in main window nib , connected terminalcontroller. my problem cannot seem figure out how access progress indicator in terminalcontroller imageuploader. can't create instance of imageuploader in main window nib , connected there, imageuploader gets initialised , released in code. there must way of accessing object think. 1 of idea make progress indicator global instance, aware structure point of view wrong , not recommended. i appreciate suggestions regarding issue here sample of code terminalcontrol...

mysql - Select 1 row from table where foreign key table records exist -

i've got 2 tables, products , productimages 1 many relationship between products , productimages. i'm trying work query on on products table condition results contain rows matching records in productimages table. products ---------- id (pk) productimages --------------- id (pk) product_id (fk products) the way can work subquery, surely there must better/more efficient way. select p.* products p inner join productimages pi on p.id = pi.product_id group p.id

java - Unable to rename file -

i trying exercise of deleting lines file not starting particular string. idea copy desired lines temp file, delete original file , rename temp file original file. my question unable rename file! tempfile.renameto(new file(file)) or tempfile.renameto(inputfile) do not work. can tell me going wrong? here code: /** * intention have method delete (or create * new file) deleting lines starting particular string. * */ package com.dr.sort; import java.io.bufferedreader; import java.io.file; import java.io.filenotfoundexception; import java.io.filereader; import java.io.filewriter; import java.io.ioexception; import java.io.printwriter; public class removelinesfromfile { public void removelinesstartswith(string file, string startswith, boolean keeporigfile) { string line = null; bufferedreader rd = null; printwriter wt = null; file tempfile = null; try { // open input file file inputfile = new file(fil...

sql server - Passing a variable into an IN clause within a SQL function? -

possible duplicate: parameterizing sql in clause? i have sql function whereby need pass list of ids in, string, into: where id in (@mylist) i have looked around , of answers either sql built within c# , loop through , call addparameter, or sql built dynamically. my sql function large , building query dynamically rather tedious. is there no way pass in string of comma-separated values in clause? my variable being passed in representing list of integers be: "1,2,3,4,5,6,7" etc passing string directly in clause not possible. however, if providing list string stored procedure, example, can use following dirty method . first, create function: create function [dbo].[fnntexttointtable] (@data ntext) returns @inttable table ([value] int null) begin declare @ptr int, @length int, @v nchar, @vv nvarchar(10) select @length = (datalength(@data) / 2) + 1, @ptr = 1 while (@ptr < @length) begin set @v = substring(@...

c# - How to populate ComboBoxes by lines of a string Array? -

please, wrong here abc = labguns.text; // multiline label string[] arr = regex.split(abc, "\r\n"); x = 0; foreach (string line in arr) { messagebox.show(line); //works fine - shows each line of label x = x + 1; string abc = "cbguns" + x.tostring(); messagebox.show(abc); //works fine - shows "cbguns1", "cbguns2"... foreach (control c in panprev.controls) { if (c.name == abc) // 5 combos named cbguns1, cbguns2... { c.text = line; //doesn't work. no combo changes text } } } if change last line - c.text = "323" - nothing happened. so, mistake somewhere near end of code. this code works (as test): foreach (control c in panprev.controls) { if (c.name == "cbguns1") { c.text = "323"; } } if i'm understanding correctly, want add line combobox, not select line in it, correct? in order this, don't set text value of combobox st...

javascript - JSON data fetching through Yahoo! Placefinder -

i trying retrieve information placefinder api. code takes information text box , sends yahoo on button click. function codeaddress(){ var address = document.getelementbyid("address").value; var requesturl = "http://where.yahooapis.com/geocode?q="+address+"&flags=j&callback=ws_results&output=json"; jsonobject = new xmlhttprequest(); jsonobject.open( "get", requesturl, false ); jsonobject.send( null ); return jsonobject; document.getelementbyid("jlatitude").innerhtml=jsonobject.latitude; alert(document.write("jlatitude")); } firebug tells me data returned, yet cannot display want in troubleshooting popup. placefinder returns when request geocoding maryland. {"resultset":{"version":"1.0","error":0,"errormessage":"no error","loc...

WiFi Direct (Android 4.0) with multiple (3+) devices -

like here: automatic authentication android wifi direct want create mobile ad-hoc wifi network android devices. unlike linked question above want use official android wifi direct api availabe since android 4.0. so there way not connect 2 devices via wifi direct 3 or more? messages passed 1 device using several other devices in between (therefore spanning larger distance between sender , receiver)? the wifi direct demo works pairing 2 devices , not find way else. thanks! is there way not connect 2 devices via wifi direct 3 or more? yes, wi-fi direct specifications explain possible create 1 many connection. 1 of devices act group owner (think access point). have been able create wi-fi direct network 3 devices during tests. as devices have in range of group owner, sure message arrive second client. 1st client -> group owner -> 2nd client

Is a full html page needed when loading a page with jQuery mobile? -

i looking @ jquery mobile , system of loading web pages xmlhttprequest. possible automatically perform transition animations between 2 pages, instance. however, not clear me. if understand correctly, each new page of jquery mobile powered website injected in dom of initial web page. documentation of jquery mobile tells because of mechanism, <title> tag of new webpages not taken account. so, in way, if initial webpage a.html loads page b.html, tend think webpage b.html not need have full html grammar <html> , <head> or <body> tags. my page b.html directly begin <div> element. am right? is full html page needed when loading html page jquery mobile? what pros , cons having webpage wrong/truncated html syntax (appart page should not accessed directly through main page)? but happens when user starts off on a.html , goes b.html , , refreshes page? jquery mobile uses pushstate plugin updates url if user had gone b.html page normally. m...

How can I run several schedule using quartz with spring configuration -

in situation, clients allowed schedule job. can see, quartz use cronexpression perform schedule. there many clients many schedules, can't write many trigger beans cuz don't know how many schedules are, depends on clients. so, 1 help? quartz designed add , remove jobs , triggers @ runtime. spring degenerated case triggers , jobs defined @ startup time. in quartz, when having instance of scheduler can create, browse , delete triggers @ wish, example how-to: scheduling job : // define job instance jobdetail job1 = newjob(colorjob.class) .withidentity("job1", "group1") .build(); // define trigger fire "now", , not repeat trigger trigger = newtrigger() .withidentity("trigger1", "group1") .startnow() .build(); // schedule job trigger schedulder.schedulejob(job, trigger); see official documentation , cookbook . also distinguish between jobs (a piece of code wrapped in class should executed) ,...

sql - How can I order results which have some value equals zero in the end, while other results are ascending? -

let me explain: need sort list in ascending order, while results leave less 0 @ end. example: **field** 2 5 15 19 0 -5 -19 i think can join result of 2 queries using union, want using one, possible? any answer telling how order thay way appreciated. use following order @ end of normal query (no union) order (case when field>0 0 else 1 end), field or, if database system's sql flavor supports implicit conversion of booleans integers: order (field <= 0), field

ruby - Rails save serialized object fails? -

see following output: 1.9.3p194 :001 > player = player.randomize_for_market => #<player id: nil, name: "gale bridges", age: 19, energy: 100, attack: 6, defense: 4, stamina: 5, goal_keeping: 3, power: 4, accuracy: 5, speed: 5, short_pass: 5, ball_controll: 4, long_pass: 6, regain_ball: 5, contract_id: nil, created_at: nil, updated_at: nil> 1.9.3p194 :002 > player.save! (0.2ms) begin sql (20.5ms) insert "players" ("accuracy", "age", "attack", "ball_controll", "contract_id", "created_at", "defense", "energy", "goal_keeping", "long_pass", "name", "power", "regain_ball", "short_pass", "speed", "stamina", "updated_at") values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17) returning "id" [["accuracy", 5], ["age", 19...

c# - Accessing Objects used to populate DataGridView through DataTable -

i attempting access object used fill datagridview in method: void memberdatagridview_selectionchanged(object sender, eventargs e) { foreach (datagridviewcell cell in memberdatagridview.selectedcells) { foreach (datagridviewrow row in memberdatagridview.rows) { if (row.cells.contains(cell)) { //here want access object used build row. //it added comboboxitem } } } here code of object being added gridview using datatable datarow row = _loadmemberstable.newrow(); row["member name"] = member.internallabel; row["type"] = member.membertype; _loadmemberstable.rows.add(row); memberdatagridview.datasource = _loadmemberstable; what can when building datatable find member object when need in selectionchanged? i not sure if understood question properly. think assigning object member properties data table columns, not object self. therefore can't directly object of type 'member' data table. ...

ios - How to release a tree structure in xcode project? -

Image
i have made tree structure using c , used storing moves of chess game. structure is struct node{ nsstring *comment; nsstring *move; struct node *variationlink; struct node *nextlink; struct node *goback; }; i create node using malloc.when game changed or unloaded want release tree there way in dalloc or have make function reach each node , free it? you need create function recursively frees structure, like: void free_nodes(struct node *n) { if (n != null) { free_nodes(n->nextlink); free_nodes(n->variationlink); [n->comment release]; [n->move release]; free(n); } } and call within dealloc method: - (void)dealloc { free_nodes(_root_node); [super dealloc]; } other comments: you'll want link mainline of variation, equivalent goback pointer, variations. allow transverse mainline of node, @ moment there no way of performing full transversal of...

css - How do I get display:inline-block to be inline? -

Image
<ul class="random-list"> <li> <div class="random-container"> <div class="inline-block" style="vertical-align: top;"> <img src="" /> </div> <div class="inline-block" style="vertical-align: top;"> <a href="">name</a> </div> </div> </li> </ul> and css: .random-container { margin-bottom: 10px; width: 100%; } .inline-block { display: inline-block; } result: how fix error: how don't use inline-block @ all, , rid of of unnecessary divs. <ul class="random-list"> <li> <img src="" /> <a href="">name</a> </li> </ul> live example

import - What to do if I have a "Do not know how to load 'dart:html' " when loading library? -

the first 2 lines in dart library are: #library('libraryname'); #import('dart:html'); when try load library .dart file #import('../path/to/libraryname.dart'); i following error: do not know how load 'dart:html''file:///the/path/to/libraryname.dart': error: line 2 pos 1: library handler failed #import('dart:html'); ^ the #import('dart:html') works fine when use library standalone app, want able access library dart app. how can use library? dart:html available in browser side. looks trying run client side script dart.exe on server side. dart:html available on browser (and interacts dom) dart:io available on server (and interacts os)

Asp.Net Repeater loses data on postback -

my problem bit more complicated title says: i made user control (i called editor) editing data base data user control made(i called gridview). the editor use each row (a row usercontrol , editor inside row insert) inside gridview , work not when try use insert. the difference between insert , edit field: #region field /// <summary> /// /// </summary> //public field field { { return dataitem field; } } private field _field; [bindable(true)] public field field { { if (isinsert && _field == null) { _field = subscriptioncontroller.createfield(); } return _field; } set { _field = value; } } #endregion inside field i've collection bind repeater subscriptioncontroller.createfield(); method create instance of field class , collection inside here code: public field createfield() { field field = new f...

How to download .msi file in Java -

i want download .msi file using java. have tried download file using following code printwriter out = null; fileinputstream filetodownload = null; bufferedreader bufferedreader = null; try { out = response.getwriter(); filetodownload = new fileinputstream(download_directory + file_name); bufferedreader = new bufferedreader(new inputstreamreader(filetodownload)); //response.setcontenttype("application/text"); //response.setcontenttype("application/x-msi"); //response.setcontenttype("application/msi"); //response.setcontenttype("octet-stream"); response.setcontenttype("application/octet-stream"); //response.setcontenttype("application/x-7z-compressed"); //response.setcontenttype("application/zip"); response.setheader("content-disposition","attachment; filename=" +file_name ); response.setcontentle...

common lisp - How to add a local project to asdf configured by quicklisp -

i want add local project known projects asdf, due fact asdf installed , configured quicklisp , *central-registry* points "#p/home/user/quicklisp/quicklisp/", contains .lisp files. not know how manual explains symbolic link directory it, not want mess around inside quicklisp. (it work hotfix, though!) therefore:how add local project asdf (not quicklisp) installed , configured quicklisp? if use quicklisp can use dedicated directory ~/quicklisp/local-projects/ scanned before others directories. use it, put project or symbolic link. (quickproject:make-project "~/quicklisp/local-projects/my-new-website/" :depends-on '(restas parenscrit cl-who)) (quickproject:make-project "~/src/lisp/my-cool-gui/" :depends-on '(qt)) $ ln -s ~/src/lisp/my-cool-gui ~/quicklisp/local-projects/my-cool-gui however, if want configure asdf explained in documentation . for example can put this: (:directory "~/src/lisp/my-project-xyz/"...

iphone - Accessing raw audio data with Audio Queue using AudioFileReadPackets -

i'm attempting access raw audio data sent audio queue callback, after calling audiofilereadpackets, number of bytes (numbytes) 0. void aqrecorder::myinputbufferhandler(void *inuserdata, audioqueueref inaq, audioqueuebufferref inbuffer, const audiotimestamp * instarttime, uint32 innumpackets, const audiostreampacketdescription* inpacketdesc) { aqrecorder *aqr = (aqrecorder *)inuserdata; try { if (innumpackets > 0) { //read packets uint32 numbytes; osstatus result = audiofilereadpackets(aqr->mrecordfile, // audio file packets of audio data read. false, // set true cache data. otherwise, set false. &numbytes, // on output, pointer number of bytes returned. (__bridge audiostreampacketdescription*)inpacketdesc, // pointer array of packet descriptions have been ...

Powershell script parameters: display help on incorrect usage? -

in powershell v2, trying use param() declaration parse switches passed script. problem can illustrated using script (example.ps1): param( [switch] $a, [switch] $b, [switch] $c ) echo "$a, $b, $c" my problem script silently ignore incorrect switches. instance, "example.ps1 -asdf" print "false, false, false", instead of reporting incorrect usage user. i noticed behavior changes if add positional parameter: param( [switch] $a, [switch] $b, [switch] $c, [parameter(position=0)] $positionalparameter ) echo "a:$a, b:$b, c:$c" now, parameterbindingexception raised if run "example2.ps1 -asdf". but, "example2.ps1 asdf" (notice parameter without leading dash) still silently accepted. i have 2 questions: is there way powershell report argument script error? in script, want allow fixed set of switches (-a, -b, -c), , other parameter should error. when parameter error detected, can powershell ...

jquery - get copy of div data in javascript variable -

html part:- <form id="inquiryform" method="" /> <h2>inquiry form</h2> <div class="margin5"> <div class="floatleft width100"><span class="borderbottom">party name</span> </div> <div class="floatleft"><input type="text" name="partyname" size="60"/></div> <div class="clear"></div> </div> </form> <div> <input type="button" id="submitform" value="send mail"/></div> jquery :- $(document).ready(function () { $('#submitform').click(function(){ var data = 'message='+$('#inquiryform').html(); alert(data); }); }); when click on send mail button ok html part want when entered in textbox data variable empty. want whatever write in text-box must part of data variable. ...

c++ - Disallowing creation of the temporary objects -

while debugging crash in multithreaded application located problem in statement: csinglelock(&m_criticalsection, true); notice creating unnamed object of csinglelock class , hence critical section object gets unlocked after statement. not coder wanted. error caused simple typing mistake. question is, there someway can prevent temporary object of class being created @ compile time i.e. above type of code should generate compiler error. in general, think whenever class tries sort of resource acquisition temporary object of class should not allowed. there way enforce it? edit: j_random_hacker notes, possible force user declare named object in order take out lock. however, if creation of temporaries somehow banned class, user make similar mistake: // take out lock: if (m_multithreaded) { csinglelock c(&m_criticalsection, true); } // other stuff, assuming lock held ultimately, user has understand impact of line of code write. in case, have know they'...

java - Set Font Size of selected text in JEditorPane Using JComboBox -

how can set font size of selected text in jeditorpane (pane) using jcombobox? previously used: toolbar.add(new stylededitorkit.fontsizeaction("12", 12)); but cant have hundreds of buttons. i don't know canonical way this, on experimentation, works: import java.awt.borderlayout; import java.awt.dimension; import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.action; import javax.swing.jcombobox; import javax.swing.jeditorpane; import javax.swing.jframe; import javax.swing.jpanel; import javax.swing.jscrollpane; import javax.swing.swingutilities; import javax.swing.text.badlocationexception; import javax.swing.text.defaultstyleddocument; import javax.swing.text.document; import javax.swing.text.styleddocument; import javax.swing.text.stylededitorkit; public class editorpanefun extends jpanel { private static final integer[] items = { 9, 10, 11, 12, 14, 16, 18, 20, 24, 32 }; private jeditorpane edito...

After using git to locally track a project, how can I add it to GitHub? -

after using git locally track project, how can add github? github gives instructions after you've created repository online. cd directory local repository git remote add origin whatever-address-my-repository is.git set remote then make commit, , push master branch. git push -u origin master https://help.github.com/articles/create-a-repo

php - Nesting inner array as value in pre-existing multi-dimensional array -

i have array called: $fragment = array($fragment); which has following 3 values: ["<div class=\"alert alert_error mt20\"><a class=\"js-alert-close close\"><\/a>please enter title <\/div>"] ["<div class=\"alert alert_error mt20\"><a class=\"js-alert-close close\"><\/a>enter valid source url (e.g. http:\/\/en.wikipedia.org\/wiki\/penguins) <\/div>"] ["<div class=\"alert alert_error mt20\"><a class=\"js-alert-close close\"><\/a>please choose category <\/div>"] i want merge array array (into 'fragment' key) looks like: $toreturn = array( 'status' => $status, 'formdata' => $formdata, 'inputs' => $inputs, 'fragment' => $fragment ); but every time so, adds first value of $fragment is: "<div class=\"alert alert_error mt20\"...

android - Runtime error: ClassNotFound exception -

i've been having runtime error week , can't find solution (i'm new android programmer). please me! the log @ end of message. know there similar questions mine couldn't find solution problem. i'm trying call class activity using intent runtime error says class couldn't found. this log file: 07-01 13:22:57.098: e/dalvikvm(1488): not find class 'com.xxx.ui.viewpager', referenced method com.xxx.ui.mainiwrapper.oncreate 07-01 13:22:57.338: e/androidruntime(1488): fatal exception: main 07-01 13:22:57.338: e/androidruntime(1488): java.lang.runtimeexception: unable start activity componentinfo{com.xxx/com.xxx.ui.mainiwrapper}: android.view.inflateexception: binary xml file line #43: error inflating class com.xxx.ui.navigationbar 07-01 13:22:57.338: e/androidruntime(1488): @ android.app.activitythread.performlaunchactivity(activitythread.java:1647) 07-01 13:22:57.338: e/androidruntime(1488): @ android.app.activitythread.handlelaunchactiv...

java - Unable to get Maven (and Eclipse) to use test resources while testing -

i having trouble getting unit tests use resources provided under src\test\resources instead of in src\main\resources . yes, resource in question named identically in both places. i have done fair amount of research, looked @ stackoverflow posts such as: make maven use test resources make eclipse use test resources however basic issue has me stumped. i have standard maven java project set up: application source & resources under src\main test source & resources under src\test eclipse (thanks m2eclipse plugin) has src\main\java , src\main\resources , src\test\java , src\test\resources in build path. with setup, when run unit test within eclipse resource files in src\main\resources being referenced. can see why (because in build path) don't know how prevent it. unit test configuration panel not allow me tweak order of (default) classpath components. even if gloss on inability run tests eclipse, maven doesn't play nice either. can see proce...

javascript - Disallowing PHP file to be accessed directly -

i have html form when gets submitted calls javascript function using ajax gets information php file using post , displays page. the question is, possible make php file accessible when using above method instead of users being able access directly if go through js method , find it's location? edit: adding bit more information people out. ajax calling external php file in order update contents of website based on php file returns. since ajax calls made in javascript can find out location , arguments function using , call php file directly, i'm trying avoid. using php sessions bit hard in case, since i'm using ajax can't destroy session once external php file done since if session never renews because i'm using ajax update content of website without refreshing it. i agree limscoder. here how use tokens on submitting forms. 1) initialize , save on server (when page loaded on client side) $token = $_session['token'] = md5(uniqid(mt_rand()...

javascript - JQuery: parameter: hard-coded string vs ajax retrieved string -

i trying jquery token input prepopulated. var assignuserjson=$('#assignuserjson').val(); console.log(assignuserjson); //[{"id":"1","name":"andrew"},{"id":"3","name":"john"}] here difference between 2 ways supposed should work in: $('#assigntask').tokeninput('/users/suggest', {prepopulate: assignuserjson}); // doesn't work and works: $('#assigntask').tokeninput('/users/suggest', {prepopulate: [{"id":"1","name":"andrew"},{"id":"3","name":"john"}]}); // works why that? shouldn't able value hidden input field , pass tokeninput function? in first method, assignuserjson string whereas in second method, array object. objectifying first 1 should work: $('#assigntask').tokeninput('/users/suggest', {prepopulate: json.parse(assignuserjson)}...

MySQL making whitespace matter -

apparently rare issue, imo extremely annoying , wrong: trailing whitespace in mysql aren't used in comparison: mysql> select "a" = "a "; +------------+ | "a" = "a " | +------------+ | 1 | +------------+ 1 row in set (0.00 sec) this problematic in following scenario: mysql> select count(*) eq name != trim(name); +------------+ | count(*) | +------------+ | 0 | +------------+ 1 row in set (0.00 sec) mysql> update eq set name=trim(name); query ok, 866 row affected (0.01 sec) rows matched: 650907 changed: 866 warnings: 0 is there way configure mysql treat whitespace properly? according the manual , 1 quick fix use like: per sql standard, performs matching on per-character basis, can produce results different = comparison operator: ... in particular, trailing spaces significant, not true char or varchar comparisons performed = operator ... as long don't use wildcards, sho...

java - Formatted Pdf word to html -

i need convert formatted pdf , word document html. conversion show document web browsers. web browser can select text. don't know if better @ backend side (with java example) or maybe php, or there jquery/javascript plugin? my target show these documents in web browser ipaper. thanks help you can use pdftohtml , run server-side automatically, or batch process pdfs it.

warnings - Lattice Diamond: Setting up a clock -

i'm working on learning verilog , working cplds , i'm stuck. code wrote toggles led, keep getting warnings during synthesis. //toggles led on , off after 1000000 clock cycles module ledon( led, clk ); output led; reg led; input clk ; wire clk; reg [31:0] count; wire count_max = 32'd1_000_000; assign count_nxt = (count >= count_max) ? 32'd0 : count + 32'd1; assign led_state_nxt = (count == count_max) ? ~led : led; @(posedge clk) begin count <= count_nxt; led <= led_state_nxt; end endmodule i these warnings: @w: mt420 |found inferred clock ledon|clk period 1000.00ns. please declare user-defined clock on object "p:clk" warning - map: c:/documents , settings/belo/desktop/ledon2/ledon2.lpf (4): error in frequency net "clk" 2.080000 mhz ; warning - map: preference parsing results: 1 semantic error detected warning - map: there errors in preference file, "c:/documents , settings/belo/desktop/ledon2/l...

sql server - Regex for hh:mm:ss tt string -

i've looked @ few regex time questions haven't found 1 need , i'm pretty clueless on how write regex expressions. i need time values pass: 06:03:05 am 06:03 pm 6:3:5 am this regex seems it'd work this(which found on here need have am/pm part required can case insensitive. ([0-1]?\d|2[0-3]):([0-5]?\d):([0-5]?\d) so sum need in regex: single digit h:m:s acceptable double digit hh:mm:ss acceptable am/pm required case insensitive if am/pm part can entered or p nice, not needed seconds optional 24 hour time not acceptable any appreciated. the regex provide supports 24 hour time, following stringently follows request (1[012]|0?\d):[0-5]?\d(:[0-5]?\d)?\s+[aapp][mm]?

osx - How to unpack and pack pkg file? -

i have pkg file created install maker mac. want replace 1 file in pkg. must under linux system, because part of download process. when user starts download file server must replace 1 file in pkg. have solution how unpack pkg , replace file dont know how pack again pkg. http://emresaglam.com/blog/1035 http://ilostmynotes.blogspot.com/2012/06/mac-os-x-pkg-bom-files-package.html packages .xar archives different extension , specified file hierarchy. unfortunately, part of file hierarchy cpio.gz archive of actual installables, , that's want edit. , there's bom file includes information on files inside cpio archive, , packageinfo file includes summary information. if need edit 1 of info files, that's simple: mkdir foo cd foo xar -xf ../foo.pkg # edit stuff xar -cf ../foo-new.pkg * but if need edit installable files: mkdir foo cd foo xar -xf ../foo.pkg cd foo.pkg cat payload | gunzip -dc |cpio -i # edit foo.app/* rm payload find ./foo.app | cpio -o | gzip -c ...

jquery - uplodify uploads files one by one -

i use uplodify 3.1 upload multiple files in asp.net. allows select mutiple files , uploads them. probem have click upload button each item. (aouto attribute set false) here code: <head> <script src="scripts/jquery.js" type="text/javascript"></script> <script src="scripts/jquery.uploadify-3.1.js" type="text/javascript"></script> <script type="text/javascript"> $(window).load( function () { $("#<%=fileupload1.clientid%>").uploadify({ 'swf': 'scripts/uploadify.swf', 'uploader': 'upload.ashx', 'filetypedesc': 'image files', 'filetypeexts': '*.jpg;*.jpeg;*.gif;*.png', 'multi': true, 'formdata': { 'galerisi': '<%=session["galeriid"]%>' }, 'auto': false, ...

osx - Java/Swing - Tooltip rectangle -

Image
i'm developing java/swing project, , i'm stuck in customization process. i've extended jtooltip , overrided paint() method draw own tooltip, can't manage remove background around tooltip. here's paint() override: /* (non-javadoc) * @see javax.swing.jcomponent#paint(java.awt.graphics) */ @override public void paint(graphics g) { string text = getcomponent().gettooltiptext(); if (text != null && text.trim().length() > 0) { // set parent not opaque component parent = this.getparent(); if (parent != null) { if (parent instanceof jcomponent) { jcomponent jparent = (jcomponent) parent; if (jparent.isopaque()) { jparent.setopaque(false); } } } // create round rectangle shape round = new roundrectangle2d.float(4, 4, this.getwidth() - 1 - 8, this.getheight() - 1 - 8, 8, 8); // draw backgrou...