Sunday, 15 June 2014

ajax - Syntax error in Javascript function -



ajax - Syntax error in Javascript function -

java script

$('#senurl').click(function () { $.ajax({ type: "post", url: "/admin/coupon1/reject", datatype: "json", data: "id="+@model.id+"&url="+@url }); });

referenceerror: expired not defined [break on error] data: "id="+2925+"&url="+expired

you want (but see below):

$('#senurl').click(function () { $.ajax({ type: "post", url: "/admin/coupon1/reject", datatype: "json", data: "id=@model.id&url=@url" }); });

...because have think browser sees, , if @url gets replaced expired server, error can tell browser sees code is:

data: "id="+2925+"&url="+expired // <=== browser sees current code

even better, allow jquery handle potential uri-encoding needed passing object instead:

$('#senurl').click(function () { $.ajax({ type: "post", url: "/admin/coupon1/reject", datatype: "json", data: {id: @model.id, url: "@url"} }); });

if don't want pass jquery object , allow handle uri-encoding you, you'll want handle yourself:

data: "id=@model.id&url=" + encodeuricomponent("@url")

javascript ajax jquery

sed - grep part of nth lines linux -



sed - grep part of nth lines linux -

i have file like:

something1 something2 201101130000 thing thing1 thing2 aaa, -2, 4, 0, 54; thing3 thing4 aaa, 43, 43, 0, 5, 0, 0,; thing5 aaa, 132.0, 43.0, 0.0, 0.0, 43.0,210.0,' thing5

how re-create date (201101130000) sec line, add together comma (,) set numbers of line before lastly (132,0, 43.0, 0.0, 43.0, 210.0) in newfile.txt new file should like:(the original file not have spaces between lines here)

20110113, 132.0, 43.0, 0.0, 0.0, 43.0,210.0

i tried grep , sed no luck. help

here's how i've interpreted question:

you're trying 'grep' , bring together parts of 2 lines. these 2 lines sec , sec lastly lines.

you're trying redirect output file. can utilize shell redirection this, like: awk ... file > outputfile.

here's 1 way using sed:

sed '2h; $!n; $!d; ${ g; s/[^,]*\([^\n]*\).* \([0-9]\{8\}\).*/\2\1/; s/..$// }' file

since you've tagged linux, i'm guessing you've got gnu sed , don't mind golf:

sed -r '2h;$!n;$!d;${g;s/[^,]*([^\n]*).*\s([0-9]{8}).*/\2\1/;s/..$//}' file

results:

20110113, 132.0, 43.0, 0.0, 0.0, 43.0,210.0

explanation:

2h # re-create sec line hold space $!n # if not lastly line append next line $!d # if not lastly line delete first newline in pattern $ { ... } # 1 lastly line, perform 2 substitutions

alternatively, awk may easier understand:

awk 'fnr==nr { c++; next } fnr==2 { x = substr($nf,0,8) } fnr==c-1 { sub(/[^,]*/,x); sub(/..$/,""); print }' file file

results:

20110113, 132.0, 43.0, 0.0, 0.0, 43.0,210.0

explanation:

fnr==nr { c++; next } # read first file in arguments list, # count of number of lines in file fnr==2 { ... } # when reading sec line of sec file in # arguments list, take substring of lastly field fnr==c-1 { ... } # 1 sec lastly line of sec file in # arguments list, perform 2 substitutions , print # line.

linux sed grep

Need a RegEx that matches only a single instance of the pipe character -



Need a RegEx that matches only a single instance of the pipe character -

i'm trying write regex match instances of 'pipe' character (|) not followed 1 or more farther pipes. pipe followed other pipe.

i have doesn't appear working:

/|(?!/|)

you escaping pipe wrongly. need utilize backslash, , not slash. apart that, need utilize negative look-behind, last pipe not matched, not preceded pipe, not followed it: -

(?<!\|)\|(?!\|)

generally, prefer utilize character class rather escaping if want match regex meta-character class: -

(?<![|])[|](?![|])

but, it's taste.

regex

javascript - how to change the css property of aboslute position div with parent div id -



javascript - how to change the css property of aboslute position div with parent div id -

<html> <head> <script src="jquery.min.js"></script> </head> <body> <div id="disp"> <div> hi how u </div> <div style="position:absolute;left:50px;top:100px;"> hello </div> </div> <script type="text/javascript"> $(function(){ $("#disp").css({"background-color":"#00ff00"}); }); </script> </body> </html>

here giving bluish color "hi how u" not reflect in next div because in position:aboslute how create part of parent div

.val used value property of <input>s, value of selectedindex alternative of <select>s, et. al.

i'm not sure want, think mean utilize .html instead.

javascript jquery

osx - Oracle virtual box acces host and host vpn -



osx - Oracle virtual box acces host and host vpn -

i have oracle virtualbox running on macbook osx 10.8.2. have windows 8 vm. accomplish 2 things:

access vm webserver running host access vm webservers of company. can access these host vpn, can access hosts vm via vpn running on host ?

i tried bridged, host-ony adapters didn't trick far.

regards, marc

bridge adapter should work. how trying access vms ? suppose ip dynamic each time seek host name.

osx networking virtualbox

c++ - The variable answer is being used without being initialized? -



c++ - The variable answer is being used without being initialized? -

any help? when set 2 numbers in, says reply not beingness initialized...?

#include <iostream> using namespace std; int main() { int num; int num2; int working; int answer; int uchoice; int work( int one, int two, int todo ); cout << "welcome basic mini-calculator!" << endl; { cout << endl << "what want do?" << endl; cout << "1) add" << endl; cout << "2) subtract" << endl; cout << "3) multiply" << endl; cout << "4) divide" << endl; cout << endl << "waiting input... (enter number): "; cin >> uchoice; cout << endl; } while( uchoice != 1 && uchoice != 2 && uchoice != 3 && uchoice != 4 ); switch ( uchoice ) { case 1: cout << endl << "you chose addition." << endl; cout << "enter number: "; cin >> num; cout << "enter number: "; cin >> num2; working = num + num2; cout << "your reply is: " << answer; break; case 2: cout << endl << "you chose subtraction." << endl; cout << "enter number: "; cin >> num; cout << "enter number: "; cin >> num2; working = num - num2; cout << "your reply is: " << answer; break; case 3: cout << endl << "you chose multiplication." << endl; cout << "enter number: "; cin >> num; cout << "enter number: "; cin >> num2; working = num * num2; cout << "your reply is: " << answer; break; case 4: cout << endl << "you chose division." << endl; cout << "enter number: "; cin >> num; cout << "enter number: "; cin >> num2; working = num / num2; cout << "your reply is: " << answer; break; homecoming 0; } }

it that. declare answer:

int answer;

then utilize many times without initializing or assigning values it:

cout << "your reply is: " << answer;

c++

Problems with pointers in C. The same pointer for different things -



Problems with pointers in C. The same pointer for different things -

i have next c code:

int main(int argc, char *argv[]) { int n = argc - 1; int array[n]; int m[n][n]; int = 0; for(i = 1; i<=n;i++) { array[i] = atoi(argv[i]); printf("%d\n",array[i]); } printf("array[4] = %d\n",array[4]); for(i = 1; i<=n;i++) { m[i][i] = 0; printf("address of m[i][i] = %p\n",&m[i][i]); } printf("value of array[4] =%d pointer = %p\n",array[4],&array[4]); for(i=1;i<=n;i++) printf("after %d\n",array[i]); homecoming 0; }

if run next command: "./program 30 35 15 5 10 20 15" output is:

30 35 15 5 10 20 25 array[4] = 5 address of m[i][i] = 0xbf93070c address of m[i][i] = 0xbf93072c address of m[i][i] = 0xbf93074c address of m[i][i] = 0xbf93076c address of m[i][i] = 0xbf93078c address of m[i][i] = 0xbf9307ac address of m[i][i] = 0xbf9307cc value of array[4] =0 pointer = 0xbf9307cc after 30 after 35 after 15 after 0 after 10 after 20 after 25

notice how array[4] has same pointer m[n][n]. , don't understand how possible. wrong code. why array[4] = m[n][n]?

your loops wrong, arrays in c zero-based. meaning first element a[0] , lastly a[n-1] n size of array.

this:

for(i = 1; <= n; i++)

should this:

for(i = 0; < n; i++)

otherwise overstep array boundries.

as side note, using vla didn't specify c99 tag. sure know doing.

c pointers

delphi - Is PChar('') guaranteed to be a pointer to #0 (not nil)? -



delphi - Is PChar('') guaranteed to be a pointer to #0 (not nil)? -

i understand in delphi, empty string (ansistring or widestring) can represented nil pointer, or pointer actual empty string.

by experiment i've shown in delphi xe2 (with particular compiler settings) pchar('') <> nil. guaranteed, or might alter in future version, or dependent on compiler setting?

i'm having crisis of confidence. if can give me definitive reply i'd grateful.

yes. type casts string literals pchar never null pointers. type casts strings of same character type pchar won't null, either. (string pchar, ansistring pansichar, etc.)

type casts of other things pchar may null, though. (pointer pchar, ansistring pwidechar, etc.)

the documentation covers in mixing delphi strings , null-terminated strings section of string types topic:

you can cast unicodestring or ansistring string null-terminated string. next rules apply:

if s unicodestring, pchar(s) casts s null-terminated string; returns pointer first character in s. such casts used windows api. example, if str1 , str2 unicodestring, phone call win32 api messagebox function this: messagebox(0, pchar(str1), pchar(str2), mb_ok);. utilize pansichar(s) if s ansistring. you can utilize pointer(s) cast string untyped pointer. if s empty, typecast returns nil. pchar(s) returns pointer memory block; if s empty, pointer #0 returned. when cast unicodestring or ansistring variable pointer, pointer remains valid until variable assigned new value or goes out of scope. if cast other string look pointer, pointer valid within statement typecast performed. when cast unicodestring or ansistring look pointer, pointer should considered read-only. can safely utilize pointer modify string when of next conditions satisfied: the look cast unicodestring or ansistring variable. the string not empty. the string unique - is, has reference count of one. guarantee string unique, phone call setlength, setstring, or uniquestring procedures. the string has not been modified since typecast made. the characters modified within string. careful not utilize out-of-range index on pointer.

the same rules apply when mixing widestring values pwidechar values.

delphi null string null-terminated pchar

android - SherlockFragmentActivity java.lang.NoSuchFieldError when setting content view at the beginning -



android - SherlockFragmentActivity java.lang.NoSuchFieldError when setting content view at the beginning -

when starting activity, i'm retrieving next error:

02-14 09:51:30.898: v/violazioniactivity(7510): oncreate before 2130903076 02-14 09:51:30.913: d/dalvikvm(7510): dexopt: couldn't find static field lit/helian/violazioni/r$id;.btn1 02-14 09:51:30.913: w/dalvikvm(7510): vfy: unable resolve static field 6831 (btn1) in lit/helian/violazioni/r$id; 02-14 09:51:30.913: d/dalvikvm(7510): vfy: replacing opcode 0x60 @ 0x0015 02-14 09:51:30.913: d/dalvikvm(7510): dexopt: couldn't find static field lit/helian/violazioni/r$id;.btn2 02-14 09:51:30.913: i/dalvikvm(7510): dexopt: unable optimize static field ref 0x1ab0 @ 0x30 in lit/helian/violazioni/fe/ui/violazionidashboardfragment;.oncreateview 02-13 18:14:32.565: e/androidruntime(26290): fatal exception: main 02-13 18:14:32.565: e/androidruntime(26290): java.lang.nosuchfielderror: it.helian.violazioni.r$id.btn1 02-13 18:14:32.565: e/androidruntime(26290): @ it.helian.violazioni.fe.ui.violazionidashboardfragment.oncreateview(violazionidashboardfragment.java:38) 02-13 18:14:32.565: e/androidruntime(26290): @ android.support.v4.app.fragmentmanagerimpl.movetostate(fragmentmanager.java:846) 02-13 18:14:32.565: e/androidruntime(26290): @ android.support.v4.app.fragmentmanagerimpl.movetostate(fragmentmanager.java:1061) 02-13 18:14:32.565: e/androidruntime(26290): @ android.support.v4.app.fragmentmanagerimpl.addfragment(fragmentmanager.java:1160) 02-13 18:14:32.565: e/androidruntime(26290): @ android.support.v4.app.fragmentactivity.oncreateview(fragmentactivity.java:272) 02-13 18:14:32.565: e/androidruntime(26290): @ android.view.layoutinflater.createviewfromtag(layoutinflater.java:669)

main activity

bundle it.helian.violazioni.be.activity; import it.helian.violazioni.r; import android.os.bundle; import android.util.log; import com.actionbarsherlock.app.sherlockfragmentactivity; import com.googlecode.androidannotations.annotations.eactivity; //@eactivity(resname="activity_violazioni") @eactivity public class violazioniactivity extends sherlockfragmentactivity { public static final string tag = "violazioniactivity"; @override public void oncreate(bundle savedinstancestate) { log.v(tag, "oncreate before " + r.layout.activity_violazioni); super.oncreate(savedinstancestate); setcontentview(r.layout.activity_violazioni); log.v(tag, "oncreate after"); } }

r.layout.activity_violazioni

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/home_root" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <fragment android:id="@+id/fragment_dashboardz" android:name="it.helian.violazioni.fe.ui.violazionidashboardfragment" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" />

it.helian.violazioni.fe.ui.violazionidashboardfragment

public class violazionidashboardfragment extends sherlockfragment { @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { system.out.println("check 2a"); view root = inflater.inflate(r.layout.main_menu, container); system.out.println("check 2b"); btn1 = (mainbutton) root.findviewbyid(r.id.btn1); system.out.println("check 3"); btn1.setonclicklistener( new view.onclicklistener() { public void onclick(view view) { firetrackerevent(event_click_classica); } }); btn2 =(mainbutton) root.findviewbyid(r.id.btn2); btn2.setonclicklistener( new view.onclicklistener() { public void onclick(view view) { firetrackerevent(event_click_classica_anpr); } }); }

main_menu.xml

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:padding="1dp" android:weightsum="101" > <linearlayout android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="10" /> <linearlayout android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="27" android:orientation="horizontal" android:weightsum="10" > <it.helian.violazioni.fe.ui.mainbutton android:id="@+id/btn1" android:layout_width="0dp" android:layout_height="fill_parent" android:layout_margin="1dp" android:layout_weight="5" /> <it.helian.violazioni.fe.ui.mainbutton android:id="@+id/btn2" android:layout_width="0dp" android:layout_height="fill_parent" android:layout_margin="1dp" android:layout_weight="5" /> </linearlayout> <linearlayout android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="10" />

if need farther details, write them down, seek help much possible!

thank in advance

regards,

luca

android exception view actionbarsherlock layout-inflater

wordpress - PHP: __call not working properly -



wordpress - PHP: __call not working properly -

i'm having problem creating class called api_widgets in wordpress using magic __call function. if simple rename file derp.php , class api_derp works without problems.

the next illustration has been stripped of unimportant issue (so if there error other specific fatal error specified in 3rd code block, ignore it).

please maintain in mind know core.php or api class' __call works, renaming widgets.php or invoking class works fine.

core.php:

class api { function __call( $method, $args ) { $rmethod = "api_{$method}"; if ( !class_exists( $rmethod ) ) { $lmethod = strtolower( $method ); require_once( "{$lmethod}.php" ); } homecoming new $rmethod( $args ); } }

widgets.php:

class api_widgets { private $widgets = array(); function add( $widgets ) { if ( is_array( $widgets ) ) { foreach ( $widgets $widget ) { if ( !in_array( $widget, $this->widgets ) ) $this->widgets[] = $widget; } } else $this->widgets[] = $widgets; } }

api.php:

$api = new api(); $widgets = $api->widgets(); // fatal error: class 'api_widgets' not found in /home4/goldencr/public_html/wp-content/plugins/minecraft-api/api/core.php on line 25 //$widgets->add( 'some_widget' );

extending comment:

though not hinted @ question, seems may not included widgets.php. seek utilize absolute path prepare that:

require_once( __dir__.directory_separator.$lmethod.".php" );

php wordpress callback naming magic-methods

Segmentation Fault in C program that is doing a binary search of an array -



Segmentation Fault in C program that is doing a binary search of an array -

in c program, doing binary search of array read in data.txt

first trying scan in data.txt array sec using insertion sort algorithm sort 3rd doing binary search of array. new c , have no thought code gone wrong, give thanks help in letting me know doing incorrect.

#include <stdio.h> #include <stdint.h> #include <stdlib.h> int main () { int v, t, low, high, mid, search; int n = 20, array[20]; int p = 0; file *infile; infile = fopen(“data.txt”,”r”); while(!feof(infile)) { fscanf(infile,”%d”, &array[p]); p++; } (p = 0; p < n; p++) { scanf("%d", &array[p]); } (p = 1 ; p <= n - 1; p++) { v = p; while ( v > 0 && array[v] < array[v-1]) { t = array[v]; array[v] = array[v-1]; array[v-1] = t; v--; } } (p = 0; p <= n - 1; p++) { printf("%d\n", array[p]); printf("please come in value (-1 = done)>\n"); scanf("%d",&search); low = 0; high = n - 1; mid = (low+high)/2; while( low <= high ) { if ( array[mid] < search ) low = mid + 1; else if ( array[mid] == search ) { printf("%d located @ %d in array.\n", search, mid+1); break; } else high = mid - 1; mid = (low + high)/2; } if ( low > high ) printf("-1\n"); homecoming 0; }

1). initialize n value 2). after insertion sort (i guess) there printf print array. add together braces after printf. if u dont programme keeps running(unless come in char breaks prog) may work cause returning before can loop still major problem..

c arrays sorting binary segmentation-fault

android source - Add gapps to custom rom? -



android source - Add gapps to custom rom? -

i new rom development, managed build custom rom galaxy nexus. dont have gapps.

i wondering how can incorporate gapps in build without having flash .zip file?

the apps not open source , prebuilt apk.

find apk files google apps include. re-create each 1 under directory /system/app/ , chmod 644 (change permissions rwrr). recompile rom , flash you'd like.

android-source rom

proxy - Squid gives "The requested URL could not be retrieved" on particular request -



proxy - Squid gives "The requested URL could not be retrieved" on particular request -

i have server has net connection (1) , 1 hasn't (2). on (1) have squid server config:

acl manager proto cache_object acl localhost src 127.0.0.1/32 ::1 acl to_localhost dst 127.0.0.0/8 0.0.0.0/32 ::1 acl portal1 src 192.168.153.40/32 acl mediation1 src 172.21.78.138/32 acl mediation2 src 172.21.78.139/32 acl ssl_ports port 443 acl safe_ports port 80 # http acl safe_ports port 21 # ftp acl safe_ports port 443 # https acl connect method connect http_access allow manager localhost http_access deny manager http_access deny !safe_ports http_access deny connect !ssl_ports http_access allow mediation1 http_access allow mediation2 http_access allow portal1 http_access allow localhost http_access deny http_port 3128 transparent coredump_dir /var/spool/squid refresh_pattern ^ftp: 1440 20% 10080 refresh_pattern ^gopher: 1440 0% 1440 refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 refresh_pattern . 0 20% 4320 visible_hostname "webcol-ctip01" cache deny request_body_max_size 10 mb client_request_buffer_max_size 20 mb request_header_max_size 10 mb

on (2) have complex application requires send info via post external host. able connect proxy:

# export http_proxy=http://192.168.153.40:3128 # wget -o - http://google.com --2013-02-15 21:20:55-- http://google.com/ connecting 192.168.153.40:3128... connected. proxy request sent, awaiting response... 301 moved permanently location: http://www.google.com/ [following] --2013-02-15 21:20:55-- http://www.google.com/ connecting 192.168.153.40:3128... connected. proxy request sent, awaiting response... 302 moved temporarily location: http://www.google.ru/ [following] --2013-02-15 21:20:55-- http://www.google.ru/ connecting 192.168.153.40:3128... connected. proxy request sent, awaiting response... 200 ok length: unspecified [text/html] saving to: “stdout” ...etc...

but specific request i'm sending in application gives me error. here reproduced error curl:

curl -k --request post --header "content-type: text/xml" --data @req.xml http://some-domain.webex.com/wbxserv...iew/xmlservice

invalid request error encountered while trying process request: post /wbxservice/preview/xmlservice http/1.1 user-agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 nss/3.13.1.0 zlib/1.2.3 libidn/1.18 libssh2/1.2.2 host: some-domain.webex.com accept: */* proxy-connection: keep-alive content-type: text/xml content-length: 1510 expect: 100-continue possible problems are: missing or unknown request method. missing url. missing http identifier (http/1.0). request large. content-length missing post or set requests. illegal character in hostname; underscores not allowed. http/1.1 "expect:" feature beingness asked http/1.0 software. cache administrator root.

meanwhile in access log:

1360949609.433 0 172.21.78.138 none/417 4317 post http://some-domain.webex.com/wbxserv...iew/xmlservice - none/- text/html

os centos 6.3 x64 & squid 3.1.10

what missing here?

proxy squid

c# - Has IQueryable provider to preserve order? -



c# - Has IQueryable provider to preserve order? -

i want create custom iqueryable provider.

has iqueryable implementation preserve order of source elements?

for exemple, can (new [] { 1, 2, 3 }).asmyqueriable().select(x => x).toarray() homecoming 3, 2, 1?

technically, queryable can whatever feels like. iqueryable interface, there no constructor , there no contract must follow in regard -- queryable thing can queried via specific methods, , origin state not covered part of interface contract. extension method's documentation, however, should indicate whether order of input sequence retained returned iqueryable object.

of course, if calls .orderby() on instance of queryable, expected reorder elements accordingly. but, if developer not phone call .orderby() free homecoming elements in whatever order like.

c# linq iqueryable

sql - How to find out data from more than one tables in MYSQL -



sql - How to find out data from more than one tables in MYSQL -

i working on mysql based project. need find out info more 1 table. have searched , found solution like

select * table_1, table_2 (condition)

but such solution fine few tables,and have 57 tables in database. please allow me know solution.

thanks in advance.

sounds want join tables. e.g.:

select * table1 inner bring together table2 on table1.table1id = table2.table1id left bring together table3 on table2.table2id = table3.table2id;

unfortunately if want info 57 tables, need bring together 57 of them.

the syntax have used (ansi 89), while work best avoided (i believe there times when oracle optimise these better), ansi 92 joins less prone user error, , (to people) more legible because bring together status comes after table. aaron bertrand has written good article on reasons utilize ansi 92 syntax on ansi 89.

mysql sql

c# - Not slowing down a loop of tasks, and know when result is returned -



c# - Not slowing down a loop of tasks, and know when result is returned -

task<string> runlist(int client) { homecoming pages[client]; } private async void form1_doubleclick(object sender, eventargs e) { (int x = 0; x < listbox1.items.count; x++) { runlist(x); } }

this fly through loop of tasks, how know when results in without compromising speed of loop?

you can await on result of whenall ensure of tasks have completed @ point in code. (it's of import not utilize waitall here, block ui thread.)

private async void form1_doubleclick(object sender, eventargs e) { var tasks = new list<task<string>>(); (int x = 0; x < listbox1.items.count; x++) { tasks.add(runlist(x)); } await task.whenall(tasks); }

the basic thought here start tasks before calling await on them. here simpler illustration 2 tasks:

await task.delay(1000); await task.delay(1000);

this perform first task , then sec task.

var task1 = task.delay(1000); var task2 = task.delay(1000); await task1; await task2;

this start both tasks , go on on after both tasks have finished, allowing run concurrently.

c# task-parallel-library

Eclipse : Whether to select Local Or Shared File during Remote Debugging -



Eclipse : Whether to select Local Or Shared File during Remote Debugging -

i have made code changes , deployed code jetty server located remotely . accessed application through browser , trying debug application .

please tell me whether need select local file or shared file eclipse debug configurations .

please see screen shot here .

the alternative shown in screenshot not help automatically code deployed remote jetty.

the alternative allows share launch configuration (remote java application - managewatchlistcall) in eclipse workspace. allow checkin launch configuration in versioning command scheme colleagues automatically sme remote java application launch configuration.

in order new code remote server, there 2 options :

redeploy application on remote server. hotdeploy pieces of code remote supported (if server supports it) use hotswap bug fixing (works little fixes) (*)

(*) if running java virtual machine (jvm) v1.4 or higher, eclipse supports feature called hotswap bug fixing (not available in jvm v1.3 or lower). allows changing of source code during debugger session, improve exiting application, changing code, recompiling, starting debugging session. utilize function, alter code in editor , resume debugging.

eclipse

c# - What is the best way to store and play back XML nodes? -



c# - What is the best way to store and play back XML nodes? -

i have xml looks (highly simplified):

<?xml version="1.0"?> <example> <shortcuts> <shortcut name="shortcut1"> <property name="name1" value="value1" /> <property name="name2" value="value2" /> </shortcut> </shortcuts> <data> <datum name="datum1"> <property name="name1" value="value1" /> <property name="name2" value="value2" /> </datum> <datum name="datum2"> <shortcutref name="shortcut1" /> </datum> <datum name="datum3"> <shortcutref name="shortcut1" /> <property name="name3" value="value3" /> </datum> </data> </example>

as can see, structured such "shortcuts" can defined consist of 1 or more properties. info can described explicitly properties, or 1 or more shortcuts, or mix of both (and there no specific order).

i want parse xmlreader (xmldocument easier won't work here because xml file large). thought way store xml subtrees of each shortcut in dictionary keyed shortcut names, unique. when referenced, read through subtree xmlreader rather main one. subtree xmlreader must still linked main xmlreader because xml comes out not expect. here code:

using(xmlreader xml = xmlreader.create("example.xml")) { dictionary<string, xmlreader> shortcuts = new dictionary<string, xmlreader>(); xml.readtodescendant("shortcuts"); xml.readtodescendant("shortcut"); { shortcuts.add(xml.getattribute("name"), xml.readsubtree()); } while(xml.readtonextsibling("shortcut")); xml.readtofollowing("data"); while(xml.readtofollowing("datum")) { console.writeline(xml.getattribute("name")); xmlreader datum = xml.readsubtree(); while(datum.read()) { if(datum.name == "property") { console.writeline(datum.getattribute("name") + ':' + datum.getattribute("value")); } else if(datum.name == "shortcutref") { xmlreader shortcut_ref = shortcuts[datum.getattribute("name")]; while(shortcut_ref.readtofollowing("property")) { console.writeline(shortcut_ref.getattribute("name") + ':' + shortcut_ref.getattribute("value")); } } } } }

what best way parse xml structured in way?

it’s not exclusively clear want – since utilize words “play back” guessing don’t need store values xml nodes (data / datum) in memory (you can discard them after use), need cache shortcut properties can re-iterate through them when referenced… had it, instead of storing xml nodes, store objects instead in dictionary.

public class property { public string name { get; set; } public string value { get; set; } } public class shortcut { public list<property> properties = new list<property>(); } class programme { static void main(string[] args) { filestream fs = new filestream(@"c:\temp\example.xml", filemode.open, fileaccess.read); xmltextreader reader = new xmltextreader(fs); dictionary<string, shortcut> shortcutdictionary = new dictionary<string, shortcut>(); while (reader.read()) { if (reader.nodetype == xmlnodetype.element && reader.localname == "shortcuts") { while (reader.read()) { if (reader.nodetype == xmlnodetype.element && reader.localname == "shortcut") { shortcut shortcut = new shortcut(); shortcutdictionary.add(reader.getattribute("name"), shortcut); while (reader.read()) { if (reader.nodetype == xmlnodetype.element && reader.localname == "property") shortcut.properties.add(new property() { name = reader.getattribute("name"), value = reader.getattribute("value") }); else if (reader.nodetype == xmlnodetype.endelement && reader.localname == "shortcut") break; } } else if (reader.nodetype == xmlnodetype.endelement && reader.localname == "shortcuts") break; } } if (reader.nodetype == xmlnodetype.element && reader.localname == "data") { while (reader.read()) { if (reader.nodetype == xmlnodetype.element && reader.localname == "datum") { while (reader.read()) { if (reader.nodetype == xmlnodetype.element && reader.localname == "property") { console.writeline(reader.getattribute("name") + ':' + reader.getattribute("value")); } else if (reader.nodetype == xmlnodetype.element && reader.localname == "shortcutref") { foreach (property property in shortcutdictionary[reader.getattribute("name")].properties) console.writeline(property.name + ':' + property.value); } else if (reader.nodetype == xmlnodetype.endelement && reader.localname == "datum") break; } } else if (reader.nodetype == xmlnodetype.endelement && reader.localname == "data") break; } } } reader.close(); fs.close(); } }

otherwise, if not it, trying access serial info in random access manner. best bet convert/save info database. sqlite it.

c# .net xml memory-management xmlreader

php - Show products after selecting a brand -



php - Show products after selecting a brand -

this question has reply here:

dropdown select based on database entries 4 answers

i'm wondering how create when select brand in drop downwards menu update other drop downwards menu prodcuts brand

example:

so when select brand in "make" section has set products brand in "make" section

http://i48.tinypic.com/rck903.jpg

thanks if helps me.

if want without postback, have alter event of brand's dropdown , send ajax request server products according brand id , in success function fill product dropdown json output

example done jquery:

$('#brand_dd').change(function(){ $.post( 'url', {'brand_id': $(this).val()}, function(data){ //fill drop here } }

php mysql database

C++ Help on Class Design Exception Handling -



C++ Help on Class Design Exception Handling -

i'm learning c++ , practicing knowledge implementing simple addressbook application. i started entry class , addressbook class implements stl map access entries lastly names of persons. arrived @ next code:

entry addressbook::get_by_last_name(string last_name){ if(this->addr_map.count(last_name) != 0){ //what can here? } else { homecoming addr_map[last_name]; }

in scripting languages homecoming -1, error message(a list in python) indicate function failed. don't want throw exception, because it's part of application logic. calling class should able react request printing on console or opening message box. thought implementing scripting languae approach in c++ introducing kind of invalid state class entry. isn't bad practice in c++? whole class design not appropriate? appreciate help. please maintain in mind i'm still learning c++.

some quick notes code:

if(this->addr_map.count(last_name) != 0){ //what can here?

you wanted other way:

if(this->addr_map.count(last_name) == 0){ //handle error

but real problem lies here:

return addr_map[last_name];

two things note here:

the operator[] map can 2 things: if element exists, returns it; if element doesn't exist, creaets new (key,value) pair specified key , value's default constructor. not wanted. however, if if statement before have been right way, latter never happen because knowthe key exists before hand. in calling count() before, tell map seek , find element. calling operator[], telling map find again. so, you're doing twice work retrieve single value.

a improve (faster) way involves iterators, , find method:

yourmap::iterator = addr_map.find(last_name); //find element (once) if (it == addr_map.end()) //element not found { //handle error } homecoming *it.second; //return element

now, back problem @ hand. if last_name not found? other answers noted:

simplest solution homecoming pointer (null if not found) use boost::optional. simply homecoming yourmap::iterator seems trying "hide" map user of addressbook that's bad idea. throw exception. wait, you'll have first check calling method 'safe' (or handle exception when appropriate). check requires boolean method lastnameexists have called before calling get_by_last_name. of course of study we'er square 1. we're performing 2 find operations retrieve single value. it's safe, if you're doing lot of calls get_by_last_name potentially place optimize different solution (besides, arguably exception not constructive: what's wrong searching isn't there, huh?). create dummy fellow member entryindicating not real entry poor design (unmanageable, counter intuitive, wasteful - name it).

as can see, first 2 solutions far preferable.

c++ class exception design exception-handling

SQL Replace string in path -



SQL Replace string in path -

how replace before "test" blank? amount of subfolders in front end of "test" may vary.

c:\aaa\bbb\test\ccc\ddd

i be:

test\ccc\ddd

solution in mssql, if you're using rdmbs i'm sure have equivalent functions patindex/substring.

declare @path varchar(8000) ,@find varchar(128) set @path = 'c:\aaa\bbb\test\ccc\ddd' set @find = 'test\' select substring(@path,patindex('%'+@find+'%',@path),len(@path))

http://sqlfiddle.com/#!3/d41d8/8576

sql

javascript - Calling a function with same name in another JS file -



javascript - Calling a function with same name in another JS file -

i'm bit confused here... if have 1 .js file function this:

function mymain() { var count=0; count++; myhelper(count); alert(count); } function myhelper(count) { alert(count); count++; }

can still phone call method myhelper() on other .js file? or there other way can pass count variable 1 function called other .js file. have thought regarding one? thanks!

when both script files included in same page, run in same global javascript context, 2 names overwrite each other. no, can not have 2 functions in different .js files same name , access both of them you've written it.

the simplest solution rename 1 of functions.

a improve solution write javascript modularly namespaces, each script file adds minimum possible (preferably 1) objects global scope avoid naming conflicts between separate scripts.

there number of ways in javascript. simplest way define single object in each file:

// in first script file var modulename = { mymain: function () { var count=0; count++; myhelper(count); alert(count); } myhelper: function (count) { alert(count); count++; } } // in later script file: modulename.mymain();

a more popular method utilize self-evaluating function, similar following:

(function (window, undefined) { // code, defining various functions, etc. function mymain() { ... } function myhelper(count) { ... } // more code... // list functions want other scripts access window.modulename = { myhelper: myhelper, mymain: mymain }; })(window)

javascript function variables count

mysql - restore backup mysqldump php -



mysql - restore backup mysqldump php -

i can't seem restore database backup in php. code

<?php $host = 'localhost'; $user = 'root'; $pass = ' '; $dbname = 'itravel'; date_default_timezone_set('asia/kuala_lumpur'); $date = date('y_m_d'); if(isset($_post['backup'])) { $backup = "c:/xampp/mysql/bin/mysqldump --opt -h $host -u $user $dbname > itravel_backup_$date.sql"; system($backup); } if(isset($_post['restore'])) { $restore = "c:/xampp/mysql/bin/mysqldump --opt -h $host -u $user $dbname < itravel_backup_$date.sql"; system($restore); } ?>

backup successful restore failure. help me guys!

updated code with

<?php $host = 'localhost'; $user = 'root'; $pass = ' '; $dbname = 'itravel'; //date_default_timezone_set('asia/kuala_lumpur'); //$date = date('y_m_d'); $backup_name = 'itravel_backup.sql'; if(isset($_post['backup'])) { $backup = "c:/xampp/mysql/bin/mysqldump --opt -h $host -u $user $dbname > $backup_name"; system($backup); } if(isset($_post['restore'])) { //$restore = "c:/xampp/mysql/bin/mysqldump --opt -h $host -u $user $dbname < itravel_backup_$date.sql"; //system($restore); $restore = "c:/xampp/mysql/bin/mysql --opt -h $host -u $user $dbname < $backup_name"; system($restore); } ?>

but still not working

you need utilize mysql binary restore, not mysqldump.

php mysql mysqldump

java - Can the IDREF attribute have only local ID value? -



java - Can the IDREF attribute have only local ID value? -

i have such element

<xsd:element name="car" type="cartype"/> <xsd:complextype name="cartype"> <xsd:complexcontent> <xsd:extension base="basictype"> <xsd:attribute name="motor" type="xsd:idref" use="required"/> </xsd:extension> </xsd:complexcontent> </xsd:complextype>

when motor element in current document, work fine.

<car id="car1" motor="motor1"/> <motor id="motor1"/>

but when import motor element file

<beans:bean:import resource="motors.conf.xml"/>

intellij thought invalid id reference, , when run programme exception

there no id/idref binding idref

may i'm doing wrong? or may xsd:idref equals ref local, , can't utilize import?

i right, xsd:idref equals ref local.

about xsd:idref msdn creating valid id, idref...

and can see why equals here -

<xsd:element name="ref"> <xsd:annotation> <xsd:documentation><![cdata[ defines reference bean in mill or external mill (parent or included factory). ]]></xsd:documentation> </xsd:annotation> <xsd:complextype> <xsd:complexcontent> <xsd:restriction base="xsd:anytype"> <xsd:attribute name="bean" type="xsd:string"> <xsd:annotation> <xsd:documentation><![cdata[ name of referenced bean. ]]></xsd:documentation> </xsd:annotation> </xsd:attribute> **<xsd:attribute name="local" type="xsd:idref">** <xsd:annotation> <xsd:documentation><![cdata[ name of referenced bean. value must bean id , can checked xml parser. hence preferred technique referencing beans within same bean mill xml file. ]]></xsd:documentation> </xsd:annotation> </xsd:attribute> <xsd:attribute name="parent" type="xsd:string"> <xsd:annotation> <xsd:documentation><![cdata[ name of referenced bean in parent factory. ]]></xsd:documentation> </xsd:annotation> </xsd:attribute> </xsd:restriction> </xsd:complexcontent> </xsd:complextype> </xsd:element>

it description of element bean element ref. , know, can utilize <ref local> elements in current xml document.

java spring import xsd

javascript - js Search String and get matched elements -



javascript - js Search String and get matched elements -

i want inquire best way search string , matched element?

//i want similar or matched element , index of it. //search key ward var key = 'pap'; <ul> <li>papa</li> <li>mama</li> </ul>

my thought utilize $.each , match text of each, believe should wrong way. however, couldn't find references net question.

thank much.

use :contains selector

$('*:contains("'+key+'"):last')

to find exact match whole text in element utilize this

$.fn.exactmatch = function (key) { var p = $(this).find(':contains("' + key + '"):last'); if (p.text() == key) { p.css('background', 'yellow'); } else { //not exact match function if wanted } }

to utilize function this

$(el).exactmatch(key);

javascript jquery string search match

collapse - Collapsible bootstrap, show first element -



collapse - Collapsible bootstrap, show first element -

i want show first element of collapsible accordion. did research in net in vain

class="snippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha256-7s5udgw3ahqw6xtjmnntr+obrjulgknjeo78p4b0yrw= sha512-nno+ycheyn0smmxsswnf/onx6/kwjuztlnzbjaukhtk0c+zt+q5jocx0ufhxq6rjr9jg6es8gpud2uzcydlqsw==" crossorigin="anonymous"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha256-kxn5pumvxcw+dayznun+drmdg1ifl3agk0p/pqt9kao= sha512-2e8qq0etcfwri4hjbzqia3uoyfk6tbnyg+qsaibzlyw9xf3swzhn/lxe9fth1u45dppf07yj94ksuhhwe4yk1a==" crossorigin="anonymous"></script> <div class="accordion" id="accordion2"> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseone" > aller au dossier personnel d'un agent </a> </div> <div id="collapseone" class="accordion-body collapse" style="height: 0px; "> <div class="accordion-inner"> <form action="gotoagent.do" method="post"> <p align="center"> <input type="hidden" value="identite" name="retour"> <label for="nomprenom" > entrer le nom complet de l'agent: </label> <input type="text" name="nomprenom" class="typeahead" /> <br> <input type="submit" value="appliquer" class="btn btn-info" /> </form> </div> </div> </div> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapsetwo"> ajout d'un nouveau fonctionnaire </a> </div> <div id="collapsetwo" class="accordion-body collapse"> <div class="accordion-inner"> <!-- lorem --> </div> </div> </div> </div>

i don't think you've got html need accordion work unless haven't pasted above.

the bootstrap docs first illustration has first element set open:

http://twitter.github.com/bootstrap/javascript.html#collapse

i think it's class "in" sets open initially.

<div class="accordion" id="accordion2"> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseone"> collapsible grouping item #1 </a> </div> <div id="collapseone" class="accordion-body collapse in"> <div class="accordion-inner"> anim pariatur cliche... </div> </div> </div> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapsetwo"> collapsible grouping item #2 </a> </div> <div id="collapsetwo" class="accordion-body collapse"> <div class="accordion-inner"> anim pariatur cliche... </div> </div> </div> </div>

twitter-bootstrap collapse bootstrap-accordion

c++ - A vector of pointers to objects that may or may not exist -



c++ - A vector of pointers to objects that may or may not exist -

here's problem: making game using sfml, , wanted have vector of sf::drawable* windowmanager.add(randomgamesprite), problem have want able have can delete randomgamesprite without having manually remove pointer window. there way have check see if object exists before trying draw it?

i using c++11, smart pointers haven't been much help in i've tried. tried using std::shared_ptr, keeps drawables alive.

you store weak_ptr<t> in vector. weak pointer not maintain object alive: if shared pointers object go out of scope, weak pointer automatically expire.

c++ pointers vector

sql server - How to get the "Generate Script" of a DB by T-SQL -



sql server - How to get the "Generate Script" of a DB by T-SQL -

i know how using sql management generate script create whole db in sql.

i need same script using t-sql.

anybody know how this?

if i'm not mistaken function of sql ide. replicate you'd have lot of introspection yourself. perhaps have utilize 3rd party tool?

to introspection need tables , views in information_schema , sys schemas determine capabilities of every object , script them yourself.

there help stored procedures sp_helptext may able utilise create job easier.

sql sql-server tsql

java - Implementing multiple Interfaces -



java - Implementing multiple Interfaces -

in interface 1 have method a , in interface 2 have method b. both methods implemented in class three. assign instance of 3 one, still can phone call method b of second?

even if possbile, correct?

assuming have this:

public interface { public void methoda(); } public interface b { public void methodb(); } public class c implements a,b { public void methoda(){...} public void methodb(){...} }

you should able this:

a = new c(); a.methoda();

but not this:

a.methodb()

on other hand, can this:

b b = new c(); b.methodb();

but not this:

b.methoda();

edit:

this because define object a of beingness instance of a. although using concrete class initialization (new c()), programming interface methods defined in interface visible.

java

user interface - How to create sidebar in GTK+3 (Python)? -



user interface - How to create sidebar in GTK+3 (Python)? -

i'm new gtk+3 (i utilize pygobject) , need create sidebar has construction this:

header 1 subheader 1 subheader 2 header 2 subheader 3 subheader 4

what examples can larn from? show me minimal working illustration of how utilize gtk.treeview , gtk.treemodel (not using gtk.builder())?

besides using xml file , gtk.builder() describe layout seems superior creating construction in python file, there seems much less documentation doing so.

my current ui description:

<?xml version="1.0" encoding="utf-8"?> <interface> <object class="gtkwindow" id="main-window"> <property name="title">applicationname</property> <signal name="delete-event" handler="ondeletewindow"/> <child> <object class="gtkbox" id="container"> <property name="orientation">horizontal</property> <child> <object class="gtktreeview" id="sidebar"> </object> </child> <child> <object class="gtkbox" id="right-container"> <property name="orientation">vertical</property> <child> <object class="gtkbuttonbox" id="top-buttonbox"> <child> <object class="gtkbutton" id="add-button"> <property name="label">add</property> </object> </child> <child> <object class="gtkbutton" id="delete-button"> <property name="label">delete</property> </object> </child> </object> </child> </object> </child> </object> </child> </object> </interface>

you should have @ gtktreeview , associated tree-like info model gtktreestore. python gtk+ 3.0 tutorial introduction.

user-interface gtk gtk3 pygobject

ruby on rails - Save one attribute for a row in active record -



ruby on rails - Save one attribute for a row in active record -

there 5 ways save new value attribute in activerecord. unfortunately 1 way work , not sure efficient way:

review = review.find(id) review.status = 'ok' review.save!

i started update method, unusual reason deleted review row

review = review.update(id, :status => 'ok) review.save!

any ideas?

the efficient way save new value attribute do:

review.update_attribute(id, :status => 'ok')

there no need phone call save method after because activerecord automatically saves value update_attribute method.

now, maintain in mind work if alter work if passes validations set on object.

check out link more info:

http://apidock.com/rails/activerecord/base/update/class

ruby-on-rails rails-activerecord

ios - What view is revealed when panning UITableViewCell? -



ios - What view is revealed when panning UITableViewCell? -

i panning uitableviewcell contentview in code below. know view exists behind uitableviewcell contentview beingness moved?

the reason inquire because want alter color of "revealed view". customize color underneath each tableviewcell when cell swiped. example, if left swipe 3rd row, see bluish behind cell. if left swipe 4th row, see greenish behind cell.

- (void)pangesturerecognizer:(uipangesturerecognizer *)recognizer { //... if ((recognizer.state == uigesturerecognizerstatebegan || recognizer.state == uigesturerecognizerstatechanged) && [recognizer numberoftouches] > 0) { cgpoint location1 = [recognizer locationoftouch:0 inview:self.tableview]; nsindexpath *indexpath = [self.tableview indexpathforrowatpoint:location1]; uitableviewcell *cell = [self.tableview cellforrowatindexpath:indexpath]; cgpoint translation = [recognizer translationinview:self.tableview]; cell.contentview.frame = cgrectoffset(cell.contentview.bounds, translation.x, 0); } //... }

one thing tried create uiview , add together cell behind contentview. works, not satisfaction. if set in code animate cell deletion uitableviewrowanimationleft, color of background move left along cell. makes sense because background view created moves along entire cell when animation moves cell out delete it. behavior want background color behind cell, not move when cell moved in deletion animation.

the next code how add together background view cell , set below contentview.

[cell.contentview setbackgroundcolor:[uicolor whitecolor]]; uiview *view = [[uiview alloc] initwithframe:cgrectmake(0, 0, 320, self.tableview.rowheight)]; view.backgroundcolor = [uicolor redcolor]; [cell addsubview:view]; [cell bringsubviewtofront:cell.contentview];

ah ha!

i found elegant , wonderful solution this. i'm jittering joy.

i added view right of cell.contentview background color want. when swipe cell, rightsideview gets pulled along looks it's view beingness revealed. (now if wanted set content in there, that's complication person... i'm not doing that) wanted have each cell able have different reveal color. yay! note, have create frame long (i.e., 500) swipe delete looks right.

here's code.

uilabel* label = [[uilabel alloc] initwithframe:cgrectmake(320, 0, 500, self.tableview.rowheight)]; label.backgroundcolor = [uicolor redcolor]; [cell.contentview addsubview:label];

ios uitableview swipe gestures

css - Website looks way different on smartphones even with media query -



css - Website looks way different on smartphones even with media query -

edit: i've managed tweak improve result setting viewport 0.25. still got awful stuff going on. actionbar example, set 100% , taking 70% of screen.

i've got big issue here.

im developing website, no big deal on it. gotta create responsive smartphones well.

well, i'm using media query this, , window resizer utilize exact width.

im using % values divs well, not height of course, width.

while i'm "emulating" on chrome, layout works fine, no problem @ all.

but when go test on galaxy s2 example, looks chunky. don't know can create same exact way.

http://www2.madeinweb.com.br/jobs/adc/prototype/html/

this home im working on right now. proper media query one:

@media screen , (min-width : 320px) , (max-width : 640px) {}

have tried adding -webkit-min-device-pixel-ratio: 1.5 or and (orientation : portrait). can find info on mobile pixel densities here: http://bjango.com/articles/min-device-pixel-ratio/

in case, if scroll down, see galaxy s2

css css3 media-queries

Typescript 0.8.2 - Compile on save with specified output file -



Typescript 0.8.2 - Compile on save with specified output file -

i'm trying configure typescript solution both compile-on-save (which have working fine) in add-on specifying output directory.

is possible? see in typescript targets file there's check see --out file specified. if is, compile-on-save disabled.

<typescriptcompileonsaveenabled condition="'$(typescriptenablecompileonsave)' != 'false' , '$(typescriptoutfile)' == ''">true</typescriptcompileonsaveenabled>

this not supported. there issue logged track at: http://typescript.codeplex.com/workitem/854

typescript

Spring upload form optional with optional file -



Spring upload form optional with optional file -

we creating profile page form optionally has profile pic on it. using spring 3.2

here form: -

<form:form id="editmember" modelattribute="memberajaxeditmodel" method="post" class="form-horizontal" enctype="multipart/form-data" > ... <form:input path="filedata" type="file"/> ... </form>

here controller method: -

@requestmapping(value = "/{id}", method = requestmethod.post) public string oneditpost(@pathvariable long id, @valid @modelattribute(memberajaxeditmodel.key) memberajaxeditmodel model, bindingresult result) throws servicerecoverableexception { .... }

here model

public class memberajaxeditmodel { ... private commonsmultipartfile filedata; ... }

it works fine if file submitted on form, there errors in bindingresult variable if form submitted without file.

here error: -

field error in object 'memberajaxeditmodel' on field 'filedata': rejected value []; codes [typemismatch.memberajaxeditmodel.filedata,typemismatch.filedata,typemismatch.org.springframework.web.multipart.commons.commonsmultipartfile,typemismatch]; arguments [org.springframework.context.support.defaultmessagesourceresolvable: codes [memberajaxeditmodel.filedata,filedata]; arguments []; default message [filedata]]; default message [failed convert property value of type 'java.lang.string' required type 'org.springframework.web.multipart.commons.commonsmultipartfile' property 'filedata'; nested exception java.lang.illegalstateexception: cannot convert value of type [java.lang.string] required type [org.springframework.web.multipart.commons.commonsmultipartfile] property 'filedata': no matching editors or conversion strategy found]

it turns out jquery form plugin sending empty string instead of spring expects - nil sent.

i solved problem using before submit remove filedata value if wasn't populated so: -

function beforesubmit(arr, $form, options){ var filedataindex = -1; $.each(arr, function(index, value) { if (value.name == "filedata"){ if (value.value.length == 0){ filedataindex = index; } } }); if (filedataindex != -1){ arr.remove(filedataindex); } }

i hope helps googlers same problem.

spring spring-mvc file-upload

excel - How to place Chart templates (.crtx) on a server -



excel - How to place Chart templates (.crtx) on a server -

i've got question regarding placement of chart templates on file server.

i want avoid having place chart template files locally on every pc. , update on pcs if there done changes.

i've found work if point "user template"-file location in word specific server location , have "chart" folder placed there. not solution since users utilize same normal.dotm then..

i've tried achive using "workgroup templates"-file location on server , have folder named "charts" chart templates. seems looks chart templates in "user template" file location, , not in "workgroup templates"-file location.

is there other solution this, it's not needed manually update chart templates localy on every pc?

when i've discussed kind of thing folks regarding updateable files of own add-ins, they've agreed login scripts pull downwards updated files or grouping policy force updated files out pair of reasonable alternatives.

excel ms-office powerpoint

Wrong date format C#, Oracle -



Wrong date format C#, Oracle -

i'm trying date in right format(dd/mm/yyyy). @ moment in format: mm-dd-yyyy hh24:mi:ss when alter dd/mm/yyyy, works in database(oracle). run in app exception: indexoutofrange @ :

this.infolist9.add(dr["start_rcv_datetime"].tostring());

please see code below.

public list<string> infolist = new list<string>(); private void populatelbldate() { conn.open(); string query; query = "select to_char(dg.start_rcv_datetime,'dd/mm/yyyy') dc_pallet dp, dc_pallet_stock dps , dc_grv dg , sku s ,prod_size ps,colour c ,purch_order_carton_sku pocs , dc_crane_instruc dci dps.pallet_id_no = '" + palletid.tostring() + "' , dp.pallet_id_no = dps.pallet_id_no , dg.dc_grv_id_no = dps.dc_grv_id_no , dg.order_no = dps.order_no , dg.company_id_no = dps.company_id_no , s.company_id_no = dps.company_id_no , s.company_id_no = dg.company_id_no , dps.company_id_no = c.company_id_no , dps.company_id_no = ps.company_id_no , s.prod_size_id_no = ps.prod_size_id_no , s.colour_id_no = c.colour_id_no , dps.company_id_no = ps.company_id_no , pocs.order_no = dps.order_no , pocs.carton_code = dps.carton_code , pocs.company_id_no = dps.company_id_no , pocs.sku_id_no = s.sku_id_no , dci.pallet_id_no(+) = dp.pallet_id_no"; oraclecommand cmd = new oraclecommand(query, conn); oracledatareader dr = cmd.executereader(); while (dr.read()) { this.infolist.add(dr["start_rcv_datetime"].tostring()); } dr.close(); conn.close(); } private void frminfo_load(object sender, eventargs e) { populatelbldate(); lbl1.text = this.infolist[0]; }

then have prev , next button well...

your indexoutofrange exception suggests immediate problem result set doesn't contain column of start_rcv_datetime - presumably because of to_char conversion.

don't deal strings @ database side @ all. fetch value datetime, , format @ client in whatever want to.

use dr.getdatetime fetch value, having removed to_char part query:

query = "select dg.start_rcv_datetime ..."; using (oraclecommand cmd = new oraclecommand(query, conn)) { using (oracledatareader dr = cmd.executereader()) { int datecolumn = dr.getordinal("start_rcv_datetime"); while (dr.read()) { datetime date = dr.getdatetime(0); // or whatever - consider cultural implications string text = date.tostring("dd/mm/yyyy"); infolist.add(text); } } }

(note using statements - should create sure clean database-related resources.)

c# oracle

rails raw sql example -



rails raw sql example -

how can convert code raw sql , utilize in rails? because when deploy code in heroku,there request timeout error.i think faster if utilize raw sql.

@payments = paymentdetail.joins(:project).order('payment_details.created_at desc') @payment_errors = paymenterror.joins(:project).order('payment_errors.created_at desc') @all_payments = (@payments + @payment_errors)

you can this:

sql = "select * ... sql query here" records_array = activerecord::base.connection.execute(sql)

records_array result of sql query in array can iterate through.

sql ruby-on-rails

php - mysql PDO multi parameter insert statement -



php - mysql PDO multi parameter insert statement -

i dont know wrong.. i've seen lot of different ways it, can 1 tell me hell wrong this.. throwing error "error: sqlstate[42000]: syntax error or access violation: 1064 have error in sql syntax; check manual corresponds mysql server version right syntax utilize near 'desc) values ('30.59','blue shirt','a cool bluish shirt')' @ line 1". have tried multiple ways , same result..

<?php $title = 'blue shirt'; $desc = 'a cool bluish shirt'; $price = 30.59; $user = 'foo'; $pass = 'bar'; try{ $conn = new pdo('mysql:host=examplehost;dbname=exampledb_name',$user,$pass); $conn->setattribute(pdo::attr_errmode, pdo::errmode_exception); if(!$conn){ echo"couldnt connect db"; }else { echo 'connected boss!!' . '<br>'; $stmt = $conn->prepare("insert 68_items (price, title, desc) values (:price,:title,:desc)"); if(!$stmt->execute(array( ':price' => $price, ':title' => $title, ':desc' => $desc)) ) { echo'statment failed'; }else { echo 'statment success, ' . $stmt->rowcount() . 'rows affected.'; } } } grab (pdoexception $e) { echo 'error: ' . $e->getmessage(); } ?>

desc reserved word in mysql should utilize backticks escape it:

"insert 68_items (price, title, `desc`) values (:price,:title,:desc)"

php mysql pdo

jsf - Expression language: Concat String with variable in method-call -



jsf - Expression language: Concat String with variable in method-call -

i have backingbean next method (signature):

public class sessionbean { ... public boolean subjectispermitted(final string permission); ... }

in jsf-template, want phone call method dynamically, this:

${sessionbean.subjectispermitted('company:manage:'company.id)}

well, concatenation within method-call throw com.sun.el.parser.parseexception. using "+" or "." concat string not help, too.

how concat string variable within el-method-call?

check other question:

combining string value of variable name of variable in el

according it, can use:

<c:set var="variable" value="company:manage:${company.id}" />

before:

${sessionbean.subjectispermitted(variable)}

and should work.

regards,

jsf

sql - Where can I find information on the sixth normal form -



sql - Where can I find information on the sixth normal form -

i looking info on how implement 6th normal form. have searched everywhere online without success. see illustration how how implemented , designed. help if there books or documentation on how implement it.

since you've searched everywhere, you've searched dba.stackexchange.com too... if did not, see 6th normal form, recomposition query, efficient implementation.

they refer chapter 7 of an introduction relational database theory (4th ed.) hugh darwen.

sql database database-design 6nf

gridview - Export to excel with browser localization - ASP.Net -



gridview - Export to excel with browser localization - ASP.Net -

i have gridview , exporting excel gridview below code.

response.clearcontent() response.addheader("content-disposition", "attachment; filename=excelshipments_" & datetime.now.ticks & ".xls") response.contenttype = "application/excel" dim swriter new stringwriter() dim htextwriter new htmltextwriter(swriter) dim hform new htmlform() ucshipmentlist.shipmentgrid.parent.controls.add(hform) hform.attributes("runat") = "server" hform.controls.add(ucshipmentlist.shipmentgrid) hform.rendercontrol(htextwriter) dim sbuilder new stringbuilder() sbuilder.append("<html xmlns:v=""urn:schemas-microsoft-com:vml"" xmlns:o=""urn:schemas-microsoft-com:office:office"" xmlns:x=""urn:schemas-microsoft-com:office:excel"" xmlns=""http://www.w3.org/tr/rec-html40""> <head><meta http-equiv=""content-type"" content=""text/html;charset=windows-1252""><!--[if gte mso 9]><xml><x:excelworkbook><x:excelworksheets><x:excelworksheet><x:name>exporttoexcel</x:name><x:worksheetoptions><x:panes></x:panes></x:worksheetoptions></x:excelworksheet></x:excelworksheets></x:excelworkbook></xml><![endif]--></head> <body>") sbuilder.append(swriter.tostring() & "</body></html>") response.write(sbuilder.tostring()) response.end()

i have dutch language in page default set hence grid displays on page right while doing export excel, shows exported in english. how can preserve language while exporting excel?

i utilize open xml sdk , create "real" excel document.

asp.net gridview localization export-to-excel

flex - Spark Datagrid with Splitted columns -



flex - Spark Datagrid with Splitted columns -

i'm trying figure out how can simple datagrid has splitted columns.

i need next layout:

+-------------------+ | destination | +--------+----------+ | dir 1 | dir 2 | +-------------------+

any thought how it?

you can utilize header renderer same. customized renderers can created.

flex datagrid flex4.5 flexbuilder

python - Twisted: How is Deferred called from EndPoint when using pyglet-twisted -



python - Twisted: How is Deferred called from EndPoint when using pyglet-twisted -

the code below taken twisted's documentation on amp (link). when callback added d, there's automatically "protocol" argument added , deferred automatically run when reactor.run() called.

def connect(): endpoint = tcp4clientendpoint(reactor, "127.0.0.1", 8750) mill = factory() factory.protocol = amp homecoming endpoint.connect(factory) d = connect() def connected(protocol): homecoming protocol.callremote( registeruser, username=u'alice' d.addcallback(connected) reactor.run()

in code, same, except i've been using pyglet-twisted (link) cocos2d can't phone call reactor.run() because reactor starts @ same time application.

if phone call reactor.run(), error saying reactor running.

if don't, deferred doesn't seem called.

i've been trying phone call reactor.calllater, reactor.callwhenrunning, both need argument. passing in none doesn't work.

so question is, how should create this deferred run without calling reactor.run().

thanks!

few of twisted's apis succeed without running reactor. reactor responsible doing i/o. must have running reactor in order set connection (regardless of whether using endpoint object or other api so).

as far can tell, pyglet integration reactor not automatically start itself. must phone call run method. question suggests not calling it, i'm quite curious is calling it.

when modify illustration create finish , runnable , add together error reporting, this:

from pygletreactor import install install() twisted.internet import reactor twisted.internet.endpoints import tcp4clientendpoint twisted.internet.protocol import mill twisted.protocols.amp import amp twisted.python.log import err def connect(): endpoint = tcp4clientendpoint(reactor, "127.0.0.1", 8750) mill = factory() factory.protocol = amp homecoming endpoint.connect(factory) d = connect() def connected(protocol): homecoming protocol.callremote( registeruser, username=u'alice') d.addcallback(connected) d.adderrback(err) reactor.run()

then behavior expect, connection attempted , fail (because not running amp server anywhere):

unhandled error traceback (most recent phone call last): failure: twisted.internet.error.connectionrefusederror: connection refused other side: 111: connection refused.

perhaps can compare finish programme , find of import difference.

python twisted pyglet twisted.internet cocos2d-python

java - Starting thread in a servlet, what can be the issues? -



java - Starting thread in a servlet, what can be the issues? -

i have web application, that, on single request may require load hundreds of data. problem info scattered. so, have load info several places, apply filters on them, process them , respond. performing these operations sequentially makes servlet slow!

so have thought of loading info in separate threads t[i] = new thread(loaddata).start();, waiting threads finish using while(i < count) t[i].join(); , when done, bring together info , respond.

now not sure if approach right or there improve method. have read somewhere spawning thread in servlets not advisable.

my desired code this.

protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { iterable<?> requireddata = requireddata(request); thread[] t = new thread[requireddata.size]; int = 0; while (requireddata.hasnext()) { t[i] = new thread(new loaddata(requiredata.next())).start(); i++; } for(i = 0 ; < t.length ; i++) t[i].join(); // after getting info process , respond! }

the main problem you'll bring server knees if many concurrent requests comes in servlet, because don't limit number of threads can spawned. problem maintain creating new threads instead of reusing them, inefficient.

these 2 problems solved using thread pool. , java has native back upwards them. read the tutorial.

also, create sure shutdown thread pool when webapp shut down, using servletcontextlistener.

java multithreading tomcat servlets asynchronous

c++ - Implementing a Linked List -



c++ - Implementing a Linked List -

i working on implementing linked list in c++. while have done in java in past, not understand how in c++ pointers, code compiles giving me segmentation fault when run it. doing wrong?

my node.h file

#ifndef node_h #define node_h #include <string> using namespace std; class node { public: node(const string, const int) ; ~node() { } void setnext(node *); // setter next variable node * getnext(); // getter next variable string getkey(); // getter key variable int getdistance(); // getter dist variable private: node *next; int dist; string key; }; #endif

my node.cpp file

#include "node.h" #include <string> node::node(string key, int dist){ key = key; dist = dist; } void node::setnext(node * next){ next->next; } node * node::getnext(){ homecoming this->next; } string node::getkey(){ homecoming key; } int node::getdistance(){ homecoming dist; }

and main.cpp file

#include "node.h" #include <iostream> using namespace std; int main(){ node* nptr1 = new node("test1", 2); node* nptr2 = new node("test2", 2); node* temp; nptr1->setnext(nptr2); temp = nptr1->getnext(); cout << temp->getkey() << "-" << temp->getdistance() << endl; }

any help appreciated. thanks.

you should initialize members defined value. shouldn't name parameters , members same, leads confusion or, more likely, bugs

node::node(string key_val, int distance) : next(0) { key = key_val; dist = distance; }

better yet, utilize fellow member initialization

node::node(string key_val, int distance) : next(0), key(key_val), dist(distance) { }

as commenters pointed out, must set next pointer in setnext() given parameter , should not modify parameter, this->next fellow member

void node::setnext(node * next_ptr){ next = next_ptr; }

c++ linked-list

Image thumbnail view for viewing images from mysqly database -



Image thumbnail view for viewing images from mysqly database -

i store image names in database , actual images saved local directory in computer. images fecthed database , displayed in gallery on php page. clicking 1 of these images open new page preview of selected image.

what want when selected image in details page clicked, should pop in original size.

i found simple image thumbnail viewer script @ dynamicdrive.com link image follows:

<a href="17.jpg"" rel="thumbnail"><img src="17.jpg" style="width: 50px; height: 50px" /></a>

however, want utilize on images names stored in database. tried next nil displayed on page:

<a href=<?php echo '<img src="./images/'.$cfilename.'" />'; ?>"" rel="thumbnail"><?php echo '<img src="./images/'.$cfilename.'" width="300" height="400" />'; ?></a>

i appreciate advice.

joseph

image

wait to load angularjs directive template -



wait to load angularjs directive template -

what trying postpone loading angular js template directive until need it. might not need @ all. there way can maybe load template directive if need it. service way this? application loads lot of directive templates , avoid loading much stuff unless need it. exact problem @ hand loading of template login form. if user clicks on button , he/she not logged in want slideopen (using jquery) login form.

in vast bulk of cases, there no value dynamically loading static directive templates. little doesn't create sense it. but, possible. however, of time, strategy used dynamic templates.

it requires $http fetch template , $compile wire angularjs.

class="lang-js prettyprint-override">app.directive('testdirective', function($http,$compile) { homecoming { scope: { show: '&' }, link: function( scope, element, attrs ) { var tpl, url = 'testdirective.tpl.html'; scope.$watch( 'show()', function (show) { if ( show ) { showthedirective(); } }); function showthedirective () { if ( !tpl ) { $http.get( url ).then( function ( response ) { tpl = $compile( response.data )( scope ); element.append(tpl); }); } } } }; });

here's plunker demonstrating works.

angularjs

ajax - Accessibility in javascript form validation -



ajax - Accessibility in javascript form validation -

this of import issue blind community i'm trying adress. how tell blind visitors username taken?

my current set-up not of import examples case, i've got jquery implementation checks user input against php script on ajax, returns json display on screen in error field. basic, , beyond scope of issue working perfectly.

but if i'm blind, won't notice username batman taken or can't contain spaces, , password requires @ to the lowest degree 7 characters.

alternatively, errors listed on error landing page after form submitted without javascript- it's chunky works. improve more dynamic solution , suport optimal.

as screen reader user fill out entire form, submit it, , if doesn't work error text. in order notify blind user invalid info before entire form submitted take @ aria-live="assertive" alternative scene on next test page, section d. http://www.accessibleculture.org/articles/2011/02/aria-alert/ out of test cases section d test worked me under firefox 18.0.1 jaws 13.0. reason alert alternative doesn't work. utilize assertive alternative notify user wrong.

javascript ajax forms validation accessibility

php - jQuery serialize() not working -



php - jQuery serialize() not working -

i have html form looks this:

<form class="form-horizontal" id="create_user" method="post" action="#" accept-charset="utf-8"> <span>username</span><input required="true" type="text" name="username" id="username"> <span>e-mail</span><input type="email" name="email" id="email"> <span>privileges</span><select id="role" name="role"><option value="1">administrator</option><option value="2">employee</option><option value="3">dealer</option></select> <span>password</span><input type="password" name="password" id="password"> <span>repeat password</span><input type="password" name="repeat_password" id="repat_password"> <input class="btn-primary btn" type="submit" value="submit"> <input class="btn-inverse btn" type="reset" value="reset"> </form>

i'm trying send info server using ajax, such:

$("form").submit(function(){ var form_data = $(this).serialize(); var request = $.ajax({ url: "user/validate", type: "post", data: form_data }); request.done(function (response, textstatus, jqxhr){ alert(response);//comes blank }) // callback handler called on failure request.fail(function (jqxhr, textstatus, errorthrown){ // log error console console.error( "the next error occured: "+ textstatus, errorthrown ); }); });

edit: here laravel controller handles post data:

class user_controller extends base_controller { public function post_validate() { homecoming input::get('username'); } }

however, no info sent using $(this).serialize(). if individually pass each element doing this: $("#username").val(), works fine. made sure form inputs had names, still didn't work.

i think page refreshed:

$("form").submit(function(e){ e.preventdefault(); //<-----try adding

php jquery ajax serialization laravel

c# - Reference previous object created in loop to update SQL -



c# - Reference previous object created in loop to update SQL -

i have loop sets form, next code (in form load event). displays checkbox persons name. checks checkbox if bit field 1.

int xaxischeckbox = 130; int yaxischeckbox = 30; (int = 0; < selectds.tables[0].rows.count; i++) { this.mycheckbox = new checkbox(); mycheckbox.location = new point(xaxischeckbox, yaxischeckbox); mycheckbox.size = new size(120, 20); mycheckbox.text = selectds.tables[0].rows[i]["fullname"].tostring(); mycheckbox.checked = (bool)selectds.tables[0].rows[i]["inoperation"]; yaxischeckbox = yaxischeckbox + 80; }

later on in code (for save button click event), runs same select load of updates set inoperation field true/false depending on tick. resets operationorder if beingness added operation.

for (int = 0; < selectdataset.tables[0].rows.count; i++) { userid = (int)selectdataset.tables[0].rows[i]["userid"]; if (mycheckbox.checked) { connection.runupdate("update users set inoperation = 1, operationorder = case when operationorder = 1 1 else case when inoperation=1 operationorder else (select count(*)+1 users inoperation=1 , operationorder > 0) end end userid=" + userid); connection.runupdate("update users set operationorder = case when operationorder = 0 (select count(*) users inoperation=1) else operationorder end inoperation=1"); } else { connection.runupdate("update users set inoperation = 0, operationorder = 0 userid=" + userid); connection.runupdate("update users set operationorder = case when operationorder -1 = 0 (select count(*) users inoperation=1) else operationorder -1 end inoperation=1"); } }

the problem updates every single row based upon lastly object created (e.g. if 5 rows, bottom checkbox count running sql, , applies of them). how can update every single row, there way can reference each object create rather lastly 1 created?

update: here of new code causing errors. public partial class selectusers : form { public int userid; public list myboxes;

public selectusers() { initializecomponent(); } private void selectusers_load(object sender, eventargs e) { dataset ds = myconnection.runselect(new dataset(), "the select"); int xaxischeckbox = 40; int yaxischeckbox = 50; myboxes = new list<checkbox>(); (int = 0; < ds.tables[0].rows.count; i++) { this.mycheckbox = new checkbox(); mycheckbox.location = new point(xaxischeckbox, yaxischeckbox); mycheckbox.size = new size(120, 20); mycheckbox.text = ds.tables[0].rows[i]["fullname"].tostring(); mycheckbox.checked = (bool)ds.tables[0].rows[i]["inoperation"]; yaxischeckbox = yaxischeckbox + 80; myboxes.add(mycheckbox); } } private void savebtn_click(object sender, eventargs e) { dataset ds = myconnection.runselect(new dataset(), "the select"); (int = 0; < ds.tables[0].rows.count; i++) { userid = (int)ds.tables[0].rows[i]["userid"]; if (myboxes[i].checked) { myconnection.runupdate("update users set inoperation = 1, operationorder = case when operationorder = 1 1 else case when inoperation=1 operationorder else (select count(*)+1 users inoperation=1 , operationorder > 0) end end userid=" + userid); myconnection.runupdate("update users set operationorder = case when operationorder = 0 (select count(*) users inoperation=1) else operationorder end inoperation=1"); } else { myconnection.runupdate("update users set inoperation = 0, operationorder = 0 userid=" + userid); myconnection.runupdate("update users set operationorder = case when operationorder -1 = 0 (select count(*) users inoperation=1) else operationorder -1 end inoperation=1"); } } }

you should maintain array of checkboxes rather individual checkbox

int xaxischeckbox = 130; int yaxischeckbox = 30; list<checkbox> myboxes = new list<checkbox>(); (int = 0; < selectds.tables[0].rows.count; i++) { this.mycheckbox = new checkbox(); mycheckbox.location = new point(xaxischeckbox, yaxischeckbox); mycheckbox.size = new size(120, 20); mycheckbox.text = selectds.tables[0].rows[i]["fullname"].tostring(); mycheckbox.checked = (bool)selectds.tables[0].rows[i]["inoperation"]; yaxischeckbox = yaxischeckbox + 80; myboxes.add(mycheckbox); }

and later ir loop:

for (int = 0; < selectdataset.tables[0].rows.count; i++) { userid = (int)selectdataset.tables[0].rows[i]["userid"]; if (myboxes[i].checked) { connection.runupdate("update users set inoperation = 1, operationorder = case when operationorder = 1 1 else case when inoperation=1 operationorder else (select count(*)+1 users inoperation=1 , operationorder > 0) end end userid=" + userid); connection.runupdate("update users set operationorder = case when operationorder = 0 (select count(*) users inoperation=1) else operationorder end inoperation=1"); } else { connection.runupdate("update users set inoperation = 0, operationorder = 0 userid=" + userid); connection.runupdate("update users set operationorder = case when operationorder -1 = 0 (select count(*) users inoperation=1) else operationorder -1 end inoperation=1"); } }

that should it.

it goes without saying, executing sql statements directy in form not idea, thats story

c# sql object checkbox

java - Permission Denied When Writing File to Default Temp Directory -



java - Permission Denied When Writing File to Default Temp Directory -

my programme intensive operations, utilize scratch file in order speed things up. utilize next java code:

file scratchfile = new file(system.getproperty("java.io.tmpdir") + "wcctempfile.tmp"); if (!scratchfile.exists()) scratchfile.createnewfile();

this code works fine on mac os x , windows. creates scratch file in java temporary directory, determined operating system.

however, when seek programme on linux (specifically linux mint), next error on line "scratchfile.createnewfile()"

java.io.ioexception: permission denied

i'm confused error because figured temp directory gathered system.getproperty("java.io.tempdir") method 1 user write (and on other operating systems). not case on linux? there way grant access temp directory? there other directory i'm supposed using?

on linux java.io.tmpdir commonly set /tmp (note missing trailing /). instead of messing around embedded slashes, it's lot cleaner utilize the two-parameter file constructor

file scratchfile = new file(system.getproperty("java.io.tmpdir"),"wcctempfile.tmp");

that way don't have worry trailing slashes or not.

java linux tempdir

java - Hard Coded SQL statements VS. Web Service to execute the queries -



java - Hard Coded SQL statements VS. Web Service to execute the queries -

i'm developing java application communicates mysql database in server. app should able read info xml file , insert info read database.

i used write sql statements straight java code, friend advised me create web service sql stuff tool, , allow tool's job read xml , send info web service.

my question is, deserve effort? why or why not?

sql in code not recommended becomes hard maintain. application tightly coupled database structure. every time database alter (or moving new database) need create changes code , release again.

i don't think web service right reply here. recommend seek 1 of following:

if application uses lot of tables , high throughput not critical, utilize hibernate orm tool. has many features , can cut down time spent on info access.

if not have many tables , don't have time larn hibernate, utilize ibatis. take 30 minutes grasp. allows set sql in separate xml file, read you. smaller applications useful , faster hibernate.

as lastly resort, rather set sql in text file(s) open , execute.

java sql database web-services

php - Incompatible AES implementation between Botan and phpseclib -



php - Incompatible AES implementation between Botan and phpseclib -

i'm using botan library aes encryption/decryption in c++. cannot utilize output of botan in phpseclib accurate results. appreciate if points me working code interoperability between botan , phpseclib or other php encryption library. thanks!

example of encryption botan in c++

// key std::auto_ptr<botan::hashfunction> thash ( botan::get_hash("sha-256") ); std::string mykey = "test"; botan::securevector<botan::byte> tsecvector(32); tsecvector.set(thash->process(mykey)); //the hash key - same size botan::symmetrickey key(tsecvector); // iv botan::initializationvector iv(mrng, 16); // encryption & encode botan::pipe pipe(botan::get_cipher("aes-256/cbc", key, iv, botan::encryption) ); pipe.process_msg(pstdstringtexttoencrypt); botan::pipe pipeb64enc(new botan::base64_encoder ); pipeb64enc.process_msg(pipe.read_all(0)); std::string strbase64encoded = pipeb64enc.read_all_as_string(0); // homecoming preturnencryptedtext = iv.as_string() + strbase64encoded;

example of decryption in php using phpseclib library:

include('crypt/aes.php'); $aes = new crypt_aes(crypt_aes_mode_cbc); //mcrypt used //decrypt request application. [iv 32 chars in hex] [base64 encrypted text] $aes->setkeylength(256); $key = hash('sha256','test', true) ; // true output raw binary output $aes->setkey($key); //iv $iv = hex2bin (substr($_post['enc'],0,32) ); $aes->setiv( $iv ); // encrypted text in binary $encryptedtextbin = base64_decode(substr($_post['enc'],32)); $decryptedrequest = $aes->decrypt( $encryptedtextbin ); echo $decryptedrequest; //no match

i tried mcrypt in php straight no success:

$decrypted_data=""; //128 hack shown on: http://kix.in/2008/07/22/aes-256-using-php-mcrypt/ $td = mcrypt_module_open(mcrypt_rijndael_128, '', mcrypt_mode_cbc, ''); mcrypt_generic_init($td, $key, $iv); $decrypted_data = mdecrypt_generic($td, $encryptedtext); mcrypt_generic_deinit($td); mcrypt_module_close($td); edit:

i tested in 128 bit both botan , phpseclib , proper decryption in 50% of cases. weird. tested different padding modes in botan (cts,pkcs7,oneandzeros,x9.23) 1 time again success in 50% of attempts.

it'd help if posted sample of key you're using botan, password (ie. pre-hashing), iv you're using , plaintext you're using / ciphertext you're getting. that'd allow people test various possibilities instead of having on behalf.

anyway, first guess botan maybe doesn't pad default whereas phpseclib assumes, default, plaintext has been padded.

php cryptography aes phpseclib botan