Posts

Showing posts from July, 2013

setinterval - Setting timer for a javascript randomizer -

the randomizer works, looking way loop using setinterval can continuously run in own div on website. <script language="javascript"> setinterval(quotes(), 3000); function quotes(i) { var r_text = new array(); r_text[0] = "all leaves brown"; r_text[1] = "and sky grey"; r_text[2] = "i've been walk"; r_text[3] = "on winter's day"; r_text[4] = "i'd safe , warm"; r_text[5] = "if in l.a."; r_text[6] = "california dreaming, on such winter's day"; var = math.floor(7 * math.random()) document.write(r_text[i]); } </script> change setinterval(quotes(), 3000); setinterval(quotes, 3000);

ruby on rails - Polymorphic has_one built through accepts_nested_attributes_for is not setting polymorphic type -

note: while project uses spree version 2.3, not of belief spree-specific problem. though please correct me if wrong. the spree framework has model called calculator looks this: module spree class calculator < spree::base belongs_to :calculable, polymorphic: true ... end end i inheriting class create own calculator looks (which little different other spree calculator subclass ): module spree class calculator class percentdiscountonvariant < calculator preference :percent, :decimal, default: 0 ... end end end my model, called clientproduct has has_one relationship calculator , , can accept nested attributes it, so: module spree class clientproduct < activerecord::base has_one :calculator, inverse_of: :calculable, foreign_key: "calculable_id", dependent: :destroy accepts_nested_attributes_for :calculator ... end end the problem when create clientproduct (either new record, or updating existi

Executing PowerShell Commands in Java Program -

i have powershell command need execute using java program. can guide me how this? my command get-itemproperty hklm:\software\wow6432node\microsoft\windows\currentversion\uninstall\* | select-object displayname, displayversion, publisher, installdate | format-table –autosize you should write java program this, here sample based on nirman's tech blog, basic idea execute command calling powershell process this: import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstreamreader; public class powershellcommand { public static void main(string[] args) throws ioexception { //string command = "powershell.exe command"; //getting version string command = "powershell.exe $psversiontable.psversion"; // executing command process powershellprocess = runtime.getruntime().exec(command); // getting results powershellprocess.getoutputstream().close(); string line; system.out.println("standard output:")

python - Concurrent or parallel requests on a 10-nodes cluster -

i wrote simple script 200 concurrent threads makes http requests , processes results. need around 50,000,000 requests. script simple modification of "twistedless solution" suggested here (the first reply). if want run on 10-nodes aws cluster, how can parallelize it? if copy script onto 1 node , run it, happens? same on local machine? being new this, need starting point. thanks! on aws can have elastic load balancer (elb). can set manually or within autoscaling group. either way, x ( x=10 :d ) instances attached elb. need set elb health check properly, sees instances healthy , serves traffic of them. if done, need send concurrent requests elb endpoint. worth check sticky sessions if need or causes false result, sending traffic 1 instance because source of requests same.

Visual Studio 2013 C language // Writing files // Crashing -

// code should run // when run code, prompt enter number when press enter crashes. file.exe stopped working or // unhandled exception @ 0x0fbfe541 (msvcr120d.dll) in file.exe: 0xc0000005: access violation writing location 0x00000000. #include<stdio.h> #include<conio.h> void main() { int n = 0; file *f; fopen_s(&f, "text.txt", "r+"); if (f == null) printf_s("error!"); printf_s("enter number: "); scanf_s("%d", n); fprintf_s(f, "%d", n); fclose(f); _getch(); }

python get a list of expressions -

i have in config (ini) file: result = "name\tage\tdob" this want final output (as list) - write output file real values written single line: [str(row["name"]).strip(), str(row["age"]).strip(), str(row["dob"]).strip()] my python reads 'result' config file string , manupulation close need. stuck after that. did: list1 = result.decode('string_escape').split() list2 = map(lambda x: x.replace('\"', ''), list1) list3 = map(lambda x: 'str(row[' + '"' + x + '"' + ']).strip()', list2); print list3 and prints list3 as: ['str(row["name"]).strip()', 'str(row["age"]).strip()', 'str(row["dob"]).strip()'] now, if notice, elements of list3 strings...which don't want. how ensure elements of list python expressions...? tried replace("'", ""), did not help. any suggestion appreciated.

scala coding to do the Huffman decoding, but wrong result -

abstract class codetree case class fork(left: codetree, right: codetree, chars: list[char], weight: int) extends codetree case class leaf(char: char, weight: int) extends codetree type bit = int def decode(tree: codetree, bits: list[bit]): list[char] = { if(!bits.isempty) { bits.head match { case 0 => tree match { case fork(l, r, _, _) => decode(l, bits.tail) case leaf(_, _) => chars(tree) ::: decode(frenchcode, bits.tail) } case 1 => tree match { case fork(l, r, _, _) => decode(r, bits.tail) case leaf(_, _) => chars(tree) ::: decode(frenchcode, bits.tail) } } } else nil } val frenchcode: codetree = fork(fork(fork(leaf('s',121895),fork(leaf('d',56269),fork(fork(fork(leaf('x',5928),leaf('j',8351),list('x','j'),14279),leaf('f',16351),list('x','j','f'),30630),fork(fork(fork(fork(leaf('z',2093),fork(leaf('k',745),leaf('w

oracle - SQL Queries "00904. 00000 - "%s: invalid identifier" -

hi have following code select entertainer_id, entertainer_groupname casestudy_entertainer inner join casestudy_availability on casestudy_entertainer.entertainer_id = casestudy_availability.availability_entertainerid inner join casestudy_calendardates on casestudy_availability.availibility_calendardateid = casestudy_calendardates.calendar_id entertainer_type = '&entertainer_type' , casestudy_calendardates.calendar_date = '&event_date' and don't seem able figure out not liking when run this. gives me following error ora-00904: "casestudy_availibility"."availibility_calendardateid": invalid identifier 00904. 00000 - "%s: invalid identifier" *cause: *action: error @ line: 7 column: 4 i have tables in place correct rows. thing have no data of yet, possibly issue? you should try lower case table/column identifiers(like in from / inner join clauses): select ente

php - mysqli prepared statement not working in login -

i want login user, returns 0 in num rows. problem? config.php <?php $hostname="localhost"; $titulo="config"; $user="root"; $pass=""; $bd="st"; $mysqli_link = new mysqli($hostname, $user, $pass, $bd); if (mysqli_connect_errno()) { printf("connect failed: %s\n", mysqli_connect_error()); exit(); } ?> no error showing. login.php include("config.php"); $user = $_post['user']; $pass = $_post['pass']; $stmt = $mysqli_link->prepare("select id, user cadastro binary user = ? , binary senha = ?"); $stmt->bind_param('ss', $user, $pass); $stmt->execute(); $stmt->store_result(); //it works!!** $num = $stmt->num_rows; echo $num; //$num 0 why? if($num > 0) {... i type user , pass correctly, im converting mysql mysqli. edit------------------------------------------------------- with $stmt->store_result(); works! have error in part:

javascript - Importing a .data file into D3js? -

so i've been given task of importing data visualize. specific: http://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data however, have not clue on how import .data file. furthermore, there no header line in order organise file. i have tried import text , use csv.parserows() led arrays length of 1 containing 1 long string: i have tried import d3.tsv(). every technique ends importing row 1 long string below. "18.0 8 307.0 130.0 3504. 12.0 70 1 "chevrolet chevelle malibu"" i have never dealt .data files , resources on using them d3 scarce. on dealing appreciated always. people awesome. thanks. you use regular expression parse string: /("[^"]+"|[^\s]+)\s*/g with regular expression, turn 18.0 8 307.0 130.0 3504. 12.0 70 1 "chevrolet chevelle malibu" into [ "18.0", "8", "307.0", "130.0"

mysql - Create migration in Laravel with and without prefix -

i need create database has tables prefix, tables can't have (legacy tables used in other softwares). so, let's have 3 tables: user group person user legacy table, nomenclature should be user myprefix_group myprefix_person i added prefix in app/config/database.php , app/config/local/database.php . database in mysql. i'm afraid must manually. create migrations prefixes , add in models protected $table = 'table_name';

android - Releasing PendingIntent after reentering app -

anyone knows how cancel pendingintent after leaving app button? when pendingintent switched on , canceled on 1 session without exiting app in between it's fine - got covered, when leave , reenter can't anymore cancel , have wait alarm. mainactivity: b5.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { setcall(12000); pendingintent.cancel(); if (alarmmanager!= null) { alarmmanager.cancel(pendingintent); } } }); public void setcall(int timetocall){ if (alarmmanager!= null) { alarmmanager.cancel(pendingintent); } string name = e1.geteditabletext().tostring(); //toast.maketext(getapplicationcontext(), name, toast.length_short).show(); intent intent = new intent(mainactivity.this, thisbroadcastreceiver.class); intent.setflags(intent.flag_include_stopped_packages); intent.pute

c++ - same function Multiple Names without Wrappers -

i creating small linear algebra library educational purposes. i have function called . these function doing mathematical operations , , given different names different communities. 1 name machine learning people(say a) , name statistics people(say b). i want both of them able access function using different names use , ie both a(...) , b(...) should give same result. obvious way use function wrapper. b(...) { return a(...) } this job done. right way ? there better more "elegant" way ? -thank you use function pointers. int f1(int a) { return * 2; } const auto f2 = f1; int main() { cout << f2(4) << endl; }

PHP & HTML Mailer Only Sending One Parameter in the Body -

this first time posting here, please excuse me if don't use code formatting correctly. also, php not strong-point. i'm attempting send user-populated e-mail html , php. i've gotten e-mail send, i'm having issues body of e-mail. phone number populating e-mail, nothing else, not name, email, or message. ideas? i know parameters being populated. inspect page, , watch network events through firebug on firefox. parameters being passed php, i'm certain. //building message body $name = $_post['name']; $email = $_post['email']; $phone = $_post['phone']; $message = $_post['message']; //adding body variable $body = "name: " + $name + "\r\n" + "e-mail: " + $email + "\r\n" + "phone: " + $phone + "\r\n" + "message: " + $message + "\r\n"; //email info $to = 'thisisafake@gmail.com'; $subject = 'you have been contacted via web form!'; $from = &

php - Laravel Advanced Wheres how to pass variable into function? -

example in doc: db::table('users') ->whereexists(function($query) { $query->select(db::raw(1)) ->from('orders') ->whereraw('orders.user_id = users.id'); }) ->get(); but if need use external variable that: ->where('city_id', '=', $this->city->id) ->where(function($query) { $query->where('name', 'like', '%'.$searchquery.'%') ->orwhere('address', 'like', '%'.$searchquery.'%') }) for created new property , accessed through $this-> , there more convenient way? you can pass necessary variables parent scope closure use keyword. for example: db::table('users')->where(function ($query) use ($activated) { $query->where('activated', &

listview - Android - creating LinearLayout with non-static number of fields (TextView) -

i have create layout 7 elements every of elements have variable numbers of items. that: <scrollview xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.lessons"> <linearlayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="5dp" android:orientation="vertical"> <linearlayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:layout_margin="5dp" android:orientation="vertical"> <textview android:id="@+id/lessons_text_1" android:layout_width="match_parent"

Error with Equation parsing (java) -

i have code: public class parse { static double eval(string exp) { scriptenginemanager mgr = new scriptenginemanager(); scriptengine engine = mgr.getenginebyname("javascript"); string stringresult = null; try { arraylist<variable> vars = askforvars(parse1(exp)); arraylist<string> usednames = new arraylist<string>(); (variable v : vars) { if (!usednames.contains(v.name)) { stringresult = replacestring(exp, v.name, "" + v.valueused); usednames.add(v.name); } return double.parsedouble(engine.eval(stringresult.tostring()) .tostring()); } } catch (exception ex) { ex.printstacktrace(); } return 0.0; } static arraylist<variable> parse1(string exp) { arraylist<variable> variables = new arraylis

delphi - Installing TChart2014 & XE7 -

i have been using tchart (pro) years , on tchart2014. have upgraded delphi xe7 installer not recognize xe7. downloaded latest bin , source code files download center xe7 not there (actually, since removed xe2, says there no ide's installed). there installation set lurking somewhere not 'public' following comments question, answer subscription license needs renewed/extended access teechart 2014.12.140923 vcl/fmx release , first version adding rad studio xe7 support, or newer version.

database - How can I automatically merge two different schemas in MySQL? -

i have mysql database in production (i'll call db1) lots of data already. in dev, made several changes it's structure , added data testing purposes. i'll call db2. i need merge db2's schema db1's without losing db1's data , without copying data db2. is there way automatically (using scripts, procedures or workbench's built-in functionality)? dump schema need without data mysqldump --no-data load dump new database. create stored procedure dynamic sql , cursor on information schema.tables. basically, each table belongs original database, construct insert ... select query inserts data new database. notice may need lock out entire database lock tables statement if want prevent data being modified while you're copying it. can construct lock tables statement dynamic sql well. done. if step 3 looks complicated, insert... select data manually. there no automatic way in mysql: depending on changes made original schema, e.g. added colum

linux - AWS RDS documentation leads to BASH syntax error -

when following this guide , command sudo mysqldump --databases world --single-transaction --compress --order-by-primary –u <local_user> -p<local_password> | mysql --host=hostname –-port=3306 –u <rds_user_name> –p<rds_password> bash returns following error: -bash: syntax error near unexpected token `|' can me understand why? after deleting greater / less symbols command, returns mysqldump: got errno 32 on write which pipe error. how shall proceed?

javascript - What's best way to run same function on multiple elements only when they're inside viewport? -

i have 3 elements background images want scale x 1. want begin when top of element inside viewport (this may vary little). i have achieved effect long way: function animatepanelbackgrounds() { var $toolsbg = $('#js-tools-bg'), $dennysbg = $('#js-dennys-bg'), $verizonbg = $('#js-verizon-bg'), $llbeanbg = $('#js-llbean-bg'); var dennystop = math.floor( $("#js-dennys").offset().top ); var dennysgo = dennystop - window.innerheight; var llbeantop = math.floor( $("#js-llbean").offset().top ); var llbeango = llbeantop - window.innerheight; var verizontop = math.floor( $("#js-verizon").offset().top ); var verizongo = verizontop - window.innerheight; var toolstop = math.floor($toolsbg.offset().top); var toolsgo = 0; var ratio, $that; if ( thiswindows.offsety() >= toolsgo ) { ratio = toolstop/(thiswindows.off

Possible Issues With BizTalk Host -

in our biztalk environment, have specific hosts processing, receiving , sending. few days ago, saw following information message in event log. the following biztalk host instance has initialized successfully. biztalk host name: sendhost windows service name: btssvc$sendhost this message started happening @ 1:04:41 , shows every minute until 10:01:05 pm night. appears each time host initialized, have been queued send start sending. each minute, same data appears attempt send - there equal number of error messages in event log our various interfaces. i'm wondering cause send host reinitialize every minute, , if happens again, how find out what's causing it. has seen type of behavior before? if so, how did resolve it? ** edit ** at 1:00:24 am, following error logged in application log application: btsntsvc.exe framework version: v4.0.30319 description: process terminated due unhandled exception. exception info: system.runtime.callbackexception stack: @ s

Serve files privately with JSP/Tomcat? -

i writing jsp app should allow users log in (authenticate against postgresql database simple username , password check), , upload photos. images should private in can accessed user while logged in. copy of image url should not work after logout. how can done tomcat/jsp? i not want store blobs in database. you can use servlet filters. let's have url /images/ images stored, using filters can check whether session user alive or not. some examples: example 1 example 2

inheritance - Is it possible to extend Methods in Java? -

i know possible in java: public class animal {...} and public class dog extends animal {...} then can write whatever dog methods can access animal method. however, wondering there way extend methods for example public void generateanimal() {...} and public void generatedog() extends generateanimal() {...} but not passing compiler. question is: is possible inherit methods in java? yes. public class animal { public void someaction() { system.out.println("from animal class"); } } public class dog extends animal { public void someaction() { super.someaction(); system.out.println("from dog class"); } } public class main { public static void main(string[] args){ animal dog = new dog(); dog.someaction(); } } output: from dog class animal class so extend functionality of method, better use composition instead of inheritance.

c++ - Strange return behaviour in recursive function -

i have tree node class this: class node { public: node(); node(char _value); ~node(); char getvalue() const; node* getparent() const; void addchild(node* _child); bool isleaf() const; bool isroot() const; bool haschild(char _value) const; private: vector<node*> children; char value; node* parent; }; and have serach method implemented: bool node::haschild(char _value) const { if (value == _value) return true; (auto = children.begin(); != children.end(); it++) { if (*it != null) { (*it)->haschild(_value); } } } however, when run code, tmp variable false. if trace debugger, return true; part executes, recursion continues. tips? node* root = new node(); node* = new node('a'); node* c = new node('c'); root->addchild(a); root->addchild(c); bool tmp = root->haschild('a'); your problem lies in haschild in way calls

html - Aligning mixed form input types with CSS -

i stuck hard on project. requires form, , aligning text input boxes/radio buttons/etc in straight line down page. have achieved text input boxes no problem, can't rows radio buttons, checkboxes, or textareas behave. code is: html: <div class="containdiv"> <label>phone <img src="circle.gif" /></label> <input type="text" name="phone" maxlength="4" size="4"> <input type="text" name="phone" maxlength="4" size="4"> <input type="text" name="phone" maxlength="4" size="4"> </div> <div class="containdiv"> <label>preferred contact <img src="circle.gif" /></label> <div class="radio"> <input type="radio" name="email" value="email"> <label for="email">

ios - How to perform action before triggering exit segue? -

i have created segue (present modally) view controller view controller b triggered through button in navigation controller of view controller a. modal takes on used send friend request typing in email. when user types in email , presses button submit friend request, want perform action triggered button (calling server send friend request , returning success if email exists or returning error if email doesn't exist). if success, want exit/unwind segue a. if error, don't want exit/unwind segue. i have looked this question, doesn't seem have implementation of need. trying following: class bviewcontroller: uiviewcontroller { // button function @ibaction func sendfriendrequest(sender: anyobject) { println("button function.") self.performseguewithidentifier("sendfriendrequest", sender: self) } override func prepareforsegue(segue: uistoryboardsegue, sender: anyobject?) { if segue.identifier == "sendfrie

c# - Multiple callers waiting on long running GET, any way to make them all wait on the same return? -

i running wcf rest service , have discovered bit of bottleneck. current code boils down below: private static list<widget> widgets; public async task<list<searchresult>> search(string term) { if(widgets == null) { // call takes 60 seconds widgets = await getwidgets(); } return searchutil.search(term, widgets); } the problem many requests can enter if check , call long running operation. instead, want additional incoming requests wait on original call complete , 1 call getwidgets() made. how can achieve stop firing off many requests when dictionary empty? as small aside, safe assume list/dictionary remain populated entire time service alive? or empty reason? best way handle type of situation (i'm guessing other mechanism cache)? thanks! if understand correctly, want cache never expires , populated first time requests value. should pretty straightforward build in generic way: class nonexpiringlazyloadingcache<

Programmatically evaluate a list of functions in Clojure -

i trying figure out how programmatically evaluate list of functions. lets have code: (defn foo [] (println "foo")) (defn bar [] (println "bar")) (def funcs [foo bar] ) i want execute functions of funcs in programmatically way. i tried use eval , no succcess. thanks help. use for if want return values, , ok lazy evaluation (your functions not guaranteed called until access return value), , doseq if don't need values , doing immediate side effects. (doseq [f [foo bar]] (f)) (def fs (for [f [foo bar]] (f)))

c# - HTTP WCF Service keep the stream open -

i'm trying stream data client on http. achieve i'm using wcf service webhttpbinding . problem system.io.stream operation returns closed before can write it. i'd keep stream open until data needs written it. not more half minute. in service request method create new instance of system.io.memorystream put collection of streams , return function output. later on when there audio data available i'm writing streams in collection. the requests have been closed. when go endpoint url browsers standard player greyed out. tested rest client, showed me request closes after return statement. the problem use libspotify sdk retrieve music. sends 8192 bytes of pcm data per cycle. make possible users play music chromecast device. chromecast doesn't support pcm data that's why convert mp3 libmp3lame , send through output stream chromecast. approach work need connection stay alive though there no actual data being send through stream . the libspotify music delivery

How should I test Rails Enums? -

suppose have model called creditcard. due technical restrictions, it's best if card networks represented enum. code looks this: class creditcard < activerecord::base enum network: [:visa, :mastercard, :amex] end what should tested when using enums if anything? if use array, need make sure order keeped: class creditcard < activerecord::base enum network: [:visa, :mastercard, :amex] end describe creditcard, '#status' let(:network) { [:visa, :mastercard, :amex] } 'has right index' network.each_with_index |item, index| expect(described_class.statuses[item]).to eq index end end end if use hash order not matter, value of each key, will. so, it's to make sure same number each key.

Rails 4 simple search form with more than two parameters -

i've been creating simple search form allow me enter 3 different criteria in order find car in inventory. 3 criteria car vin or car model or car color. have done far allows me search either vin number or color whenever enter model search not return anything. here controller: def index #@cars = car.all @cars = car.search(params[:search], params[:car_vin], params[:car_model], params[:car_color]).page(params[:page]) end here model: def self.search(search, car_vin, car_model, car_color) if search where('car_vin ? or car_model ? or car_color ?', "%#{search}%", "%#{search}%", "%#{search}%") else where(nil) end end here view: <%= form_tag cars_path, :method => 'get' %> <p> <%= text_field_tag :search, params[:search], :placeholder => "car vin, model or color" %> <%= submit_tag "search", :name => nil %> </p> i can't pinpoint cause of why not return i

mysql - Update form row in php error -

i'm trying update multiple row/rows in form. i'm getting error notice: array string conversion in c:\wamp..... i'm getting error warning: cannot modify header information - headers sent (output started @ c:\wamp\.... both of these fixed. form $ad = "<form action='updaterecords.php' method='post' id='update'> \n"; $records = $this->query_recs(); foreach ($records $record) { $ad .= "<p id='id{$record->id}'>"; $ad .= "<input type='hidden' name='id[]' value='" .$this->render_i18n_data($record->id) . "' />\n"; $ad .= "<input type='text' name='paname[]' value='". $this->render_i18n_data($record->pa_name) . "' class='paname' />\n"; $ad .= "<input type='text' name='pcname[]' value='". $

Visual studio, Windows Phone emulator not working -

Image
made app in visual studio 2013 downloaded windows phone 8.1, latest version tried running app, , keeps giving me error. i've tried uninstalling, using repair, redownloading , reinstalling, restarting computer, deleting folder couple people recommended, nothing. (error 1 retrieving com class factory component clsid {2d0a16c9-53d9-42c1-bcc2-8d2a135e2163} failed due following error: 8007007e specified module not found. (exception hresult: 0x8007007e). please rebuild solution , try again. 0 0 ) anyone got ideas? the clsid reference above vsd (visual studio device) connection manager. looks vs can't find vsd connectionmanager. a few things at: do have hyper-v enabled , running? if not, need running hyper-v in order run windows phone emulator. in hyper-v manager, see windows phone emulator images listed? using hyper-v manager, can start of emulator images: in visual studio, see emulators listed in build & debug target toolbar:

How to append text to an existing file in Java -

i need append text repeatedly existing file in java. how do that? are doing logging purposes? if there several libraries this . 2 of popular log4j , logback . java 7+ if need 1 time, files class makes easy: try { files.write(paths.get("myfile.txt"), "the text".getbytes(), standardopenoption.append); }catch (ioexception e) { //exception handling left exercise reader } careful : above approach throw nosuchfileexception if file not exist. not append newline automatically (which want when appending text file). steve chambers's answer covers how files class. however, if writing same file many times, above has open , close file on disk many times, slow operation. in case, buffered writer better: try(filewriter fw = new filewriter("myfile.txt", true); bufferedwriter bw = new bufferedwriter(fw); printwriter out = new printwriter(bw)) { out.println("the text"); //more code out.println("mo

tools:RGUI disappears from globalenv R -

i installed newest version of r os -- r version 3.1.3 mac. tools:rgui not load properly. half time, open r , search() not include tools:rgui. other half of time, appear disappears global environment. result, cannot use function or search , install packages. internet connection fine. ideas? i think figured out problem; had detach() @ start of code. not attach data have been told bad habit can lead problems. right. have deleted references attach , detach , things seem work fine now.

css - What causes a parent container to cut off content in child element? -

Image
on mac safari , chrome, dark select box appears correctly: in ios safari, gets cut off @ border of selected div: what make happen? here styles of selected parent: and on select box: one of parents of select box had overflow-y hidden.

ruby on rails - Generating and linking to multiple prawn pdfs single action -

i'm generating pdf using prawn gem on show action: format.pdf pdf = procurementreportpdf.new @real_property_sale_project, current_user, view_context send_data pdf.render, filename: "procurementreport.pdf", type: "application/pdf", disposition: "inline" end i access pdf in show view so: <%= link_to '', "/real_property_sale_projects/#{@rpsp.id}.pdf", class: "fa fa-file-pdf-o right track-with-mixpanel", :data => { :event => "clicked bid export icon", tooltip: "export_bids" }, :title => "procurement report (pdf)", :target => "_blank" %> i generate second report action i'm unsure of best way this? after generating report how go linking in view? solved defining following method in controller: def vendor_report @real_property_sale_project = realpropertysaleproject.find params[:project_id] respond_to |format| format.pdf

How to get a sub-string array from array string c# -

i'm new c#. have string split string array , 1 of elements needs split again string array parsed differently. i'm trying convert string arrays float arrays , combine them 1 final float array @ original position. string ido = "433, 045, 3-3-15, 444, 0.6,3.9,4,5,5,4,3,3"; string[] sn= ido.split(',', 13, stringsplitoptions.removeemptyentries); string subnum = sn[2]; string[] st = subnum.split('-',3,stringsplitoptions.removeemptyentries); float [] stnum = array.convertall<string, float>(st, float.parse) float[] farray = new float[ float.parse(sn[0]), float.parse(sn[1]),... stnum, float.parse(sn[3:end])]; i know last line wrong. don't want feed each element float.parse() individually. i'm trying there better way this? can use convertall how elements in string array element 3 end of array? since want result of array of floats, can split original string on both ',' , '-' characters, end array of "nu

Creating Python Pinger - Sockets -

ok, changed try , ask more specific question. i have 2 methods. dooneping creation use sendoneping, written me in aid understand sockets better. i trying understand if creating socket correctly within dooneping, believe am, not sure if missing specific or better. thanks def sendoneping(mysocket, destaddr, id): # header type (8), code (8), checksum (16), id (16), sequence (16) mychecksum = 0 # make dummy header 0 checksum # struct -- interpret strings packed binary data header = struct.pack("bbhhh", icmp_echo_request, 0, mychecksum, id, 1) data = struct.pack("d", time.time()) # calculate checksum on data , dummy header. mychecksum = checksum(header + data) # right checksum, , put in header if sys.platform == 'darwin': # convert 16-bit integers host network byte order mychecksum = htons(mychecksum) & 0xffff else: mychecksum = htons(mychecksum) header = struct.pack("

bash - xinetd / netcat - redirecting stdin/stdout -

i have simple xinetd controlled script wraps simple java application listens on given port. xinetd talks via stdin/stdout, use netcat redirect traffic to/from java app. @ moment have following configuration. xinetd service my_server { type = unlisted disable = no socket_type = stream protocol = tcp wait = no user = root port = 2177 log_on_success += duration host userid server = /opt/stuff/my_server.sh } my_server.sh port=2111 # start java process on given port java -jar /opt/stuff/myserver.jar "$port" & # redirect traffic using netcat retry_counter=0 until nc -v 127.0.0.1 ${port} let "retry_counter++" echo "retrying... (${retry_counter})" >> /var/log/smpp_nc sleep 0.1 done it seems netcat job of sending data app, not other way around... help/hints appreciated! assuming you're in control of java server code, you

Accessing javascript variable in jsp in java -

i have included javascript file in head of jsp file! want there variable increasing using click on map, , want value in jsp page. please tell me how that, here code! the jsp file code! incremental value defined clickhandler.js <%@ page language="java" contenttype="text/html; charset=iso-8859-1" pageencoding="iso-8859-1"%> <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <title>insert title here</title> <script src="http://www.openlayers.org/api/openlayers.js"></script> <script src="clickhandler.js" type="text/javascript"> </script> </head> <h1>this login page</h1> <body onload='init();'> <form action="hellowelcome" method=&q

How to use the TCL script to test the C language function on the embedded system? -

i want test c language function on embedded system. topology is: pc -------(console or telnet)------ embedded system. the testing script running on pc, , call c language function on embedded system. want use tcl script test it. see solution: embed tcl interpreter embedded system run-time. the test steps: pc send tcl script embedded system. the tcl interpreter embed in embedded system parse tcl script , run call c language function. q1: feasible solution? q2: there other possible solution (must run tcl script on pc)? q3: need embed swig on embedded system run-time? thanks. like many situations, choice of partition things between processors depends upon many factors. because system embedded in nature not mean embedded computer not powerful. have done suggest, running tcl interpreter on embedded system , using drive testing of embedded application. long time ago, in tcl 7.x days. current tcl interpreter quite large embedded computer standards (although quite

css - media query won't take precedence -

i have simple css , html see if media query work. wrong <!doctype html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type="text/css"> .box { background: red; width: 100px; height: 200px } /* mobile phones */ @media screen , (max-device-width:640px) { .box { background: blue; } } </style> </head> <body> <div class="box"></div> </body> </html> the box background won't change blue when viewing in mobile. use firefox plugin "go mobile" simulate mobile screen environment during test solution: https://jsfiddle.net/r56m37kb/ max-width instead of max-device-width

node.js - Moongoose sort by parseFloat(String) -

i want sort query result float value . value stored in mongodb type string ,can parse string float , sort dynamically? complex sort. the following parts of schema , sort code: schema: var scenicspotschema = new schema({ ... detail_info: { ... overall_rating: string, ... }, }); sort function: scenicspot.find({'name': new regexp(req.query.keyword)}, ) .sort('-detail_info.overall_rating') .skip(pagesize * pagenumber) .limit(pagesize) .exec(function (err, scenicspots) { if (err) { callback(err); } else { callback(null, scenicspots); } }); any kind of , advice appreciated. :) .sort mongoose not support converting data type. see: http://mongoosejs.com/docs/api.html#query_query-sort it accept column names , order. there 2 path acheive goal: use mapreduce in mongo, first convert type, , sort retri

r - using paste() in a for loop with glm -

in code below, df.pts dataframe. i'd run dozen glm models using different y variable (only 2 shown in code). i'm using loop paste() function, can't seem paste() function work properly. missing paste()? spca2 = df.pts[,3] clqu2 = df.pts[,4] df.list = list(spca2, clqu2) (i in df.list) { qp.mod = glm(paste(i,"~ndvi+elev"), family="quasipoisson", data=my.data) print(summary(gp.mod)) } many thanks! main problem df.list list of vectors, , should have been list of names. i other words, correct problem... df.list = ("spca2", "clqu2") instead of df.list = list(spca2, clqu2) however, correctly pointed out dataframe, my.data, not correct dataframe. finally, while worked without it, function as.formula() worked. again, many thanks!

php while loop invoked remotely by cURL fails -

long-time user, first-time poster, patience! this php code when invoked remotely through curl fails unless comment out while loop, of course defeats code's purpose of reading through file. fgets right file reading tool me, since file contains text lines ending in newline. (i've created slightly-awkward construction using $readworks combine while , if clauses , enable code work when while loop commented out.) <?php define( "ipdirfile", "path/to/ipfile.csv" ); // lookup in standard file location local lookups $readworks = true; $iplookup = fopen( ipdirfile, "r" ); if ($iplookup) { // while ( $readworks ) { // uncomment loop produce failure if (($ipline = fgets( $iplookup )) !== false) { echo "got line fgets: " . $ipline . "<br>"; } else { echo "can't fgets line<br>"; $readworks = false; } } //} // ending brace fclose( $iplookup ); ?> here'