Friday, 15 February 2013

javascript - How to get this code to run in jsFiddle? -



javascript - How to get this code to run in jsFiddle? -

how run code in jsfiddle? original code adam khoury's site @ http://www.developphp.com/view.php?tid=1262

i've experimented , able button show , canvas outline can not object animate left right when button clicked.

here effort run in jsfiddle at...

http://jsfiddle.net/tn8xc/

function draw(x,y){ var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.save(); ctx.clearrect(0,0,550,400); ctx.fillstyle = "rgba(0,200,0,1)"; ctx.fillrect (x, y, 50, 50); ctx.restore(); x += 1; var looptimer = settimeout('draw('+x+','+y+')',30); }

thanks help.

jsfiddle's default settings have javascript run onload, or after html loads.

this works cases, except when utilize on* attribute execute js inline, because js hasn't loaded, can't access variables , methods.

you need alter onloadto no wrap - in <head> in left sidebar @ top: places js in <script> tags in head. head loads before else (whatever set in html area), when utilize onclick attribute reference draw() function, has been defined.

you can utilize no wrap - in <body> because js still placed before rest of html, placing in head should serve in cases.

had checked console, have seen referenceerror: can't find variable: draw, have told js hadn't loaded before tried access draw().

demo

javascript css html5 animation

regex - Extracting data between keywords into an array using perl -



regex - Extracting data between keywords into an array using perl -

i have file has keywords frame 1, frame 2 , frame 3 ... frame 100+, want extract info between each frames , place in array. tried , not getting per need. maintain getting matched line. tried 2 ways.

my $key1 = "frame 1" ; $key2 = "frame 2"; while (<readhandle>){ if (/^$key1/../^$key2/){ @linearray=$_; print "\n @linearray \n" ; } }

this print lines. , sec seek follows

my $key1 = "frame" ; while (<readhandle>){ if (/^$key1/){ @linearray=$_; print "\n @linearray \n" ; } }

this print matched lines not info between.

my file looks below

frame 1: 140 bytes on wire (1120 bits), 140 bytes captured (1120 bits) encapsulation type: ethernet (1) arrival time: jun 11, 2014 16:03:37.864278820 republic of india standard time ethernet ii, src: cisco_a9:94:0a (00:30:96:a9:94:0a), dst: ipv6mcast_00:00:00:0d (33:33:00:00:00:0d) frame 2: 90 bytes on wire (720 bits), 90 bytes captured (720 bits) encapsulation type: ethernet (1) net protocol version 6, src: ::200:1:1:2 (::200:1:1:2), dst: ff02::1:ff01:1 (ff02::1:ff01:1) 0110 .... = version: 6

so on.. help or suggestion much appreciated.

you can utilize array of array,

my @linearray; while (<readhandle>){ force @linearray, [] if /^frame/; force @{ $linearray[-1] }, $_ if @linearray; } utilize data::dumper; print dumper \@linearray;

regex perl search data-structures

java - Restlet Framework and Spring - Global filter -



java - Restlet Framework and Spring - Global filter -

i'm having problem restlet framework configuration spring. want have 1 global filter requests , responses. guess can utilize filter class , it's methods beforehandle, afterhandle , setnext this:

filter.beforehandle() -> router -> filter.afterhandle()

the problem is, i'm using spring configured restlet , don't know if regular filter work correctly springrouter org.restlet.ext.spring package. current restlet configuration follows:

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="root" class="org.restlet.ext.spring.springrouter"> <property name="attachments"> <map> <entry key="/login"> <bean class="org.restlet.ext.spring.springfinder"> <lookup-method name="create" bean="loginresource" /> </bean> </entry> </map> </property> </bean> </beans>

i'm thinking adding bean id root , class extends class filter, , pass property next bean id router (which called root). think solution?

mixing restlet classes spring extension other 1 shouldn't issue. spring* classes provide additional configurability.

java spring restlet

What does the attribute ?pfdrid_c=true mean in primefaces PDF object -



What does the attribute ?pfdrid_c=true mean in primefaces PDF object -

i read few posts attaching ?pfdrid_c=true attribute pdf object. , why utilize that. related posts using attribute:

primefaces <p:graphicimage /> throwing undefined function

jsf load uploaded images nested subfolders

pdf primefaces

php - Zpanel and cron job with cakephp -



php - Zpanel and cron job with cakephp -

i have tried , browsed lot regarding how set cron job cakephp , zpanel

in zpanel tried different types url

for illustration

domain_folder/app/cron_dispatcher.php /campaignmasters/newsletter_find_cron(error: script not exist)

then tried file domain_folder/app/cronjob.php(worked)

it worked confused how can phone call "domain_folder/app/cron_dispatcher.php /campaignmasters/newsletter_find_cron" cronjob.php

i in twisted state, have tried 10 hours trying many methods.

any zpanel or cakephp expert please tell me best way set cron job.

can add together cron job through ssh in zpanel? if can add together 1 through ssh "domain_folder/app/cron_dispatcher.php /campaignmasters/newsletter_find_cron" great. ready seek anything.

the os centos

i decided go out :)

step 1

create shell class can phone call actions command line.

http://book.cakephp.org/2.0/en/console-and-shells.html

class helloshell extends appshell { public function main() { $this->out('hello world.'); } }

step 2

try command you've created via ssh or terminal:

console/cake hello

you may have run command in app directory:

cd yourapp/app ../console/cake hello

step 3

create cron job using cron tab

crontab -e

vim or default text editor open. apply cron command there.

* 00 * * 6 php your_app_path/lib/cake/console/cake.php hello

checkout http://en.wikipedia.org/wiki/cron understand how occurrences work.

save , done!

php ssh cron cakephp-2.0 izpanel

Crystal Reports If Any Record Meets Condition, Exit Formula -



Crystal Reports If Any Record Meets Condition, Exit Formula -

i wish create formula read each record, , if status met formula stop reading records , homecoming specific label. have tried next code , right result displayed @ detail level not footer. appears "exit for" isn't working. help!

current code (i have placed in study footer):

shared stringvar label := ""; local numbervar i; := 1 {#count_records} ( if ({report_data.return_code}[i] = "defective-exchange" or {report_data.return_code}[i] = "defective") label := "defective-exchange only"; exit for; ); if label = "" label:="pickup credit memo"; label;

to eliminate data, utilize record-selection formula:

{report_data.return_code} = "defective-exchange" or {report_data.return_code} = "defective"

to format data, utilize formula field:

// {@return code} if {report_data.return_code} = "defective-exchange" or {report_data.return_code} = "defective" "defective-exchange only" else if {report_data.return_code} = "" "pickup credit memo" else "something else"

crystal-reports

html - Setting Inner Div width's percentage of parent -



html - Setting Inner Div width's percentage of parent -

i have 2 parent div's. (parent-left , parent-right). parent left 50px , parent right takes remaining screen width, set 100%.

i have 2 child/inner divs within parent-right. need take 85% , 15% of parent-right's width calculates percentage based on screen width. doing wrong?

code below:

<div class="row clearfix"> <div id='parent-left' style="width:50px;float:left;background-color:blue;"><span> parent-left </span> </div> <div id='parent-right' style="width:100%;"> <div id='inner-left' style="width:85%;float:left;background-color:green;"><span> inner1</span></div> <div id='parent-right' style="width:15%;float:left;background-color:gray"><span> inner2</span></div> </div> </div>

do not set width #parent-right element, instead set left-margin equal width of #parent-left element.

<div id='parent-right' style="margin-left:50px;">

demo @ http://jsfiddle.net/gaby/5j38g/

html html5

PHP Strip String, Convert to int -



PHP Strip String, Convert to int -

i have string $special formatted £130.00 , ex tax(vat) price.

i need strip first char can run simple addition.

$str= substr($special, 1, 0); // strip first char '£' echo $str ; // echo value check worked $endprice = (0.20*$str)+$str ; // work out vat

i don't receive value when echo on sec line ? need convert string integer in order run add-on ?

thanks

matt

+++ update

thanks help this, took code , added of own, there more nicer ways works :) found out if cost below 1000 £130.00 if cost larger value include break. ie £1,400.22.

$str = str_replace('£', '', $price); $str2 = str_replace(',', '', $str); $vatprice = (0.2 * $str2) + $str2; $display_vat_price = sprintf('%0.2f', $vatprice); echo "£"; echo $display_vat_price ; echo " (inc vat)";

thanks again, matt

you cannot utilize substr way using currently. because trying remove £ char, two-byte unicode character, substr() isn't unicode safe. can either utilize $str = substr($string, 2), or, better, str_replace() this:

$string = '£130.00'; $str = str_replace('£', '', $string); echo (0.2 * $str) + $str; // 156

original answer

i'll maintain version still can give insight. reply ok if £ wouldn't 2byte unicode character. knowing this, can still utilize need start sub-string @ offset 2 instead of 1.

your usage of substr wrong. should be:

$str = substr($special, 1);

check documentation 3rd param length of sub-string. passed 0, hence got empty string. if omit 3rd param homecoming sub-string starting index given in first param until end of original string.

php string int

sql server - How to select columns with other name in linq? -



sql server - How to select columns with other name in linq? -

i select records in sql server query seen below:

select productname 'some name1' , payment 'some name2' dbo.prefactorproduct

is there way select records in linq queries?

you can project result query anonymous type , utilize different alias/field names fields.

var query = db.prefactorproduct .select(r=> new { somename1 = r.productname, somename2 = r.payment });

but if trying format result set displaying purpose should in assigning column names grid/ info container.

sql-server linq multiple-columns

java - How can I properly use my value as an argument to JComboBox.setModel()? -



java - How can I properly use my value as an argument to JComboBox.setModel()? -

in code below, attempted create defaultlistmodel object utilize jcombobox.

apparently, setmodel() method accepts object comboboxmodel. attempted convert it, , got exception, java.lang.classcastexception.

i searched how prepare specific problem, couldn't find helpful.

i tried create comboboxmodel object instead, yet learned class abstract. how can bypass problem, , valid argument setmodel()?

private void setcomboboxyears(int numberofyears, jcombobox combobox) { defaultlistmodel<integer> years = new defaultlistmodel<>(); for(int = 1; <= numberofyears; i++) years.addelement(i); combobox.setmodel((comboboxmodel) years);

use defaultcomboboxmodel instead. please have @ api of info can gleaned simple glance.

java swing exception combobox defaultlistmodel

c# - .NET LINQ , List of Orders grouped by CustomerId across three tables? -



c# - .NET LINQ , List of Orders grouped by CustomerId across three tables? -

i have 3 tables in sql-database

orders (id, value, timestamp) customer(id, firstname, lastname) ordercustomer(id, customerid, ordersid)

i want accomplish list of results each object got customerid , related orders of customer.

i have seen illustration @ msdn.com, need, 2 tables:

dim customerlist = cust in customers grouping bring together ord in orders on cust.customerid equals ord.customerid customerorders = group, ordertotal = sum(ord.total) select cust.companyname, cust.customerid, customerorders, ordertotal

my code right gives me list customers , order, not grouped together. like:

customer 1 - order 1 customer 1 - order 5 customer 2 - order 2 customer 2 - order 3

customer 2 - order 36

dim results = customers in db.customers bring together ordercustomer in db.ordercustomer on customers.id equals ordercustomer.customerid grouping bring together orders in db_alt.orders on ordercustomer.orderid equals orders.id customerorders = group, ordertotal = sum(aufträge.order_value) select customers.firstname, customers.firstname, customerorders, ordertotal, customers.id

if foreign keys set up, linq sql or ef should see properties , can query this:

var result = db.customers.include("order") // ef

that should bring customers , each of them have collection of orders

or var result = db.customers.select(c=>new {customer = c, orders = c.orders}

c# sql vb.net linq

python - Returning lines containing two or more keywords -



python - Returning lines containing two or more keywords -

i want iterate through number of lines (containing text) , homecoming lines contain 2 or more of words in list of keywords.

i have been trying making wordlist , keywordlist sets utilize intersect function, like:

if len(set(line).intersection(set(keywords))) >1: print line

also tried various types of nested loops

if word in line

but no success yet.

you need utilize str.split , split line on whitespace before convert set:

if len(set(line.split()).intersection(set(keywords))) > 1:

see demonstration below:

>>> keywords = ['if', 'def', 'class'] >>> line = 'if def word' >>> len(set(line).intersection(set(keywords))) > 1 false >>> len(set(line.split()).intersection(set(keywords))) > 1 true >>>

without change, set of characters instead of set of words:

>>> line = 'if def word' >>> set(line) {' ', 'f', 'd', 'e', 'i', 'o', 'r', 'w'} >>> set(line.split()) {'word', 'if', 'def'} >>>

python set intersection

Yelp search Api in iOS -



Yelp search Api in iOS -

i working on app in have show accessories, cost & other info yelp. after lot of searching have found useful link: https://github.com/yelp/yelp-api/tree/master/v2/ios method not working me.

until have used single web service working & other's giving error missing parameter.

this working:

http://api.yelp.com/business_review_search?term=mobile&ywsid=pyhvqegfdlev******&tl_lat=37.9&tl_long=-122.5&br_lat=37.788022&br_long=-122.399797

is there api phone call returns me cost , offers & other info because above 1 review.

check answer: how search local business name, location in ios?

in success venue block info event

-(instancetype)initwithdict:(nsdictionary *)dict { self = [super init]; if (self) { self.name = [dict objectforkey:@"name"]; self.venueid = [dict objectforkey:@"id"]; self.thumburl = [dict objectforkey:@"image_url"]; self.ratingurl = [dict objectforkey:@"rating_img_url"]; self.yelpurl = [dict objectforkey:@"url"]; self.venueid = [dict objectforkey:@"id"]; self.reviewscount =[[dict objectforkey:@"review_count"] stringvalue]; self.categories = [dict objectforkey:@"categories"][0][0]; self.distance = [dict objectforkey:@"distance"]; self.price = [dict objectforkey:@"deals.options.formatted_price"]; self.address = [[[dict objectforkey:@"location"] objectforkey:@"address"] componentsjoinedbystring:@", "]; nsarray *adr = [[dict objectforkey:@"location"] objectforkey:@"display_address"]; self.displayaddress = [adr componentsjoinedbystring:@","]; } homecoming self;

}

ios yelp

winforms - C# OOP concepts: is inheritance from Control class the right way? -



winforms - C# OOP concepts: is inheritance from Control class the right way? -

my question right way of code writing. utilize c# winforms. created instance of command class (anyone available in designer), illustration panel class, set properties of object, subscribed events, wrote event handlers, etc. next way: create custompanel class inherited panel , white above code (setting properties, subscribing events, event handlers) in custompanel class. so, when want utilize panel setting , functionality, can drag , drop custompanel object designer. right way or interitance command classes isn't idea? maybe should create own class (not inherited) contains panel settings , bind panel?

use decorators when possible

using visual inheritance windows form designer very buggy, lot of times designer doesn't work , on top of never works when controls in 64 bit assembly http://support.microsoft.com/kb/967050

c# winforms oop inheritance

Python convert list to tree representation format -



Python convert list to tree representation format -

me , friend working on simple python project. implementing prefix parallel sum algorithm in our own way.

we creating , processing binary tree weird format. convert format 1 accepted tree printing libraries/software ete2.

so, every level of tree pushed in list in way

[ [level0], [level1], ... [level i-1], [root] ]

in our format every internal list (tree's level) has number of nodes or leaves.

for instance, have input: [1, 2, 3, 4, 5]. produce next output list: [[1, 2, 3, 4], [3, 7], [10, 5], [15]]

the issue above output illustration leaves not on lastly level, included in upper level lists. makes hard process list of lists , distinguish nodes leaves , arrange them in right position.

we visualize follows:

http://i.imgur.com/bkrqnzi.png

where numbers included in parenthesis nodes , other ones leaves.

in order produce output tree, utilize 1 tree drawing library. of them expect type of format: [root, [left], [right]]

so, in our illustration our format should this:

[15, [10, [3, [1], [2]], [7, [3], [4]] ], [5] ]

because not in position @ moment rewrite whole logic of our code, looking smart way convert our weird format one.

any ideas welcome. give thanks much in advance.

you can take advantage of fact element in row r, col c of tree, left , right kid elements @ position c*2 , c*2+1 of next row, respectively, if elements exist (otherwise node leaf). set algorithms:

def normalize(tree, row=0, col=0): try: node = tree[row][col] left = normalize(tree, row+1, col*2) right = normalize(tree, row+1, col*2+1) homecoming [node, left, right] if left or right else [node] except: homecoming none # kid index not exist

example:

>>> tree = [[1, 2, 3, 4], [3, 7], [10, 5], [15]] >>> print normalize(tree[::-1]) # reverse list! [15, [10, [3, [1], [2]], [7, [3], [4]]], [5]]

python list binary-tree prefix-sum

Android ads google play services is missing -



Android ads google play services is missing -

i tried adding admob ads android app, works fine on emulator, ads shown , no problems whatsoever.

however, when app on android device, message in logcat: w/googleplayservicesutil(1424): google play services missing.

and no ads shown, whereas on emulator ads shown (test ads though).

i have included google-play-services-lib project.

thanks

update sdk latest google apis. create emulator (or re-create existing one) target google api (for e.g. 19). worked me.

android service admob ads

function - php web mail application -



function - php web mail application -

i developing web application handle email list, , know how set send emails when application in localhost. using mail() function, getting failed connect server error. using php , apache. give thanks you.

yes, can send via smtp. here phpmailer, opensource library sending emails using php:

https://github.com/phpmailer/phpmailer/

php function email

Return true in jquery ajax -



Return true in jquery ajax -

i using ajax within jquery check whether value exist in database or not. can utilize normal select query(php) this, have create alert popup if value exist. that's why decide way. done, problem due homecoming false in jquery not allow next line eventhough name not exist in database. how can give homecoming true in particular place?

$.ajax({ type:"post", url:"actionn.php", data:"name="+name, success:function(data){ alert(data); //if info not exist means should out of ajax function } }); homecoming false; //if info exists if(name=="") //data not exist means should come here { alert("please come in name"); homecoming false; }

as t.niese pointed out return true (or false) within success not doing expect do. (see first comment under question).

probably straight-forward way accomplish goal utilize whatever code have if user (doest not) exists within success.

so move logic/code when user exists/doesn't exist within success callback. for more insights should read of links provided in comments

edit: think miss understand concept of asynchronous request - given comments in code

$.ajax({ type:"post", url:"actionn.php", data:"name="+name, success:function(data){ alert(data); //if info not exist means should out of ajax function //ajax function has "exited" here success callback //this code executed when request action.php succesfull //as in response code 200/ok } }); //return false; //if info exists //nope, don't know if info exists code //executed _while_ (!) request action.php made! //there no guarantee when request returns , can't write code //here relies on response //if(name=="") //data not exist means should come here //{ // alert("please come in name"); // homecoming false; //}

what want write this:

$.ajax({ type:"post", url:"actionn.php", data:"name="+name, success:function(data){ if(name==""){ alert("please come in name"); }else{ alert("your name is: "+data); } } });

crisp , short. logic depending on server's response handleded inside successcallack. there no code after $.ajax in way dependant on data.

please refrain returning in $.ajax.success - it's not believe is

for farther question i'd invite (again) read ajax call's: http://stackoverflow.com/a/14220323/1063730 think paragraph restructuring code highly interesting you.

jquery ajax

php - My contact form is working but it won't show the success message -



php - My contact form is working but it won't show the success message -

my contact form working success message doesn't show. developer wrote php code did of jquery , won't display message. i'm pretty sure problem jquery. i'm particularly confused line of code...

$("#result").hide().html(output).slidedown(); }, 'json'); }

i think want utilize .show() since #result needed show html didn't seem trick. total code below.

$(function(){ $(".btn").click(function() { //get input field values var user_name = $('input[name=name]').val(), user_email = $('input[name=email]').val(), user_message = $('textarea[name=message]').val(), proceed = true; //simple validation @ client's end //we alter border color reddish if empty field using .css() if(user_name===""){ $('input[name=name]').css('border','2px solid red').after('<p class="error-msg">(what\'s name?)</p>'); proceed = false; } if(user_email===""){ $('input[name=email]').css('border','2px solid red').after('<p class="error-msg">(please provide valid email)</p>'); proceed = false; } if(user_message==="") { $('textarea[name=message]').css('border','2px solid red').after('<p class="error-msg">(please allow me know enquiry about)</p>'); proceed = false; } //everything looks good! proceed... if(proceed) { //data sent server post_data = {'username':user_name, 'useremail':user_email, 'usermessage':user_message}; //ajax post info server $.post('../../contact-form.php', post_data, function(response){ //load json info server , output message if(response.type === 'error') { output = '<div class="error">'+response.text+'</div>'; }else{ output = '<div class="success">'+response.text+'</div>'; alert('thanks message'); //reset values in input fields $('.form-container input').val(''); $('.form-container textarea').val(''); } $("#result").hide().html(output).slidedown(); }, 'json'); } }); //reset set border colors , hide message on .keyup() $(".form-container input, .form-container textarea").keyup(function() { $(".form-container input, .form-container textarea").css('border-color',''); $("#result").slideup(); }); });

php code

<?php if($_post)

{ $to_email = "alexechaparro@gmail.com"; //replace recipient email address $subject = 'alexsdogvacay.com'; //subject line emails

//check if ajax request, exit if not if(!isset($_server['http_x_requested_with']) , strtolower($_server['http_x_requested_with']) != 'xmlhttprequest') { //exit script outputting json info $output = json_encode( array( 'type'=>'error', 'text' => 'request must come ajax' )); die($output); } var_dump($_request); //check $_post vars set, exit if missing if(!isset($_post["username"]) || !isset($_post["useremail"]) || !isset($_post["usermessage"])) { echo $_post["username"]; $output = json_encode(array('type'=>'error', 'text' => 'input fields empty!')); die($output); } //sanitize input info using php filter_var(). $user_name = filter_var($_post["username"], filter_sanitize_string); $user_email = filter_var($_post["useremail"], filter_sanitize_email); $user_message = filter_var($_post["usermessage"], filter_sanitize_string); //additional php validation if(strlen($user_name)<4) // if length less 4 throw http error. { $output = json_encode(array('type'=>'error', 'text' => 'name short or empty!')); die($output); } if(!filter_var($user_email, filter_validate_email)) //email validation { $output = json_encode(array('type'=>'error', 'text' => 'please come in valid email!')); die($output); } if(strlen($user_message)<5) //check emtpy message { $output = json_encode(array('type'=>'error', 'text' => 'too short message! please come in something.')); die($output); } //proceed php email. /* incase host allows emails local domain, should un-comment first line below, , remove sec header line. of-course need come in own email address here, exists in cp. */ //$headers = 'from: your-name@your-domain.com' . "\r\n" . $headers = 'from: '.$user_email.'' . "\r\n" . //remove line if line above un-commented 'reply-to: '.$user_email.'' . "\r\n" . 'x-mailer: php/' . phpversion(); // send mail service $sentmail = @mail($to_email, $subject, $user_message .' -'.$user_name, $headers); if(!$sentmail) { $output = json_encode(array('type'=>'error', 'text' => 'could not send mail! please check php mail service configuration.')); die($output); }else{ $output = json_encode(array('type'=>'message', 'text' => 'hi '.$user_name .' give thanks email. possible.')); die($output); }

} ?>

so, line of code that's confusing: $('#result').hide().html().slidedown(); works. no need changing that. 1 problem see variable output isn't beingness defined var making global variable.

that aside, php code seems kill success response die function, bc doesn't homecoming output. alter this:

if(!$sentmail) { $output = json_encode(array('type'=>'error', 'text' => 'could not send mail! please check php mail service configuration.')); die($output); }else{ $output = json_encode(array('type'=>'message', 'text' => 'hi '.$user_name .' give thanks email. possible.')); die($output); }

to:

if(!$sentmail) { $output = json_encode(array('type'=>'error', 'text' => 'could not send mail! please check php mail service configuration.')); }else{ $output = json_encode(array('type'=>'message', 'text' => 'hi '.$user_name .' give thanks email. possible.')); } echo $output;

hope helps!

t

php jquery ajax forms

ajax - jQuery JSONP parse error -



ajax - jQuery JSONP parse error -

i'm working on phonegap project uses jquery ajax info our online app.

here code using:

$.ajax({ type: 'get', url: home , async: false, datatype: "jsonp", jsonpcallback: 'jsoncallback', data: {action: 'get_survey', survey: survey_id}, success: function (result) { $.mobile.loading( 'hide', {}); display_survey(result); }, error: function (request,error) { $.mobile.loading( 'hide', {}); alert(error); } });

here info beingness returned server:

jsoncallback({"symptoms":{"ent":["does not pay attending details or makes careless mistakes wiht, example, homework","has difficulty keeping attending needs done","does not seem hear when spoken directly","does not follow through when given directions , fails finish activities (not due refusal or vailure understand)","has difficulty organizing tasks , activities","avoids, dislikes, or not want start tasks require ongoing mental effort","loses things necessary tasks or activities (toys, assignments, pencils or books","is distracted noises or other stimuli","is forgetful in daily activities","fidgets hands or feet or squirms in seat","leaves seat when remaining seated expected","runs or climbs much when remaining seated expected","has difficulty playing or origin quiet play activities","is 'on go' or acts if 'driven motor'","talks much","blurts out answers before questions have been completed","has difficulty waiting or turn","interrupts or intrudes on others' conversations and\/or activities","argues adults","loses temper","actively defies or refuses go along adults' requets or rules","deliberately annoys people","blames others or mistakes or misbehaviors","is touchy or annoyed others","is angry or resentful","is spiteful , wants even","bullies, threatens, or intimidates others","starts physical fights","lies out of problem or avoid obligations (ie, 'cons' others)","is truant school (skips school) without permission","is physically cruel people","has stolen things have value","deliberately destroys others' property","has used weapon can cause serious harm (bat, knife, brick, gun)","is physically cruel animals","has deliberately set fires cause damage","has broken else's home, business or car","has stayed out @ night without permission","has run away home overnight","has forced sexual activity","is fearful, anxious or worried","is afraid seek new things fear of making mistakes","feels worthless or inferior","blames self problems, feels guilty","feels lonely, unwanted or unloved; complains 'no 1 loves him or her'","is sad, unhappy or depressed","is self-conscious or embarrrassed"]},"performance":{"ent":["overall school performance","reading","writing","mathematics","relationship parents","relationship siblings","relationship wiht peers","participation in organized activities (eg, teams)"]}})

right now, testing app in browser. when pg app called same server online app, works fine. however, if pg app on different server, 'parseerror' jquery , error function triggerd.

however, when in console, can see pg app receiving of data.

am missing when set-up jsonp call?

i think need alter jsonpcallback:'jsonpcallback' bit jsonpcallback: function() { alert('foo'); }

jquery ajax jsonp

How can I access the "red bubble" notifications in AtTask through the API? -



How can I access the "red bubble" notifications in AtTask through the API? -

is possible own reddish bubble notifications show in attask through api? what's objcode?

attask

java - What design pattern would fit my needs? -



java - What design pattern would fit my needs? -

i have next class:

public class { private string a; private long b; private date c; //getters, setters, constructors }

and need able export excel different templates. example, 1 excel has next headers: b c

another excel has next template: b c

and template this: b a

what way design code format object according 1 template or another? there particular design pattern can at?

i think can utilize adapter pattern, need create different adapter different templates.

bind object adapter , logic in adapter assign value passed object template want fill values.

by making adapter can create new format without making alter in existing format, create code more maintainable , separate.

this rough thought concept can apply here, still have scope of making many modification in it.

adapter interface

public interface adapter { }

adapter class

public class format2adapter implements adapter { private long title; string subtitle; public void filltemplate(core c){ title = c.getb(); } }

format2adapter class

public class format2adapter implements adapter { private long title; string subtitle; public void filltemplate(core c){ title = c.getb(); } }

business object class

import java.util.date; public class core { private string a; private long b; private date c; public string geta() { homecoming a; } public void seta(string a) { this.a = a; } public long getb() { homecoming b; } public void setb(long b) { this.b = b; } public date getc() { homecoming c; } public void setc(date c) { this.c = c; } // getters, setters, constructors }

java design-patterns architecture

sharding - MongoDB presplitting chunks for compound shard key -



sharding - MongoDB presplitting chunks for compound shard key -

in mongodb setup have compound shard key {"region" : 1, "foo" : 1, "bar" : 1} , know values part can , each part should on 1 chunk.

therefore i'd pre-split based on part key only. sharding status should afterwards:

{ "region": { "$minkey" : 1 }, "foo": { "$minkey" : 1 }, "bar": { "$minkey" : 1 } } -> { "region": region1, "foo": { "$minkey" : 1 }, "bar": { "$minkey" : 1 } } on: shard1 { "region": region1, "foo": { "$minkey" : 1 }, "bar": { "$minkey" : 1 } } -> { "region": region2, "foo": { "$minkey" : 1 }, "bar": { "$minkey" : 1 } } on: shard2 { "region": region2, "foo": { "$minkey" : 1 }, "bar": { "$minkey" : 1 } } -> { "region": { "$maxkey" : 1 }, "foo": { "$minkey" : 1 }, "bar": { "$minkey" : 1 } } on: shard3

i've tried ways accomplish that, nil worked:

db.runcommand( { split : "mydb.mycollection" , middle : { "region" : "region1" } } ); homecoming error, because finish shard key have part of split. db.runcommand( { split : "mydb.mycollection" , middle : { "region" : "region1", "foo" : { "$minkey" : 1 }, "bar" : { "$minkey" : 1 } } } ); , db.runcommand( { split : "mydb.mycollection" , middle : { "region" : "region1", "foo" : "$minkey" , "bar" : "$minkey" } } ); interpret minkey string , split on base of operations wrong.

how can split chunks compound shard key on single field base?!

cheers.

mongodb sharding

java - Reading files of different types in ByteBuffer -



java - Reading files of different types in ByteBuffer -

in java application (fuse file system) need read types of files bytebuffer. did below:

public int read(final string path, final bytebuffer buffer, final long size, final long offset, final fileinfowrapper info) { path p = paths.get(path); seek { byte[] info = files.readallbytes(p); buffer.put(bytebuffer.wrap(data)); homecoming data.length; } grab (ioexception e) { // todo auto-generated grab block e.printstacktrace(); }

but *.txt extensions files read correctly (i think because of less size, larger *.txt files not read correctly). rest of file types not correctly read.

these errors shown file type specific applications while opening files

it throws these errors while reading files other *.txt

severe: exception thrown: java.nio.bufferoverflowexception java.nio.directbytebuffer.put(directbytebuffer.java:357) java.nio.directbytebuffer.put(directbytebuffer.java:336) org.organization.upesh.firstmaven.sfs_360.read(sfs_360.java:132) net.fusejna.loggedfusefilesystem$27.invoke(loggedfusefilesystem.java:437) net.fusejna.loggedfusefilesystem$27.invoke(loggedfusefilesystem.java:433) net.fusejna.loggedfusefilesystem.log(loggedfusefilesystem.java:355) net.fusejna.loggedfusefilesystem.read(loggedfusefilesystem.java:432) net.fusejna.fusefilesystem._read(fusefilesystem.java:234) net.fusejna.structfuseoperations$23.callback(structfuseoperations.java:260) sun.reflect.generatedmethodaccessor8.invoke(unknown source) sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43) java.lang.reflect.method.invoke(method.java:606) com.sun.jna.callbackreference$defaultcallbackproxy.invokecallback(callbackreference.java:455) com.sun.jna.callbackreference$defaultcallbackproxy.callback(callbackreference.java:485)

and reading process slow.

what right way read types of file correctly , @ speed.

p.s. whatever solution suggest, reading file bytebuffer must , must returns number of bytes transferred.

please read function signature of what you're trying implement.

public int read(final string path, final bytebuffer buffer, final long size, final long offset, final fileinfowrapper info)

as can see, there's size , offset argument there. function supposed read size number of bytes file @ most, , supposed read them offset offset file. function not supposed read everything. provided illustration filesystem shows how this.

java file-io

Bootstrap responsive not responding in smartphones -



Bootstrap responsive not responding in smartphones -

i have problem this website

when resize browser window in laptop responsiveness works well, when load website in smartphone shows desktop version.

i found similar problem there's no clear answer.

i thought code seek bootstrap template, problem still remains.

the problem loading page through iframe. page linked is:

http://arwink.com/test

but there total screen iframe on page loads:

http://www.bondzu.com/template/test/

if view sec link in phone, see resizes accordingly. first link not. because first link missing head tag:

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

if add together first page, should work, have never tried load mobile page through iframe on mobile page before, can't speak direct experience.

twitter-bootstrap

AngularJS How to skip element submission when element is hidden -



AngularJS How to skip element submission when element is hidden -

i have dropdown list enum values. when dropdownlist hidden ng-show, value still submitted ''. getting

org.codehaus.jackson.map.jsonmappingexception: can not build instance of myenum string value '': value not 1 of declared enum instance names @ [source: com.ibm.ws.webcontainer.srt.http.httpinputstream@1024cb7e; line: 1, column: 349]

how skip validation/submission?

<select ng-show="itishidenow()" ng-model="value.myenum" ng-options="option alternative in myenumoptions"> </select>

check if element visible before submit:

$("#dropdown").is(":visible")

angularjs

android - How to make an object global in Javascript? -



android - How to make an object global in Javascript? -

i made little phonegap/cordova application, , need access object within .js file. turns out have no thought on how alter construction of code create happen.

here index.html code :

<!doctype html> <html> <head> <title>nfc tag id reader</title> <script type="text/javascript" src="js/index.js"></script> <script type="text/javascript" charset="utf-8"> // wait device api libraries load document.addeventlistener("deviceready", ondeviceready, false); // device apis available function ondeviceready() { window.requestfilesystem(localfilesystem.persistent, 0, gotfs, fail); } function gotfs(filesystem) { filesystem.root.getfile("readme.txt", {create: true, exclusive: false}, gotfileentry, fail); } function gotfileentry(fileentry) { fileentry.createwriter(gotfilewriter, fail); } function gotfilewriter(writer) { writer.onwriteend = function(evt) { console.log("contents of file 'some sample text'"); writer.truncate(11); writer.onwriteend = function(evt) { console.log("contents of file 'some sample'"); writer.seek(4); writer.write(" different text"); writer.onwriteend = function(evt){ console.log("contents of file 'some different text'"); } }; }; writer.write("some sample text"); //make object global ? } function fail(error) { console.log(error.code); } </script> </head> <body> <div class="app"> <script type="text/javascript"> app.initialize(); </script> </body> </html>

and here index.js code :

var app = { /* application constructor */ initialize: function() { this.bindevents(); console.log("starting nfc reader app"); }, /* bind events required on startup listeners: */ bindevents: function() { document.addeventlistener('deviceready', this.ondeviceready, false); }, /* runs when device ready user interaction: */ ondeviceready: function() { nfc.addtagdiscoveredlistener( app.onnfc, // tag scanned function (status) { // listener initialized app.displaycpt("<b>"+cpt+"</b>" + ' personnes restantes.'); app.displaybjr("\n"); app.displaybjr("identifiez-vous:"); }, function (error) { // listener fails initialize app.display("nfc reader failed initialize " + json.stringify(error)); } ); }, /* displays tag id @nfcevent in message div: */ onnfc: function(nfcevent) { var tag = nfcevent.tag; var nfcuid = nfc.bytestohexstring(tag.id); var mydb = { "04c85ccab52880": { "name": "name", "firstname": "fname", "societe": "work" } var mapped = object.keys(mydb).map(function(uid){ homecoming (mydb[uid].uid = uid) && mydb[uid]; }); for(var = 0; < mapped.length ; i++){ if(mapped[i]['uid'] != nfcuid){ mapped[i]['uid'] += 1; } else { mapped[i]['uid'] = nfcuid; app.display(mapped[i]['name'] + ' ' + mapped[i]['firstname'] + ', ' + mapped[i]['societe']); writer.write(mapped[i]['name'] + ' ' + mapped[i]['firstname'] + ', ' + mapped[i]['societe']); //i need author usable in order write array content file } } }, }; // end of app

i think writer object needs global in order create mapped array write file, can't find way that.. ideas ?

thanks

have tried putting var writer outside of , removing arguments list of gotfilewriter(writer)? should create global variable. note isn't best of programming practices, 1 should avoid global variables possible.

javascript android cordova

jquery - Form with multiple buttons - all are submitting the form -



jquery - Form with multiple buttons - all are submitting the form -

my form, 'file-upload' has submit button:

<button id="btn-save" type="submit">save</button>

i utilize so:

$('#file-upload').submit(this.save.bind(this));

the problem is, form has other buttons in it:

<button class="btn-delete">&times;</button>

and these appear running this.save method.

how can prevent this?

this know behavior, <button> s within form tag deed submit button, either need prevent default behavior event.preventdefault() or alter buttons <input type='button'>

jquery

python - How to install psycopg2 for python2.6 when there is also 2.7 installed? -



python - How to install psycopg2 for python2.6 when there is also 2.7 installed? -

i tried install psycopg2 python2.6 scheme has 2.7 installed.

i did

>sudo -e pip install psycopg2 downloading/unpacking psycopg2 downloading psycopg2-2.5.3.tar.gz (690kb): 690kb downloaded running setup.py (path:/private/var/folders/yw/qn50zv_151bfq2vxhc60l8s5vkymm3/t/pip_build_root/psycopg2/setup.py) egg_info bundle psycopg2 installing collected packages: psycopg2 running setup.py install psycopg2 building 'psycopg2._psycopg' extension cc -dndebug -g -fwrapv -os -wall -wstrict-prototypes -qunused-arguments -qunused-arguments -arch x86_64 -arch i386 -pipe -dpsycopg_default_pydatetime=1 -dpsycopg_version="2.5.3 (dt dec pq3 ext)" -dpsycopg_extensions=1 -dpsycopg_new_boolean=1 -dhave_pqfreemem=1 -dpg_version_hex=0x09010b -dpsycopg_extensions=1 -dpsycopg_new_boolean=1 -dhave_pqfreemem=1 -i/system/library/frameworks/python.framework/versions/2.7/include/python2.7 -i. -i/usr/local/cellar/postgresql91/9.1.11/include -i/usr/local/cellar/postgresql91/9.1.11/include/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.9-intel-2.7/psycopg/psycopgmodule.o ...

you can see pip associating psycopg2 python2.7 during install process. pip install completed reported success result when ran 2.6 script after that imports psycopg2, couldn't find it:

import psycopg2 importerror: no module named psycopg2

how install psycopg2 python2.6 when there 2.7 installed?

as per this answer, installed pip2.6. installed psycopg2 using pip2.6 command , not pip before:

sudo -e pip2.6 install psycopg2

then worked

python pip psycopg2

Reverse GeoCoding Issues with OpenStreetMap/Nominatim -



Reverse GeoCoding Issues with OpenStreetMap/Nominatim -

i'm wondering kind of sense these results do? afaik, response strange. house number, expect getting total address, or to the lowest degree city, county country or so. http://nominatim.openstreetmap.org/reverse?format=json&lat=0.01&lon=0.01&zoom=18&addressdetails=1 info returned house number 4. {"house_number":"4"}

take @ returned object. located somewhere in atlantic ocean , consequently can't have total address. not response unusual object is. delete it.

geocoding openstreetmap nominatim

swift - Fill an array with strings from a txt file -



swift - Fill an array with strings from a txt file -

data.txt contains stuff this : "cat" "dog" "mouse"

i want fill array strings file (dico[0] = "cat", dico[1] = "dog", aso).

i found this, how phone call objective-c's nsarray class method within swift? , read , write info text file, when utilize code :

let bundle = nsbundle.mainbundle() allow path = bundle.pathforresource("data", oftype: "txt") allow dico = nsarray(contentsoffile: path) println("\(dico[0])") println("\(dico.count)")

all "nil" , "0".

i guess info in file aren't written way should , code utilize isn't right, can't figure why.

moreover, when utilize code, it's ok :

allow bundle = nsbundle.mainbundle() allow path = bundle.pathforresource("data", oftype: "txt") allow dico = nsstring(contentsoffile: path) println("\(dico)")

the problem don't want dico string, want array.

this not how arraywithcontentsoffile works.

it expects argument path file containing string representation of array produced writetofile:atomically: method.

for purposes, can utilize sec approach, complemented calling componentsseparatedbystring() on string.

let bundle = nsbundle.mainbundle() allow path = bundle.pathforresource("data", oftype: "txt") allow dico = nsstring(contentsoffile: path).componentsseparatedbystring("\n")

arrays swift

image processing - Python array manipulation using numpy -



image processing - Python array manipulation using numpy -

i trying replicate border of array:

a=[1,2],[3,4]

and want result as

[1,1,1,2,2,2] [1,1,1,2,2,2] [1,1,1,2,2,2] [3,3,3,4,4,4] [3,3,3,4,4,4] [3,3,3,4,4,4]

how do in python? using

import numpy (a,2,reflect') or wrap not getting array

you can utilize nested repeat method (example in ipython):

in [1]: import numpy np in [2]: = np.array([[1,2],[3,4]]) in [3]: a.repeat(3, 1).repeat(3, 0) out[3]: array([[1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2], [3, 3, 3, 4, 4, 4], [3, 3, 3, 4, 4, 4], [3, 3, 3, 4, 4, 4]])

but image manipulation migth want have @ e.g:

python imaging library (or newer variant, pillow) python interfaces imagemagick suite

especially imagemagick provides lot of image manipulation tools.

python image-processing numpy scipy

php - Convert numerical date into Datetime object -



php - Convert numerical date into Datetime object -

just wondered best way convert date in next format: 02072014 (2nd july 2014) \datetime object? i've tried:

$date = datetime::createfromformat("jmy", $digits);

but didn't seem work. i'm using date format because it's beingness entered on phone keypad.

cheers,

ewan

the function definition of createfromformat()

public static datetime datetime::createfromformat ( string $format , string $time [, datetimezone $timezone ] )

so need

$digits = '02072014'; $date = datetime::createfromformat('dmy',$digits); echo $date->format("j m y");

set info in desired format.

$date->format("j m y");

php date datetime

node.js - Appending to agrument object in javascript -



node.js - Appending to agrument object in javascript -

the arguments variable returns object like:

console.log(arguments) => { '0': 'arg1', '1': function[] }

what if wanted append , shift right?

{ '0': 'add', '1': 'arg1', '2': function[] }

how can accomplish this? manually or underscorejs

useful info underscore:

oarray_.toarray(list)

creates real array list (anything can iterated over). useful transmuting arguments object.

did like:

var args = _.toarray(arguments) args.unshift(fn)

you can apply array unshift method on arguments object:

array.prototype.unshift.call(arguments, "add");

however, it's improve not mess arguments object. rather convert array, prepend "add" that, , utilize instead of arguments in function body:

var args = ["add"].concat(array.prototype.slice.call(arguments)); var args = ["add"].concat(_.toarray(arguments));

javascript node.js

integer - Convert hexadecimal file into unsigned int 32 Big-Endian in Java -



integer - Convert hexadecimal file into unsigned int 32 Big-Endian in Java -

it might question asked, have not found satisfactory reply yet out there. in particular because conversion has been done in c or c++.

btw, how convert hexadecimal file (200mb) uint32 big-endian representation in java?

this illustration of trying achieve:

54 00 00 00 -> 84 55 f1 2e 04 -> 70185301 a2 3f 32 01 -> 20070306 , on

edit

file fileinputstring = new file(inputfilefield.gettext()); fileinputstream fin = new fileinputstream(fileinputstring); fileoutputstream out = new fileoutputstream(filedirectoryfolder.gettext() +"/"+ fileinputstring.getname()); byte[] filecontent = new byte[(int)fileinputstring.length()]; fin.read(filecontent); system.out.println("file lenght" + filecontent.length); for(int = 0; < filecontent.length; i++){ byte b = filecontent[i]; // boxing conversion converts `byte` `byte` int value = b.intvalue(); out.write(value); } close(); system.out.println("done");

edit 2

file fileinputstring = new file(inputfilefield.gettext()); fileinputstream fin = new fileinputstream(fileinputstring); fileoutputstream out = new fileoutputstream(filedirectoryfolder.gettext() +"/"+ fileinputstring.getname()); bytearrayoutputstream bos = new bytearrayoutputstream(); byte[] filecontent = new byte[(int)fileinputstring.length()]; system.out.println("file lenght" + filecontent.length); int bytesread; while (( bytesread = fin.read(filecontent)) != -1) { bytebuffer.wrap(filecontent).order(byteorder.little_endian).getlong(); bos.write(filecontent, 0, bytesread); } out.write(bos.tobytearray()); system.out.println("done");

edit 3

dataoutputstream out = new dataoutputstream(new fileoutputstream(output)); datainputstream in = new datainputstream(new fileinputstream(input))) { int count = 0; while (count < input.length() - 4) { in.readfully(buffer, 4, 4); string s=long.tostring(bytebuffer.wrap(buffer).order(byteorder.little_endian).getlong()); out.writebytes( s + " "); count += 4; }

thanks

the next code should suffice. uses long values ensure can represent range of positive values 4 bytes can represent.

note: code assumes hex input 4 bytes. may want add together more checks , measures in production code.

private static long tolong(string hex) { hex = hex.replace(" ", "") + "00000000"; byte[] info = datatypeconverter.parsehexbinary(hex); homecoming bytebuffer.wrap(data).order(byteorder.little_endian).getlong(); } public static void main(string[] args) throws exception { system.out.println(tolong("54 00 00 00")); system.out.println(tolong("55 f1 2e 04")); system.out.println(tolong("a2 3f 32 01")); system.out.println(tolong("ff ff ff ff")); }

output:

84 70185301 20070306 4294967295

based on recent edits, propose code such following. note assumes input multiple of 4 bytes in length. left-over bytes ignored:

file input = new file("whatever"); byte[] buffer = new byte[8]; list<long> result = new arraylist<>(); seek (datainputstream in = new datainputstream(new fileinputstream(input))) { int count = 0; // note: trailing bytes ignored while (count < input.length() - 4) { in.readfully(buffer, 4, 4); result.add(bytebuffer.wrap(buffer) .order(byteorder.little_endian).getlong()); count += 4; } }

java integer big-endian

Guice injector for library -



Guice injector for library -

i writing new java library , want utilize guice here. library going depend on other guice modules. understand while creating guice application @ point of time guice.createinjector(...). question should create injector in library there many entry points it.

ideally clients of library using jsr-330 , add together modules own injectors. if isn't feasible require clients phone call initialization method of library setup modules, create injector, , homecoming simple mill or provider object (injected guice) providing access necessary entry points of api.

guice

javascript - Clip Google Maps JS API ImageMapType to a polygon -



javascript - Clip Google Maps JS API ImageMapType to a polygon -

how can clip maptype in google maps arbitrary polygon. example, if have custom imagemaptype covers big area (i.e. world), want show within given polygon (i.e. 1 country).

is there way clip imagemaptype given polygon, or implement custom maptype accomplish behaviour? should allow zooming , panning normally.

the rest of map should remain same, , there maptype covering specific area. therefore, not possible overlay polygon cover areas outside polygon display needed.

like so:

server-side clipping not option.

you place div above map, absolute positioning , high z-index. then, apply polygon mask div this: -webkit-clip-path: polygon(0 0, 0 100%, 100% 0);

javascript google-maps google-maps-api-3

jquery - Is it possible to create a custom html attr as a tag -



jquery - Is it possible to create a custom html attr as a tag -

is possible add together custom attribute in format html element.

<div class="example" editor:edit></div>

( bit mailchimp's merge tags)

if so, how go targeting element, preferably jquery.

mdn's html attribute reference implies should never create non-standard attributes.

this purpose of data-* attribute, description in list is: lets attach custom attributes html element.

jquery html mailmerge

r - Preserve column names when ddply returns empty dataframe -



r - Preserve column names when ddply returns empty dataframe -

i using ddply homecoming dataframe, if returned dataframe each element of initial dataframe contains no rows final output empty dataframe 1 column, initial variable. want homecoming empty dataframe columns have returned if did have data.

for illustration if have next

y <- data.frame(a = 1:5, b = 6:10) res1 <- ddply(y, .(a), function(x) subset(x, b == 6)) res2 <- ddply(y, .(a), function(x) subset(x, b == 5))

res1 returns dataframe column & b, whereas res2 returns column - homecoming empty dataframe columns , b.

running next works

res3 <- dlply(y, .(a), function(x) subset(x, b == 5)) res3 <- do.call('rbind', res3)

but there way in 1 go using ddply?

thanks in advance

r plyr

ember.js - Ember-Data "TypeError: this.container is undefined" -



ember.js - Ember-Data "TypeError: this.container is undefined" -

i'm trying load current user info store having difficulty. server uses passportjs , visiting /api/users/me returns json object similar this:

{"user":{"_id":"53a4d9c4b18d19631d766980","email":"ashtonwar@gmail.com", "last_name":"war","first_name":"ashton","location":"reading, england", "birthday":"12/24/1993","gender":"male","fb_id":"615454635195582","__v":0}}

my store defined app.store = ds.store.create();

the controller retrieve current user is:

app.userscurrentcontroller = ember.objectcontroller.extend({ content: null, retrievecurrentuser: function() { var controller = this; ember.$.getjson('api/users/me', function(data) { app.store.createrecord('user', data.user); var currentuser = app.store.find(data.user._id); controller.set('content', currentuser); }); }.call() });

it called application controller:

app.applicationcontroller = ember.controller.extend({ needs: "userscurrent", user: ember.computed.alias("controllers.userscurrent") });

i suspect line app.store.createrecord('user', data.user); causing issues don't have thought how prepare it.

the console logs typeerror: this.container undefined while ember debugger shows every promise fulfilled , users.current controller has no content. thankyou help can provide.

are defining store on app namespace, because ember info doesn't default. either way, you're failing define type want find after create record.

var currentuser = controller.store.find('user', data.user._id);

createrecord returns record, there no point in finding afterward

var currentuser = controller.store.createrecord('user', data.user);

also in example, trying phone call function on type, , not on instance. should add together method run on init.

app.userscurrentcontroller = ember.objectcontroller.extend({ retrievecurrentuser: function() { console.log('hello') var controller = this; ember.$.getjson('api/users/me', function(data) { var user = controller.store.createrecord('user', data.user); controller.set('model', user); }); }.on('init') });

http://emberjs.jsbin.com/oxidivu/693/edit

ember.js controller ember-data containers store

spring data rest - Can't POST a collection -



spring data rest - Can't POST a collection -

i have simple entity single collection mapped.

@entity public class appointment identifiable<integer> { @id @generatedvalue(strategy = generationtype.auto) @jsonignore private integer id; @column(name="trak_nbr") private string tracknumber; @onetomany(fetch =fetchtype.eager, cascade= cascadetype.all) @joincolumn(name="cnsm_apt_ver_wrk_i", nullable = false) private set<product> products = new hashset<product>(); } @entity public class product implements identifiable<integer> { @id @column(name = "cnsm_prd_ver_wrk_i") @generatedvalue(strategy = generationtype.auto) @jsonignore private integer id; @column(name = "prd_mdl_nbr") private string model; @column(name = "prd_spec_dsc") private string description; }

in application when include pagingandsortingrepository appointment. can phone call post command next payload.

{ "tracknumber" : "xyz123", "products": [ {"model" : "model", "description" : "name" }] }

when add together pagingandsortingrepository product , seek same post next error message.

{ "cause" : { "cause" : { "cause" : null, "message" : null }, "message" : "(was java.lang.nullpointerexception) (through reference chain: com..model.appointment[\"products\"])" }, "message" : "could not read json: (was java.lang.nullpointerexception) (through reference chain: com.model.appointment[\"products\"]); nested exception com.fasterxml.jackson.databind.jsonmappingexception: (was java.lang.nullpointerexception) (through reference chain: com.model.appointmentverification[\"products\"])" } payload both repositories returns this. desired format. link products should included { "tracknumber" : "xyz123", "_links" : { "self" : { "href" : "http://localhost:8080/consumerappointment/appointments/70" }, "products" : { "href" : "http://localhost:8080/consumerappointment/appointments/70/products" } }

with appointment repository next payload , can post list of products.

{ "tracknumber" : "xyz123", "products" : [ { "model" : "model", "description" : "name", } ], "_links" : { "self" : { "href" : "http://localhost:8080/consumerappointment/appointments/1" } } }

let's take step , create sure understand what's happening here: if repository detected, spring info rest exposes dedicated set of resources manage aggregates handled repository via http. thus, if have repositories multiple entities related each other, relationship represented link. why see products inlined appointmentrepository in place , products link in place 1 time create productrepository.

if want expose both repositories resources, need hand uris of product instances in payload post create appointment. means, instead of posting this:

{ "tracknumber" : "xyz123", "products": [ { "model" : "model", "description" : "name" } ] }

you'd create product first:

post /products { "model" : "model", "description" : "name" } 201 created location: …/products/4711

and hand id of product appointment payload:

{ "tracknumber" : "xyz123", "products": [ "…/products/4711" ]}

in case don't want of (no resources exposed product in first place, utilize @repositoryrestresource(exported = false) on personrepository. still leave bean instance created repo, no resources exported , resource exposed appointments inlining related products.

spring-data-rest

html5 - CSS rule to disable text selection highlighting on ol li number within contenteditable div -



html5 - CSS rule to disable text selection highlighting on ol li number within contenteditable div -

given:

list item 1 list item 2

i'm trying highlight content within li

<div contenteditable="false"> <ol> <li><span>list item 1</span></li> <li><span>list item 2</span></li> </ol> </div>

this works fine if apply -webkit-user-select: none; ol , -webkit-user-select: all; ol li span. long contenteditable = false. if set true css no longer takes effect.

any ideas?

see: http://jsfiddle.net/bqxfz/

html5 css3

xpages - Disable ClientSide Validation -



xpages - Disable ClientSide Validation -

in posting: how disable client-side validation xpage?

sven demonstrated setting property disable client side validation.

<xp:this.properties> <xp:parameter name="xsp.client.validation" value="false" /> </xp:this.properties>

i tried in test xpage , works great, tried in application , error when submit button clicked rich text field undefined. have custom command contains input , validation , called ext lib application layout control. have removed can app layout when submit right validation gives message:

--------------------------- xpwfsdemoinput --------------------------- error occurred while updating of page. dijit.byid("view:_id1:_id2:_id3:_id4:callback1:_id145:callback1:_id148:inputrichtext1") undefined --------------------------- ok ---------------------------

i place input custom command within new xpage, set parameter on xpage , run , works fine, sees richtext , processes correctly. there appear in app layout causing problems. seek putting ext lib applayout xpage , see happens.

some farther info -- found problem code client side script periodic time check. no thought why hates rtf though.

if want disable client-side validation application, can in xsp properties in application. can in xsp.properties file on server. check out xpages portable command guide more details on , xsp.properties settings

xpages xpages-extlib

Using 'system ("COLOR [attr]")' in C++ -



Using 'system ("COLOR [attr]")' in C++ -

i working on code need display output in different colors according input given user. how can this? tried next code begin with, it's not working.

#include<iostream> #include<cstdlib> using namespace std; int main(void) { scheme ( "title color check" ); for(int i=0;i<10;i++) { scheme ( "color i" ); cout << "this color color" << << endl; } system("pause"); homecoming 0; }

this should work:

for(int = 31; < 38; i++) cout << "\e[0;" << << "m"<< "this color color " << << "\e[0;0m" << endl;

just utilize right color codes:

'\e[0;31m' # red '\e[0;32m' # green '\e[0;33m' # yellow '\e[0;34m' # blue '\e[0;35m' # purple '\e[0;36m' # cyan '\e[0;37m' # white

c++ colors

excel vba - VBA code to bring over background color of a cell -



excel vba - VBA code to bring over background color of a cell -

i trying figure out if there code out there re-create on background color of cell. instance cell a1 had background color of white decided wanted highlight cell yellow, possible bring on color formatting vba code?

try this:

sub macro1() range("a1").style = "neutral" 'select whatever cell want alter 'this style kinda yellowish range("a2").style = "accent6" 'select whatever cell want alter 'this style orange 'you have utilize whatever accent want end sub

you'll have adapt little use. allow me know if helps!

just tried else. 1 changes fill color, not style.

range("a3").select selection.interior .pattern = xlsolid .patterncolorindex = xlautomatic .color = 65535 .tintandshade = 0 .patterntintandshade = 0 end

excel-vba

sql - Derby classpath cant connect to databse -



sql - Derby classpath cant connect to databse -

i installed derby , followed instructions here exact same way told me replacing paths paths. reason why seek create connection connect create database , run sql scripts create tables , populate them gives me few errors firstly 1

error 08001: no suitable driver found jdbc:derby:supermarket;create=true

then when sql scripts run error

ij error: unable found connection

i dont see did wrong line used set class path

c:\> set classpath=%derby_install%\lib\derby.jar;%derby_install%\lib\derbytools.jar;.

i included derby.jar file needed cant see problem know did wrong? when run

connect 'jdbc:derby://localhost:1527/mydb';

the server starts fine

c:\derbs\db-derby-10.10.2.0-bin\bin>startnetworkserver thu jun 26 11:56:38 pdt 2014 : security manager installed using basic server security policy. thu jun 26 11:56:39 pdt 2014 : apache derby network server - 10.10.2.0 - (158244 6) started , ready take connections on port 1527

there many troubles when start using derbydb. painful practice.

1. for example, download derby http://db.apache.org/derby/derby_downloads.html#latest+official+releases

2. unzip c:\tools\db-derby-10.11.1.1-bin.

3. press windows key + r, type: systempropertiesadvanced, set environment variables. reference: https://db.apache.org/derby/docs/10.0/manuals/getstart/gspr16.html

4. run cmd, should run additional command:

c:\tools\db-derby-10.11.1.1-bin\bin\networkservercontrol.bat

and type:

c:\tools\db-derby-10.11.1.1-bin\bin\ij.bat

then press enter, , result:

5. set in-memory derby database d:\ directory. folder vy1 must doesn't exit. type command creating new database named vy1:

connect 'jdbc:derby:d:\vy1;create=true';

use windows explorer, go directory d:\vy1, see new folder named vy1 created.

then type command:

connect 'd:\vy1'

6. see sql command create database, table, insert, read database this:

(open images in new web page improve view. note: old screenshot when utilize older version few months ago).

come question, focus @ section 3, , commnand phone call networkservercontrol.bat @ section 4.

good luck! :)

sql database jdbc derby

performance - What is the fast way to calculate this summation in MATLAB? -



performance - What is the fast way to calculate this summation in MATLAB? -

so have next constraints:

how write in matlab in efficient way? inputs x_mn, m, , n. set b={1,...,n} , set u={1,...,m}

i did (because write x follwoing vector)

x=[x_11, x_12, ..., x_1n, x_21, x_22, ..., x_m1, x_m2, ..., x_mn]:

%# first constraint function r1 = constraint_1(m, n) ee = eye(n); r1 = zeros(n, n*m); m = 1:m r1(:, (m-1)*n+1:m*n) = ee; end end %# sec constraint function r2 = constraint_2(m, n) ee = ones(1, n); r2 = zeros(m, n*m); m = 1:m r2(m, (m-1)*n+1:m*n) = ee; end end

by above code matrix a=[r1; r2] 0-1 , have a*x<=1.

for example, m=n=2, have this:

and, create function test(x) returns true or false according x.

i help , optimize code.

you should place x_mn values in matrix. after that, can sum in each dimension want. looking @ constraints, place these values in m x n matrix, m amount of rows , n amount of columns.

you can place values in vector , build summations in way intended earlier, have write for loops subset proper elements in each iteration, inefficient. instead, utilize matrix, , utilize sum sum on dimensions want.

for example, let's values of x_mn ranged 1 20. b in set 1 5 , u in set 1 4. such:

x = vec2mat(1:20, 5) x = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

vec2mat takes vector , reshapes matrix. specify number of columns want sec element, , create right amount of rows ensure proper matrix built. in case, want 5 columns, should create 4 x 5 matrix.

the first constraint can achieved doing:

first = sum(x,1) first = 34 38 42 46 50

sum works vectors matrices. if have matrix supplied sum, can specify sec parameter tells in direction wish sum. in case, specifying 1 sum on of rows each column. works in first dimension, rows.

what doing is summing on possible values in set b on values of u, doing here. summing every single column individually.

the sec constraint can achieved doing:

second = sum(x,2) sec = 15 40 65 90

here specify 2 sec parameter can sum on of columns each row. sec dimension goes on columns. doing is summing on possible values in set u on values of b. basically, summing every single row individually.

btw, code not achieving think it's achieving. you're doing replicating identity matrix set number of times on groups of columns in matrix. not performing summations per constraint. doing ensuring matrix have conditions specified @ origin of post enforced. these ideal matrices required satisfy constraints.

now, if want check see if first status or sec status satisfied, can do:

%// first status satisfied? firstsatisfied = all(first <= 1); %// sec status satisfied secondsatisfied = all(second <= 1);

this check every element of first or second , see if resulting sums after above code showed <= 1. if satisfy constraint, have true. else, have false.

please allow me know if need further.

performance matlab optimization

c++ - Parallel search of distinct values? -



c++ - Parallel search of distinct values? -

consider next code :

// preprocessor #include <iostream> #include <chrono> #include <thread> #include <algorithm> #include <mutex> #include <random> // main function int main() { // random vector of size 100 10 different random values std::vector<unsigned int> vector = make_random_vector(100, 10); // @ end, result should 10 different random values std::vector<unsigned int> result; // mutex deals concurrency std::mutex mutex; // parallel search parallel_for_each(vector.begin(), vector.end(), [=, &result, &mutex](const unsigned int& i){ /* critical section: begin */ // if current element not yet in resulting vector, inserts if (!std::binary_search(result.begin(), result.end(), i)) { mutex.lock(); result.insert(std::lower_bound(result.begin(), result.end(), i), i); mutex.unlock(); } /* critical section: end */ }); // unique values result.erase(std::unique(result.begin(), result.end()), result.end()); // display result std::for_each(result.begin(), result.end(), [](const unsigned int& i){ std::cout<<i<<std::endl; }); // finalization homecoming 0; }

the goal find n distinct values in vector in parallel.

my question : preceding code ok (no problem of concurrency), , if not, how right ?

note: code has calls 2 functions :

parallel_for_each executes provided function on provided number of threads :

// parallel execution returning execution time in seconds template <class iterator, class function> double parallel_for_each(const iterator& first, const iterator& last, function&& function, const int nthreads = std::thread::hardware_concurrency()) { const std::chrono::high_resolution_clock::time_point tbegin = std::chrono::high_resolution_clock::now(); const long long int ntasks = std::max(static_cast<int>(1), nthreads); const long long int grouping = std::max(static_cast<long long int>(first < last), static_cast<long long int>((last-first)/ntasks)); std::vector<std::thread> threads; iterator = first; threads.reserve(ntasks); (it = first; < last-group; += group) { threads.push_back(std::thread([=, &last, &group, &function](){std::for_each(it, std::min(it+group, last), function);})); } std::for_each(it, last, function); std::for_each(threads.begin(), threads.end(), [](std::thread& current){current.join();}); homecoming std::chrono::duration_cast<std::chrono::duration<double> >(std::chrono::high_resolution_clock::now()-tbegin).count(); }

make_random_vector produces random vector of nelements nvalues different random values

// produces random vector of nelements nvalues different random values std::vector<unsigned int> make_random_vector(const unsigned int nelements, const unsigned int nvalues) { std::vector<unsigned int> vector(nelements); std::vector<unsigned int> values(nvalues); std::random_device device; std::mt19937 engine(device()); std::uniform_int_distribution<unsigned int> distribution1; std::uniform_int_distribution<unsigned int> distribution2(0, nvalues-1); std::for_each(values.begin(), values.end(), [=, &distribution1, &engine](unsigned int& i){i = distribution1(engine);}); std::for_each(vector.begin(), vector.end(), [=, &distribution2, &engine, &values](unsigned int& i){i = values[distribution2(engine)];}); homecoming vector; }

your code has problem, protect concurrent write access not read access of result.

a solution move mutex locking outside of if follow:

[=, &result, &mutex](const unsigned int& i){ std::lock_guard<std::mutex> lck (mutex); // if current element not yet in resulting vector, inserts if (!std::binary_search(result.begin(), result.end(), i)) { result.insert(std::lower_bound(result.begin(), result.end(), i), i); } }

but break purpose of parallel :/

an other solution work on different result set, , bring together result @ end of loop.

an other solution may variant of double-checked locking requires re-create result @ each insertion.

c++ c++11 concurrency parallel-processing mutex

insert multiple rows into mysql through node.js -



insert multiple rows into mysql through node.js -

i want insert multiple rows mysql thru node.js mysql module. info have

var info = [{'test':'test1'},{'test':'test2'}];

i using pool

pool.getconnection(function(err, connection) { connection.query('insert '+table+' set ?', data, function(err, result) { if (err) throw err; else { console.log('successfully added db'); connection.release(); } }); }); }

which fails.

is there way me have mass insertion , phone call function when insertion finishes?

regards hammer

you can insert multiple rows mysql using nested arrays. can see reply post: how do mass insert in mysql using node.js

mysql node.js node-mysql

How to improve jqPlot parseOptions/jquery.extend performance -



How to improve jqPlot parseOptions/jquery.extend performance -

i have app uses jqplot , want create perform improve - i.e. have render charts faster.

using firefox profiler, i'm able drill downwards on time beingness spent in various parts of code, , i've found phone call jqplot takes ~85% of time. of 85%, ~60% spent in jqplot.draw routine , ~20% taken in jqplot.parseoptions routine.

in add-on static configuration info (legend related stuff, grid related stuff, cursor , highlighter stuff, , x, y, y1, , y2 axis info), actual chart info passed in alternative object jqplot. chart info includes series data, series options, , label ticks.

jqplot copies of stuff it's own memory, , function called parseoptions uses jquery.extend() function work. jquery.extend function appears general purpose re-create function knows how deal info types , objects, generalized function it's not optimized 1 of them.

my first effort seek pass in static options on phone call jqplot, , utilize jqplot.replot() pass series data, series options, , ticks chart object (to avoid extend in parseoptions). failed, , after traced through code discovered replot accepts line plot info (x,y points) , not take ohlc info (as these charts composed of). next tried passing ohlc info in initial phone call jqplot , passing series options , ticks in subsequent phone call replot, although (limited) jqplot documentation says replot take options, it's not total alternative set , ones needed weren't handled.

my next effort create series_options "lighter". primary series info chart uses ohlcrenderer, , other series utilize linerenderer. current code has linerenderer set default, , each series_option object has override specifying ohlcrenderer. each of these ohlcrenderer override references in series_option objects has multiple objects beneath them - function prototypes , other stuff. since there few of non-sample/wafer types compared sample/wafer objects, changed things around create ohlcrenderer default , added linerenderer overrides other objects. thought removing many object references speed parseoption process, had no appreciable difference (if anything, seemed little slower since profiling course of study it's not clear).

i'm out of ideas @ point. have ideas speed chart rendering?

jquery performance jqplot

sql server - Generate average growth data for the missing dates -



sql server - Generate average growth data for the missing dates -

i’m working in mssql 2008 r2 , need help generating data

i have table of ranges looks this

create table [dbo].[weight]( [id] [int] identity(1,1) not null, [date] [datetime] null, [weight] [decimal](18, 2) null, )

the info have looks this

insert [weight] values ('2014-05-07', 1) insert [weight] values ('2014-05-10', 20) insert [weight] values ('2014-05-15', 80) insert [weight] values ('2014-05-25', 100)

ok want generate average growth info missing dates. missing dates want insert temp table

this how end result should like.

date weight 2014-05-07 1 2014-05-08 7.33 2014-05-09 13.66 2014-05-10 20 2014-05-11 32 2014-05-12 44 2014-05-13 56 2014-05-14 68 2014-05-15 80 2014-05-16 82 2014-05-17 84 2014-05-18 86 2014-05-19 88 2014-05-20 90 2014-05-21 92 2014-05-22 94 2014-05-23 96 2014-05-24 98 2014-05-25 100

select dateadd(day,[n],[date]) [date], [weight] + isnull([n]*([next_weight]-[weight])/[count],0) [weight] [dbo].[weight] t1 outer apply ( select top 1 datediff(day,t1.[date],[date]) [count], [weight] [next_weight] [dbo].[weight] [date] > t1.[date] order [date] ) t2 cross apply ( select top(isnull([count],1)) row_number() over(order (select 1))-1 [n] master.dbo.spt_values ) t3

sql fiddle demo

sql-server

asp.net - Minification failed. Returning unminified contents -



asp.net - Minification failed. Returning unminified contents -

i have made first website using mvc 5 works fine on local machine when publish server of css not loading correctly.

/* minification failed. returning unminified contents. (80,1): run-time error css1019: unexpected token, found '@import' (80,9): run-time error css1019: unexpected token, found 'url('../content/dark-skin/skin.css')' (671,16): run-time error css1062: expected semicolon or closing curly-brace, found ':' (1288,16): run-time error css1062: expected semicolon or closing curly-brace, found ':' (1680,1): run-time error css1019: unexpected token, found '@keyframes' (1682,5): run-time error css1062: expected semicolon or closing curly-brace, found '50%' (1685,1): run-time error css1019: unexpected token, found '@-webkit-keyframes' (1687,5): run-time error css1062: expected semicolon or closing curly-brace, found '50%' */ /* nuget: begin license text * * microsoft grants right utilize these script files sole * purpose of either: (i) interacting through browser microsoft * website or online service, subject applicable licensing or utilize * terms; or (ii) using files included microsoft product subject * product's license terms. microsoft reserves other rights * files not expressly granted microsoft, whether implication, estoppel * or otherwise. notices , licenses below informational purposes only. * * nuget: end license text */ /*! * bootstrap v3.0.0 * * copyright 2013 twitter, inc * licensed under apache license v2.0 * http://www.apache.org/licenses/license-2.0 * * designed , built love in world @mdo , @fat. *//*! normalize.css v2.1.0 | mit license | git.io/normalize */

i understand compiler trying minimize css files failing so. tried right errors after correcting of them , publishing 1 time again error looks same, not picking changes.

even strangest thing bootstrap.css file have modified purpose of website. when publish changes not in bundle file. possible bootstrap loaded bootstrap server advertisement not project?

bundles.add(new stylebundle("~/content/cssmain").include( "~/content/bootstrap.css", "~/content/site.css", "~/content/ilightbox.css", "~/content/bannerscollection_zoominout.css"));

i have tried minification myself using web application changes not visible , files looks not minificated.

any help appreciated

i resolved problem bundling bootstrap.css doing 2 things:

include bootstrap.css first in bundle. code sample in question this, not. add official minified version (bootstrap.min.css) project in same directory unminified version. prompts bundler utilize existing minified file instead of trying (and failing) minify bootstrap.css itself. see greenish arrow in screenshot below.

note if using specific theme, substitute bootstrap.css , bootstrap.min.css files provided theme. here's working code project uses spacelab theme:

bundles.add(new stylebundle(getstylebundlepath("bootstrap")).include( "~/content/3rdparty/bootstrap.spacelab.css", "~/content/3rdparty/bootstrap-datepicker.css", "~/content/3rdparty/bootstrap-multiselect.css"));

asp.net asp.net-mvc

c# - Reading content from MS Access db using ADO.net and trying to insert the values into a SQL Server table -



c# - Reading content from MS Access db using ADO.net and trying to insert the values into a SQL Server table -

i'm using oledb connection read table in ms access. i've closed connection , i'm trying insert values retrieved sql server table using entity framework.

while establishing connection sql server, i'm getting error:

a network-related or instance-specific error occurred while establishing connection sql server. server not found or not accessible. verify instance name right , sql server configured allow remote connections. (provider: sql network interfaces, error: 26 - error locating server/instance specified)

the error message crystal clear: server not found. so, take 2 steps.

verify connection string misspelled server name.

verify sql server instance accepting connections network, disable default.

go to:

start > programs > sql server 2005 > configuration tools > sql server surface area configuration

click on surface area configuration services , connections

select instance having problem > database engine > remote connections

enable local , remote connections

restart instance

see article:

http://www.sswug.org/articlesection/default.aspx?targetid=44331

c# entity-framework

triggers - Jenkins schedule multiple versions of the same build -



triggers - Jenkins schedule multiple versions of the same build -

i have project has 3-5 different mercurial branches going @ times. want schedule weekly jenkins test run our tests on relevant branches.

what want, think, parameterized build, branch name parameter, , have list of branches, , 1 time week, run parameterized build each of parameters in list.

however, see can't send parameters triggered build. assume there plugin this. job generator right plugin? there better?

i should mention currently, doing multiple scms, , having body of build have sh loop runs through each directory , runs tests. inefficient, , pain maintain...

i can suggest 1 solution couldn't called elegant.

firstly, need create multi-configuration project (aka matrix project).

in project need declare 1 node (it can existed master node) , 1 type of axis (for illustration branch - careful don't utilize jenkins set environment variables variables) values corresponding each branch (for illustration default, testing, devel, etc).

after need add together in project build action in need check environment variable (previously declared $branch) , find branch build launched (the main thought illustrated illustration using bash).

and need manually sources corresponding branch.

next build steps can same branches.

this approach have set of drawbacks: 1. can not triggered project changes in repository (you can check using mercurial plugin 1 branch). 2. subprojects rebuilt if have not changed. 3. appropriate statically defined branches. 4. not elegant.

but has 1 advantage versus parameterized build: 1. artifacts (and build logs) of branches stored in separated directories (because separate subprojects).

jenkins triggers

sql - add extra columns in a SELECT INTO statement -



sql - add extra columns in a SELECT INTO statement -

i doing select statement create new table values in table. want add together 2 columns onto newly created table (pol_eff_dt, pol_exp_dt) , create them null (these columns exist in source table otherwise pull data). need create sure come on datetime types. how can cast them way? i've tried lot of things, nil compile.

select distinct bnd_ser_nbr, trans_nbr, uws_product_cd, bill_id, null pol_eff_dt, null pol_exp_dt er_ro_urs_prem_detail urs_prem_detail_interim

you can seek casting null explicitly datetime, so:

select distinct bnd_ser_nbr, trans_nbr, uws_product_cd, bill_id, cast(null datetime) pol_eff_dt, cast(null datetime) pol_exp_dt er_ro_urs_prem_detail urs_prem_detail_interim

demo here. in demo, if alter type 2 columns cast to, , seek assign datetime value, conversion error.

sql tsql datetime select select-into

Get the machine name of an Azure worker or web role using PowerShell? -



Get the machine name of an Azure worker or web role using PowerShell? -

is there way using powershell azure cmdlets machine name on azure worker or web role running? specifically, i'm looking name starts "rd". i'm not 100% sure if i'm searching using right terminology, because results clouded info azure virtual machines. i've been exploring objects returned such calls get-azuredeployment , get-azurevm, haven't found "rd" name anyplace yet.

i've found give-and-take here, wondering if it's out of date: http://social.msdn.microsoft.com/forums/windowsazure/en-us/73eb430a-abc7-4c15-98e7-a65308d15ed9/how-to-get-the-computer-name-of-a-webworker-role-instance?forum=windowsazuremanagement

motivation: new relic monitoring complains "server not reporting" instances have been decommissioned. new relic's server monitoring knows "rd..." names, , i'm looking quick way list of these azure can compare , see if new relic complaining old instances or if there's real problem 1 of current instances.

you can more important host names rd... setting vmname key in cloud service's serviceconfiguration file.

then, host names of form vmnamexx, xx instance number of role. (i.e. "myapp01", "myapp02", ...)

for details on this, see links below:

https://azure.microsoft.com/documentation/articles/virtual-networks-viewing-and-modifying-hostnames/

http://blogs.msdn.com/b/cie/archive/2014/03/30/custom-hostname-for-windows-azure-paas-virtual-machines.aspx

powershell azure

mysql - getting quantity from one table and substract from another table quantity using php -



mysql - getting quantity from one table and substract from another table quantity using php -

<?php include ("../database.php"); include ("../session.php"); include ("../utype.php"); $search=$_post["search"]; $barcode=$_post["barcode"]; if (isset($search)) { $sql2=mysql_query("select * stock_count_tb "); while($row=mysql_fetch_array($sql2)) { $sql3=mysql_query("select * product_stock_fullsum "); while($row1=mysql_fetch_array($sql3)) { $correctqty=$row1['qty']-$row['qty']; $prod_id=$row['st_product_id']; $sql5=mysql_query("insert `product_stock_correctstock` (`prod_id`, `qty`, `free`, `po_id`, `expire_date`) values ('$prod_id', '$correctqty', '0', '', '00:00:0000');"); } } } ?> <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>untitled document</title> <link href="../css/style1.css" rel="stylesheet" type="text/css" /> <link href="brightside.css" rel="stylesheet" type="text/css" /> <script src="../jquerylib.js"></script> </head> <body> <form action="sales_deduct_stock.php" name="foo" method="post"> <table width="700" border="0"> <tr><th width="183" scope="row"><div align="right" class="style12">enter product barcode :</div></th> <th width="501" scope="row"><div align="left"><label><input name="search" type="submit" class="button" id="search" value="add stock" /></label></div></th></tr> </form> </body> </html>

php mysql