Thursday, 15 April 2010

javascript - Node-Mysql database query + res.json far too slow -



javascript - Node-Mysql database query + res.json far too slow -

i learning node.

using express , node-mysql, able query mysql database , homecoming result client json.

however, far slow. simple query limit of 100 taking 6 seconds response.

according logger, db query takes 8 ms run - not think node-mysql problem.

but other thing doing passing resultset response object converted json.

here code, roughly:

route:

app.get( "/exercises", function( req, res ){ exercises.get( req.query, function( result ){ res.json( result ); }); });

model:

module.exports.get = function( params, cb ){ var sql = "select * exercises limit 100"; db.do( sql, function( result ){ var response = {}; response.data = result[ 0 ]; response.meta = result[ 1 ][ 0 ]; cb( response ); }); };

db:

module.exports.do = function( sql, vals, cb ){ var selectstart = +new date(); pool.acquire(function( err, db ){ db.query( sql, vals, function( err, result ) { cb( result ); console.log( "query execuction: %d ms", +new date() - selectstart ); pool.release( db ); }); }); };

does know doing wrong / why taking long send resultset client?

thanks (in advance) help.

i'm not familiar pool, , unfortunately can't comment yet. 1 thing noticed calling db.do 2 arguments, while takes three. should raise 'undefined not function' when seek callback.

javascript node.js node-mysql

jquery - Grabbing, Resizing, and Displaying Image from JSON -



jquery - Grabbing, Resizing, and Displaying Image from JSON -

basically, i'm trying following:

a user enters id asset on our system the id submitted part of api phone call returns json field called "videostillurl", contains url thumbnail image. resize thumbnail image existing size smaller that, if right clicks , saves hard drive, resized version , not original.

i'm not sure if possible... can bits , pieces of it, haven't been able set , thought i'd see if had insight.

below format of json returning. i'm having hardest time figuring out how load image url videostillurl item, because url has slashes in it.

{"name":"test item","videostillurl":"http:\/\/brightcove.vo.llnwd.net\/d21\/unsecured\/media\/1547387903001\/1547387903001_2146991932001_vs-5112b14ee4b0a4075c1c8334-1592194027001.jpg?pubid=1547387903001","thumbnailurl":"http:\/\/brightcove.vo.llnwd.net\/d21\/unsecured\/media\/1547387903001\/1547387903001_2146991933001_th-5112b14ee4b0a4075c1c8334-1592194027001.jpg?pubid=1547387903001"}

any help appreciated!

extra slashes shouldn't issue escaped.

let you're doing mockup:

$(document).ready(function() { ... ajaxsuccesscallhere(data) { var image = $("<img/>"); $(image).attr('src', data.thumbnailurl) $(document.body).append(image); } ... });

what find impossible do, in you're trying achieve, making save videostillurl when right clicking on image alone. how i'd wrap <a href='[videostillurl]'> tag around image - right clicking, , picking "save source" save original image , not thumbnail

jquery

Java MySQL calling commit() on a large EntityTransaction object failed -



Java MySQL calling commit() on a large EntityTransaction object failed -

i have big javax.persistence.entitytransaction object, ent, when called method commit() on object (to insert new record (mysql) table: ent.commit();

i got quere error (please see below). think problem relates size of entitytransaction object, because smaller size (4k, 5m, 9m) calls succeeds new records inserted table. size of entitytransaction object caused failure 15m, not big (i guess) because utilize longblob columns.

any help, pointer or advice highly appreciated.

please help!

thanks,

tri

================================== code:

public static boolean inserttransaction(transaction tran) { em.gettransaction().begin(); if (!em.contains(tran)) { system.out.println("dbmanager.inserttransaction persist"); em.persist(tran); system.out.println("dbmanager.inserttransaction persist returned"); } else { system.out.println("dbmanager.inserttransaction merge"); em.merge(tran); } system.out.println("dbmanager.inserttransaction commit"); em.gettransaction().commit();////>>>>>>>>>>>>>failure happened here big object system.out.println("dbmanager.inserttransaction commit returned"); homecoming true; }

================================== output:

dbmanager.inserttransaction commit [el warning]: 2013-02-07 16:53:08.947--unitofwork(13583728)--exception [eclipselink-4002] (eclipse persistence services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.databaseexception internal exception: com.mysql.jdbc.exceptions.jdbc4.communicationsexception: communications link failure exception in thread "awt-eventqueue-0" java.lang.nullpointerexception lastly packet received server 234 milliseconds ago. lastly packet sent server 234 milliseconds ago. error code: 0 call: insert transaction_tbl (tnc, dest, rtcn, src, status, time_stamp, tran_file, tran_file_size, tran_file_type, ttype) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) bind => [10 parameters bound] query: insertobjectquery(com.cmbios.db.client.transactiontbl[ tnc=358cph8ltl ]) [el warning]: 2013-02-07 16:53:08.95--clientsession(10091188)--exception [eclipselink-4002] (eclipse persistence services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.databaseexception internal exception: com.mysql.jdbc.exceptions.jdbc4.mysqlnontransientconnectionexception: no operations allowed after connection closed.connection implicitly closed driver. error code: 0 [el warning]: 2013-02-07 16:53:08.95--unitofwork(13583728)--java.lang.nullpointerexception @ org.eclipse.persistence.sessions.server.serversession.setcheckconnections(serversession.java:814) @ org.eclipse.persistence.sessions.server.connectionpool.releaseconnection(connectionpool.java:285) @ org.eclipse.persistence.sessions.server.serversession.releaseclientsession(serversession.java:762) @ org.eclipse.persistence.sessions.server.clientsession.release(clientsession.java:555) @ org.eclipse.persistence.internal.jpa.transaction.entitytransactionimpl.commitinternal(entitytransactionimpl.java:99) @ org.eclipse.persistence.internal.jpa.transaction.entitytransactionimpl.commit(entitytransactionimpl.java:63) @ com.cmbios.db.client.dbmanager.inserttransaction(dbmanager.java:137)

java mysql persistence commit large-data

ruby on rails - Easiest way to dump Heroku database for use in local seed.rb? -



ruby on rails - Easiest way to dump Heroku database for use in local seed.rb? -

i can dump heroku database $ heroku pgbackups:capture. also, this post shows there tools taking development database , dumping seed.rb.

i'm wondering if there easy way combine 2 processes, dumping info production heroku database local seeds.rb more realistic development testing.

if possible, what's cleanest way this?

update:

based on insightful reply db', may consider using pgsql locally. still interested, however, in seed.rb aspect of question if there way easily.

there couple ways accomplish such thing. @db' has outlined 1 of them - using the pg backups add-on export database. it's great options involves few (trivial) manual commands.

i recommend using pg:transfer heroku cli plugin transfer info in single step. under covers it's still much same thing happening using pg backups, it's packaged bit nicer , has useful defaults.

from app's directory, re-create production database locally (assuming local pg db), installing plugin , execute pg:transfer command.

$ heroku plugins:install https://github.com/ddollar/heroku-pg-transfer $ heroku pg:transfer

there couple options can set well. see my writeup more details.

hope helps! , yes, please utilize same database during development in production.

ruby-on-rails ruby-on-rails-3 heroku seeding database-dump

android - How to tell if a bluetooth device is connected? My code isn't working -



android - How to tell if a bluetooth device is connected? My code isn't working -

i trying hear bluetooth connection/disconnection events determine if there bluetooth device connected. i'm trying way app run on older android versions.

i registered receiver in manifest such:

<receiver android:name=".bluetoothreceiver"> <intent-filter> <action android:name="android.bluetooth.device.action.acl_connected" /> </intent-filter> </receiver>

and in bluetoothreceiver class have

public class bluetoothreceiver extends broadcastreceiver{ public final static string tag = "bluetoothreciever"; public void onreceive(context context, intent intent) { log.d(tag, "bluetooth intent recieved"); final bluetoothdevice device = intent.getparcelableextra(bluetoothdevice.extra_device); string action = intent.getaction(); if (bluetoothdevice.action_acl_connected.equalsignorecase(action)) { log.d(tag, "connected " + device.getname()); } if (bluetoothdevice.action_acl_disconnected.equalsignorecase(action)) { log.d(tag, "disconnected " + device.getname()); } }}

but when connecting , disconnecting bluetooth, nil happens. doing wrong?

you have manipulate modify_audio_settings finger if bluetooth headset connected. 1 time you've defined intent, , configure manifest correctly should work. headphone jack, can applied bluetooth if utilize above mentioned.

here 2 sites may help explain in more detail:

http://www.grokkingandroid.com/android-tutorial-broadcastreceiver/ http://www.vogella.com/articles/androidbroadcastreceiver/article.html

you have define intent; otherwise won't access scheme function. broadcast receiver; alert application of changes you'd hear for.

every receiver needs subclassed; must include onreceive(). implement onreceive() you'll need create method include 2 items: context & intent.

more service ideal; you'll create service , define context through it. in context; you'll define intent.

an example:

context.startservice (new intent(context, yourservice.class));

very basic example. however; particular goal utilize system-wide broadcast. want application notified of intent.action_headset_plug.

how subscribe through manifest:

<receiver android:name="audiojackreceiver" android:enabled="true" android:exported="true" > <intent-filter> <action android:name="android.intent.action.headset_plug" /> </intent-filter> </receiver>

or can define through application; but. particular request; require user permissions if intend observe bluetooth modify_audio_settings.

update:

i misread question, thought trying find bluetooth headsets; not bluetooth paired.

over on question; explain how check paired bluetooth devices.

import bluetooth package.

import android.bluetooth.*;

set permission.

<uses-permission android:name="android.permission.bluetooth" />

access bluetooth adapter:

bluetoothadapter bluetooth = bluetoothadapter.getdefaultadapter();

run check connection not null.

if (bluetooth != null) { // something. }

make sure enabled:

if (bluetooth.isenabled()) { // enabled, work bluetooth } else { // not enabled else. }

display bluetooth state bluetoothadapter.getstate()

by default turned off; you'll have enable it.

string state = bluetooth.getstate(); status = devicename + " : " + devicelocation + " : " + devicestate;

android android-intent

r - Scoping in custom lattice functions (group argument) -



r - Scoping in custom lattice functions (group argument) -

please consider function:

tf <- function(formula = null, info = null, groups = null) { grv <- eval(substitute(groups), data, environment(formula)) # values grn <- as.character(match.call()$groups) # name gr <- match.call()$groups # unquoted name p <- xyplot(formula, data, # draws info not in groups # seek these options: # p <- xyplot(formula, data, groups, # can't find 'cat2' # p <- xyplot(formula, data, groups = data[,grn], # can't fine grn # p <- xyplot(formula, data, groups = grv, # can't find grv panel = function(x, y) { panel.stripplot(x, y, jitter.data = true, pch = 20) } ) p }

which can run with:

tf(formula = mpg~vs, groups = am, info = mtcars)

what doing wrong in passing groups argument xyplot - why can't found? can't figure out how wants group information. thanks.

update:

@agstudy's reply helpful, if add together panel function in original example, groups still not recognized (no grouping, no error occurs either):

tf <- function(formula = null, info = null, groups = null) { ll <- as.list(match.call(expand.dots = false)[-1]) p <- xyplot(as.formula(ll$formula), info = eval(ll$data), groups = eval(ll$groups), panel = function(x, y) { panel.stripplot(x, y, jitter.data = true, pch = 20) } ) p }

something still missing... thanks.

you can utilize eval here since match.call returns symbols.

tf <- function(formula = null, info = null, groups = null) { ll <- as.list(match.call(expand.dots = false)[-1]) p <- xyplot(as.formula(ll$formula), info = eval(ll$data), groups = eval(ll$groups), panel = function(x, y,...) { ## here ... contains groups , subscripts ## here can transform x or y before giving them jitter panel.stripplot(x, y, jitter.data = true, pch = 20,...) } ) p }

r lattice

sql - Referring to a table by variable -



sql - Referring to a table by variable -

i'm sure pretty basic, how set insert statement using variable table name?

for example, have number of input files, configured identically (input1, input2, input3, ...) going insert or merge statement.

i want either loop, working through input files, or phone call insert statement function

insert [outputfile] select i.* [<input variable>] left bring together [outputfile] op on concat(i.field1, i.field6) = concat(op.field1, op.field6) op.field1 null print 'number of rows added ' + cast(@@rowcount char(6));

i'll using merge statements, assume process same.

how set insert statement using variable table name?

you don't, not straight sql. table names , column names cannot variables.

you can accomplish using dynamic sql, have careful not introduce sql injection.

the curse , blessings of dynamic sql fantastic in depth article discussing dynamic sql.

sql sql-server tsql sql-server-2012-express

ruby on rails - Complaints that a route is missing while it's not -



ruby on rails - Complaints that a route is missing while it's not -

i'm working on simple project management web app.

i have 2 different pages view projects.

1. view projects 2. view projects administrator (includes buttons editing / deletion of projects)

because have 2 different pages showing projects decided create custom route directs user custom action in project controller.

however, doesn't (by reason) work, , next error message:

no route matches {:action=>"edit", :controller=>"projects"}

the view:

<%= link_to "manage projects", users_projects_path %>

project controller:

class projectscontroller < applicationcontroller ... def users_projects @users_projects = project.where(:user_id => current_user.id) end ... end

project model:

class project < activerecord::base has_and_belongs_to_many :users, :class_name => 'user' belongs_to :user has_many :tickets, :dependent => :destroy //validation attr_accessible :user_id, :title, :description, :start_date, :end_date end

the problem not giving id parameter route, required.

somewhere, generating link edit_project_path. ensure giving project url generator: edit_project_path(project)

ruby-on-rails ruby-on-rails-3 model controller routes

Output PHP array into unordered list -



Output PHP array into unordered list -

new php: have simple array:

$people = array('joe','jane','mike');

how output list?

<ul> <li>joe</li> <li>jane</li> <li>mike</li> </ul>

any help or direction appreciated?

try:

echo '<ul>'; foreach($people $p){ echo '<li>'.$p.'</li>'; } echo '</ul>';

php

if statement - Excel Column Equal to Text and Cell -



if statement - Excel Column Equal to Text and Cell -

i'm trying fill column url text , column info straight after slash in url column.

for illustration want input http://xxx.xxx.xxx/ column info goes here

the text url address , right after slash need column info go.

can help me out?

try concatenate function.

=concatenate("http://xxx.xxx.xxx/", a1)

excel if-statement excel-formula

html5 - Css transition is not linear -



html5 - Css transition is not linear -

i’m trying accomplish nice transition effects when hovering after image.(a hover div appear same direction mouse ).

everything works fine except “hover in” transition not in straight line more in diagonal & fill kind of way.(in illustration below transition left: -378px; left : 0px / top 0).

normal state:

<div class="hover_effect initial_hover slidefromleft" style="display: block;">link aici</div>

hover state (classes removed , added via jquery):

<div class="slidefromleft hover_effect initial_hover slideleft" style="display: block;">link aici</div>

i want motion in straight line hover out transition works fine. can point me bug ?

this html & css code:

<div class="portfolio-sample regular-portfolio coding-2 isotope-item" style="position: absolute; left: 0px; top: 0px; -webkit-transform: translate(0px, 0px);"> <img width="455" height="295" src="http://localhost/wp-content/uploads/2013/01/env0251-455x295.jpg" class="attachment-portfolio-two wp-post-image" alt="env025"> <div class="slidefromleft hover_effect initial_hover slideleft" style="display: block;">link aici</div> <div class="custom_slider_shadow"></div> </div>

thank you!

.hover_effect{ -webkit-transition: 0.3s ease; -moz-transition: 0.3s ease-in-out; -o-transition: 0.3s ease-in-out; -ms-transition: 0.3s ease-in-out; transition: 0.3s ease-in-out; } .initial_hover{ position: absolute; background: rgba(75,75,75,0.7); width: 378px; height: 245px; top: 260px; } .slidefromleft { top: 0px; left: -378px; } .slideleft { left: 0px; }

answer : ok figure out - because initial_hover class added after slidefromleft on hover. 1 time reverse these works expected

it not linear because specified not linear. if want linear transition, should alter both ease-in-out , ease linear in styling .hover_effect.

css html5 transitions

sql - IIS tries to connect to a database as a non existent user -



sql - IIS tries to connect to a database as a non existent user -

on webserver had old asp.net mvc application working perfectly, decided remove it. installed new one, , next error when seek open website:

cannot open database "mydbname" requested login. login failed. login failed user 'nt authority\network service'.

the problem is, not have user called 'nt authority\network service' in system. now?

check identity on web site's application pool. business relationship beingness set.

also, business relationship available on machine, built in. on permissions dialog type "network service" , resolve account.

sql asp.net-mvc sql-server-2008 iis windows-server-2008

sql - Updating all columns of a table -



sql - Updating all columns of a table -

i using ms access connect linked oracle database. have table b pulls columns table (in linked db).

i trying execute macro runs query1 update table b info changing.

the 2 not related id, update table command doesn't seem logical me. should using join? need place launch query from.

based on give-and-take in comments, sounds table b "view" on table a. not confident need update query.

in ms access, the syntax create view thus:

create view my_view select col1, col2 [table a]

sql oracle ms-access

jQuery datepicker not initialized after partial inserted -



jQuery datepicker not initialized after partial inserted -

i have rails 4 application uses turbo links , jquery.turbolinks. uses jquery date picker plugin.

i using ryan bates' technique adding/editing multiple models in 1 form, railscast episode #196 nested model form.

in case, adding/editing people associated household. person_fields partial includes birthdate field 'attempts' utilize date picker (a string input class="datepicker"), doesn't work, datepicker doesn't appear when click on field class of '.datepicker'.

with other forms loaded page, datepicker works fine. form added dynamically code, datepicker doesn't appear.

here's code link inserts partial:

def link_to_add_fields(name, f, association) new_object = f.object.send(association).klass.new id = new_object.object_id fields = f.fields_for(association, new_object, child_index: id) |builder| render(association.to_s.singularize + "_fields", f: builder) end link_to(name, '#', class: "add_fields little round button success", data: {id: id, fields: fields.gsub("\n", "")}) end

and coffee script inserting partial:

$('form').on 'click', '.add_fields', (event) -> time = new date().gettime() regexp = new regexp($(this).data('id'), 'g') $(this).before($(this).data('fields').replace(regexp, time)) event.preventdefault()

and coffee script date picker:

$('.datepicker').datepicker()

any help much appreciated.

--- update ---

thanks billy monk's suggestion, code add together fields looks this:

$('form').on 'click', '.add_fields', (event) -> time = new date().gettime() regexp = new regexp($(this).data('id'), 'g') $(this).before($(this).data('fields').replace(regexp, time)) event.preventdefault() $('.datepicker').datepicker()

and works! much appreciated! take reply i'm allowed.

in javascript function adds new fields add together $('.datepicker').datepicker() after have been added. datepicker won't automatically bind newly added elements.

jquery jquery-plugins ruby-on-rails-4

How can I show a preview of all data entered as a final django form wizard step? -



How can I show a preview of all data entered as a final django form wizard step? -

i'm using form wizard in django 1.4 conditionally add together instances of 7 models. regardless of steps user completes, i'd lastly step show preview of info entered. doesn't have form since user can utilize "first step" or "previous step" buttons go , prepare info messed up. i'd send confirmation email user info , suspect whatever solution come here provide info well.

here's have:

# views.py forms = [ ('person_application', personapplicationform), ('family_application', familyapplicationform), ('student_application', studentapplicationform), ('spouse', spouseform), ('child', childformset), ('roommate', roommateformset), ('preview', form), # doing because think formwizard requires form subclass every step, makes sense ] templates = { ... 'preview': 'preview.html', } condition_dict = { ... 'preview': true, } class signupwizard(sessionwizardview): ... def get_context_data(self, form, **kwargs): context = super(signupwizard, self).get_context_data(form=form, **kwargs) if self.steps.current == 'preview': context.update({'all_data': self.get_all_cleaned_data()}) homecoming context # # triggering infinite loop or because python gets stuck @ 100+% cpu , won't stop when kill runserver # def get_form_initial(self, step): # if step == 'preview': # homecoming self.get_all_cleaned_data() # homecoming {} ... # urls.py urlpatterns = patterns('app.views', ... url(r'^start$', signupwizard.as_view(forms, condition_dict=condition_dict, instance_dict=modelform_instances), name='wizard'), url(r'^thanks$', 'thanks', name='thanks'), )

as can see, @ point thought i'd seek utilize form preview, tried overriding wizardview.get_form_initial. wanted utilize wizardview.get_all_cleaned_data() provide info form's initial dict. however, mentioned in comment, caused python stuck , had find , kill process manually stop it.

so i'm thinking i'll override wizardview.get_context_data() send context variable template containing info user has entered (again, using get_all_cleaned_data()). however, going bit complicated couple reasons. since fields of models have same name going shadow each other, i'll have go , namespace model field names. seems unecessary, whatever. also, 2 of forms modelformsets, info them comes list of dictionaries. not big deal, it's going create parsing in template more difficult. question getting long might helpful see data, here's illustration of returned get_all_cleaned_data() (as gets sent template):

{'all_data': {'birthdate': datetime.date(1940, 2, 5), 'building_pref_1': u'ngh4', 'building_pref_2': u'k2', 'city': u'nashville', 'country': u'', 'email': u'johnny@cash.com', 'first_name': u'johnny', u'formset-child': [{'birthdate': datetime.date(2013, 2, 3), 'gender': u'f', 'id': none, 'name': u'rosanne'}, {'birthdate': datetime.date(2013, 2, 1), 'gender': u'f', 'id': none, 'name': u'cathy'}, {'birthdate': datetime.date(2013, 2, 5), 'gender': u'f', 'id': none, 'name': u'cindy'}, {'birthdate': datetime.date(2013, 2, 2), 'gender': u'f', 'id': none, 'name': u'tara'}, {}, {}], 'furnishing': u'f', 'gender': u'f', 'global_id': u'', 'last_name': u'cash', 'living_situation': u'sc', 'middle_initial': u'', 'move_in_date': none, 'move_out_date': none, 'name': u'vivian liberto', 'phone': u'9891111111', 'smoker_status': u'true', 'state_province': u'tn', 'street_1': u'street', 'street_2': u'', 'student_number': none, 'term': <term: summer 2013>, 'type': u'f', 'university_status': u'o', 'university_status_other': u'travelling musician', 'zip_code': u''},

so, question is, on right track or there improve way this? example, might utilize formpreview subclass form 'preview' step , define formpreview.done() as

def done(self, request, cleaned_data): pass

so info gets passed along formwizard's final processing machinery (i.e. wizardview.done())?

i'd override get_template_name handle template show (assuming have special 1 'preview` step).

then i'd overload get_form, appending info each step instance variable.

finally, i'd overload get_context_data append instance variable templates context.

overloading get_form let's manipulate info before preview displayed.

django django-forms django-formwizard

internet explorer - JSF Page hangs/freezez in production websphere7 ie8 -



internet explorer - JSF Page hangs/freezez in production websphere7 ie8 -

i have jsf page constructed using facelets , icefaces. page contains info table , commandbutton , when command button pressed confimation panel displayed, if confirm popup panel, values populated in datatable , inserted in db after unable interact page. page freezez. on 1 production server(websphere 7) ie8 have issue, on on dev server(websphere 7) ie8 dont have problem. , can interact page several time. application simple 1 page login, home page , search page. search page hangs/freezez in production after 1 interaction unable produce on dev / staging machine. should into.

internet-explorer jsf websphere

android - AlarmManager to simply update data without waking up screen -



android - AlarmManager to simply update data without waking up screen -

alarmmanager update info without waking screen

how do ?? want update phone call , info usages values in background @ intervals without waking display screen

instead of alarmmanager write service. work @ background. think these links help you. http://www.vogella.com/articles/androidservices/article.html http://developer.android.com/reference/android/app/service.html

android alarmmanager

Incorporate data migrations with SSDT publish? -



Incorporate data migrations with SSDT publish? -

is there systematic way incorporate info migration scripts ssdt publish?

for instance, deploying new feature requires new permission added database in form of series of inserts.

i know can edit generated publish script, if script needs regenerated have remember re-add info migration scripts.

the recommended practice utilize post-deployment script. blog post describes approach further:

http://blogs.msdn.com/b/ssdt/archive/2012/02/02/including-data-in-an-sql-server-database-project.aspx

data-migration ssdt

android - FileObserver -> onEvent(event, path): path is NULL -



android - FileObserver -> onEvent(event, path): path is NULL -

i want know when file finished writing, , i'm trying utilize fileobserver. i'm doing this:

fileobserver observer = new fileobserver(imageuri.getpath()) { @override public void onevent(int event, string path) { if(event == fileobserver.close_write) log.d(tag, "file: "+path); } }; observer.startwatching();

imageuri valid uri. when file closed next log entry:

file: null

why null? it's possible user writes several files, need know 1 triggering event.

thanks!

according documentation of onevent():

the path, relative main monitored file or directory, of file or directory triggered event

so guess when path null the specified file or directory...

you need maintain track of original path yourself. , append path of onevent() path total path (unless tracking file , value null):

fileobserver observer = new fileobserver(imageuri.getpath()) { public string basepath; @override public void onevent(int event, string path) { string fullpath = basepath; if(path != null) { // add together '/' in between (depending on basepath) fullpath += path; } log.d(tag, "file: "+fullpath); } }; observer.basepath = imageuri.getpath(); observer.startwatching();

i tried maintain illustration close code snippet possible. but, much improve create full-blown class extending fileobserver, can add together constructor store basepath , not required access public field outside class/instance!

android fileobserver

What am I doing wrong in this C++ mergesort? -



What am I doing wrong in this C++ mergesort? -

the programme compiles , runs properly. list of integers read input file, output displays numbers without changes. expect them sorted to the lowest degree greatest. reference, trying implement version similar illustration on wikipedia.

// arra contains items sort; arrb array work in void mergesort(int *arra, int *arrb, int first, int last) { // 1 element array sorted // create increasingly longer sorted lists (int width = 1; width < last; width = 2 * width) { // arra made of 1 or more sorted lists of size width (int = 0; < last; += 2 * width) { // merge 2 sorted lists // or re-create arra arrb if arra total merge(arra, i, min(i+width, last), min (i + 2 * width, last), arrb); } // end // arrb total of sorted lists of size 2* width // re-create arrb arra next iteration copy(arrb, arra, last); } // end } // end mergesort void merge(int *arra, int ileft, int iright, int iend, int *arrb) { int i0 = ileft, i1 = iright; // while either list contains integers (int j = ileft; j < iend; j++) { // if 1st integer in left list <= 1st integer of right list if (i0 < iright && (i1 >= iend || arra[i0] <= arra[i1])) { arrb[j] = arra[i0]; i0 += 1; } // end if else { // right head > left head arrb[j] = arra[i0]; i0 += 1; } // end else } // end } // end merge void copy(int *origin, int *destination, int size) { (int = 0; < size; i++) { destination[i] = origin[i]; } // end } // end re-create int main() { int size = 0, first = 0, *arra, *arrb; // input info read(&arra, &arrb, &size); // sorting mergesort(arra, arrb, first, size); // output write(arra, first, size); // cleanup delete [] arra; delete [] arrb; } input 33 9 -2 output 33 9 -2

i haven't looked @ code, if-statement seems bit off me:

if (i0 < iright && (i1 >= iend || arra[i0] <= arra[i1])) { arrb[j] = arra[i0]; i0 += 1; } // end if else { // right head > left head arrb[j] = arra[i0]; i0 += 1; } // end else

surely, whole point of pair of if/else clauses different things in if vs. else part. far can tell, it's identical here.

c++ mergesort

java - Use prepared statement to delete values from database -



java - Use prepared statement to delete values from database -

how can utilize prepared statement delete entries database? have found must write next code

string deletesql = "delete dbuser user_id = ?

but want specify clause more 1 variable. have used and operator doesn't seem work.

here illustration if syntax not correct..

delete dbuser user_id = ? , user_name = ?;

you can append more conditions in clause using more and ... operators.

or if have more 1 user_ids delete in single query..

delete dbuser user_id in (?, ?, ?, ?);

java sql prepared-statement

ActionScript reference to grandchild (child of child) element -



ActionScript reference to grandchild (child of child) element -

let's have basic mxml setup follows:

<item id="parent"> <frame> <mx:image/> </frame> </item>

how can refer attribute of image element referring grandchild (child of child) of parent item? i've tried daisy-chaining 2 calls getchildat(), i.e.:

parent.getchildat(0).getchildat(0)

but next error:

error: phone call perchance undefined method getchildat through reference static type flash.display:displayobject.

what proper way create phone call grandchild element?

getchildat() function returns displayobject

getchildat()

so must type cast follows.

displayobjectcontainer(parent.getchildat(0)).getchildat(0)

actionscript-3 parent-child mxml grandchild

java - How hdfs map-reduce actually work in fully distributed mode -



java - How hdfs map-reduce actually work in fully distributed mode -

i'm bit confused how hdfs map-reduce work in distributed mode.

suppose running word count program. giving path of 'hdfs-site' & 'core-site'.

then how things beingness carried out?

whether programme distributed on each node or ?

yes, programme distributed. wrong say, distributed every node. it's more, hadoop checks info working with, splits info smaller parts (under constraints configuration) , moves code nodes in hdfs these parts (i assume, have datanode , tasktracker running on nodes). first map part exeuted on these nodes, produces data. info stored on nodes , during mapping finishes sec part of job starts on nodes, reduce-phase.

the reducers started on nodes (again, configure how many of them) , fetch info mappers, aggregate them , send output hdfs.

java hadoop mapreduce hdfs

audio - Java Sound. Temporarily mute background music and play a sound -



audio - Java Sound. Temporarily mute background music and play a sound -

i'm in fraternity in college , in fraternity have stairs. every , 1 time again falls downwards stairs. play music computer behind bar (usually net or itunes). have usb button, , write programme temporarily mutes background music , plays clip song "wiiiipe-ouuut" when press button after falls downwards stairs. how sound... have ideas?

it pretty easy create java app exposes little more button plays given sound cue, or set of buttons different cues.

you presumably leave application running, waiting right time press button, in order near-instantaneous response. i'd utilize swing library create button , javax.sound.sampled.clip hold sound in memory , play on command. however, there maybe easier sound objects this, since don't need play cue @ total volume. also, javafx starting used gui buttons.

i don't know how turn downwards itunes or browser volume java. not can't done. if else can how, select answer! haven't tried yet.

but, maybe not hard manually turn , downwards volume of itunes or browser if practice few times. turning volume or downwards has benefit of not beingness disruptive stopping , restarting music application. so, turn downwards volume in app (not main computer volume!), mouse on java button app , click it, wait sound end , turn volume of music app up. not ideal, job of producing desired sounds.

another idea, maybe instead of controlling music apps, there way route output of apps through java before playing them. in case, single button force written handle entire sequence. i'd targetdataline main tool used handle inputting of sound stream, don't know how you'd id appropriate mixer lines or ports. it's has customized setup , os , sound card or sound system.

fun idea! language might work this, e.g., separate little browser window html5 , button launching sound effect.

java audio usb javasound

ruby and gems are installed but sass gem not working -



ruby and gems are installed but sass gem not working -

i know have ruby , gem installed because i've installed bunch of gems previously. additionally when following

~$ ruby --version ruby 1.8.7 (2010-08-16 patchlevel 302 [i486-linux] ~$ gem --version 1.3.7

they, can see, homecoming version--yet when seek this--

~$ sass --watch happy.scss:happy.css bash: sass: command not found

i'm relative noob everything, far more ruby , gems. sake of revealing more or less level of understanding things i've learned plenty of debian environment clojure running , web app working (taken me year of spare time that--i knew virtually nil of programming previoiusly). i'm trying sass working ease mental load in webpage design side of things , i'm hitting brick wall on this.

would path issue? if needs on path 1 gem works --

btw here's happens when install sass--

# gem install sass installed sass-3.2.5 1 gem installed installing ri documentation sass-3.2.5... installing rdoc documentation sass-3.2.5...

any help can give much appreciated. i've been @ 1 day , can't figure out life of me.

justin ⮀ ~ ⮀ gem install sass fetching: sass-3.2.5.gem (100%) installed sass-3.2.5 1 gem installed justin ⮀ ~ ⮀ sass -v sass 3.2.5 (media mark)

seems ok me. check path.

the proper path depend on gems installed. utilize rvm different. seek throw exception in ruby code rubygems loaded should give starting point.

> rails c loading development environment (rails 3.2.11) 1.9.3p362 :001 > throw test argumenterror: wrong number of arguments (0 2..3) (irb):1:in `test' (irb):1 /users/justin/.rvm/gems/ruby-1.9.3-p362@rails3.2/gems/railties-3.2.11/lib/rails/commands/console.rb:47:in `start' /users/justin/.rvm/gems/ruby-1.9.3-p362@rails3.2/gems/railties-3.2.11/lib/rails/commands/console.rb:8:in `start' /users/justin/.rvm/gems/ruby-1.9.3-p362@rails3.2/gems/railties-3.2.11/lib/rails/commands.rb:41:in `<top (required)>' script/rails:5:in `require' script/rails:5:in `<main>'

so see /users/justin/.rvm/gems/ruby-1.9.3-p362@rails3.2/gems/railties-3.2.11/lib/rails/commands/console.rb

so bin path @ /users/justin/.rvm/gems/ruby-1.9.3-p362@rails3.2/bin

and if i

> ls /users/justin/.rvm/gems/ruby-1.9.3-p362@rails3.2/bin

b2json capify fog html2haml nokogiri rails ri sass-convert therubyracer tilt bundle coderay geocode httpclient oauth rake2thor ruby_noexec_wrapper scss lean tt cap erubis haml j2bson rackup rdoc sass sprockets thor

boom sass

so in case want add together /users/justin/.rvm/gems/ruby-1.9.3-p362@rails3.2/bin

but utilize rvm me.

ruby gem sass

Learning x86 assembly language. Need some instructions -



Learning x86 assembly language. Need some instructions -

i'm trying understand x86 assembly language on given example. please give me advice code? code isn't mine comments are.

bits 16 ; means? org 100h ; means? section .bss ; section info tekst resb50 ; variable tekst type resb50 section .text ; main application instructions mov si,tekst ; re-create value of tekst si. value contains 'tekst'? et1: ; label et1 mov ah,01h ; interrupt read input int 21h ; phone call interrupt mov [si],al ; re-create al [si]. why al? why square brackets? cmp al,'0' ; compare al info '0' je petla ; if equal jump petla inc si ; increment si jmp et1 ; jump et1 mov ah,'w' ; re-create 'w' ah mov si,tekst ; re-create tekst si. petla: cmp byte [si], '0' ; compare '0' [si] info je et3 ; if equal jump et3 cmp ah,[si] ; compare [si] info ah je et2 ; if qual jump et2 inc si jmp petla ; jump petla

am wrong above comments?

bits , org directives compiler.

bits sets flavor of code generate (16-bit , 32-bit commands differ little same operands)

org 100h tells compiler skip 256 bytes in resulting image. com file source - in com files, first 256 bytes of segment occupied header directive needed.

in general, larn assembler, it's improve read book on real-mode 1 - explain general cpu architecture , workings executable files inner construction , handling os. can recommend ones in native russian.

assembly x86 ms-dos

sml - Can I fold with an infix operator without writing out an anonymous function? -



sml - Can I fold with an infix operator without writing out an anonymous function? -

if wanted add together list this:

- list.foldr (fn (x, y) => x + y) 0 [1, 2, 3] val = 6 : int

is there way write more along lines of:

list.foldr + 0 [1, 2, 3]

i tried this:

fun inf2f op = fn (x, y) => x op y;

you're close. add together op keyword in sec example.

- list.foldr op + 0 [1,2,3]; val = 6 : int

sml syntactic-sugar

Node.js function returns undefined -



Node.js function returns undefined -

i have issues asyncness of node.js.

rest.js var shred = require("shred"); var shred = new shred(); module.exports = { request: function (ressource,datacont) { var req = shred.get({ url: 'ip'+ressource, headers: { accept: 'application/json', }, on: { // can utilize response codes events 200: function(response) { // shred automatically json-decode response bodies have // json content-type if (datacont === undefined){ homecoming response.content.data; //console.log(response.content.data); } else homecoming response.content.data[datacont]; }, // other response means something's wrong response: function(response) { homecoming "oh no!"; } } }); } } other.js var rest = require('./rest.js'); console.log(rest.request('/system'));

the problem ist if phone call request other.js 'undefined'. if uncomment console.log in rest.js right response of http request written console. think problem value returned before actual response of request there. know how prepare that?

best, dom

first off, useful strip downwards code have.

request: function (ressource, datacont) { var req = shred.get({ // ... on: { // ... } }); }

your request function never returns @ all, when phone call , console.log result, print undefined. request handlers various status codes phone call return, returns within of individual handler functions, not within request.

you right asynchronous nature of node though. impossible return result of request, because request still in progress when function returns. when run request, starting request, can finish @ time in future. way handled in javascript callback functions.

request: function (ressource, datacont, callback) { var req = shred.get({ // ... on: { 200: function(response){ callback(null, response); }, response: function(response){ callback(response, null); } } }); } // called this: var rest = require('./rest.js'); rest.request('/system', undefined, function(err, data){ console.log(err, data); })

you pass 3rd argument request function phone call when request has finished. standard node format callbacks can fail function(err, data){ in case on success pass null because there no error, , pass response data. if there status code, can consider error or whatever want.

node.js

neo4j - filtering a filtered a Cypher query result -



neo4j - filtering a filtered a Cypher query result -

hi here's current query i'd 're-filter':

start film = node(*) match user-[:like]->category-[:similar*0..3]-()<-[:tagged]->movie user.name = "current_user" distinct movie, user, category homecoming user.name, category.name, id(movie), movie.name order movie.name;

http://console.neo4j.org/r/u19iim

here's how looks after current query:

+--------------+----------------+-----------+-------------------------+ | user.name | category.name | id(movie) | movie.name | +--------------+----------------+-----------+-------------------------+ | current_user | c | 14 | movie_c_and_d_and_e | | current_user | d | 14 | movie_c_and_d_and_e | | current_user | e | 14 | movie_c_and_d_and_e | | current_user | | 9 | movie_of_a_and_b_and_b1 | | current_user | b | 9 | movie_of_a_and_b_and_b1 | | current_user | b | 10 | movie_of_b2_first | | current_user | b | 11 | movie_of_b2_second | | current_user | c | 12 | movie_of_c | | current_user | d | 13 | movie_of_d_and_e | | current_user | e | 13 | movie_of_d_and_e | +--------------+----------------+-----------+-------------------------+

i'd group count(sugg) category_count extract this:

+--------------+----------------+-----------+-------------------------+ | user.name | category_count | id(movie) | movie.name | +--------------+----------------+-----------+-------------------------+ | current_user | 3 | 14 | movie_c_and_d_and_e | | current_user | 2 | 9 | movie_of_a_and_b_and_b1 | | current_user | 2 | 13 | movie_of_d_and_e | | current_user | 1 | 10 | movie_of_b2_first | | current_user | 1 | 11 | movie_of_b2_second | | current_user | 1 | 12 | movie_of_c | +--------------+----------------+-----------+-------------------------+

how can accomplish this?

similar questions: - how have 2 aggregation in cypher query in neo4j?

update here's working result (with demo: http://tinyurl.com/cywlycc):

start film = node(*) match user-[:like]->category-[:similar*0..3]-()<-[:tagged]->movie user.name = "current_user" distinct movie, category count(movie) category_count, movie, collect(category.name) categorized homecoming category_count, id(movie), movie.name, categorized order category_count desc;

start film = node(*) match user-[:like]->category-[:similar*0..3]-()<-[:tagged]->movie user.name = "current_user" distinct movie, user, category homecoming user.name, count(category.name) category_count, id(movie), movie.name order category_count desc, movie.name asc

http://console.neo4j.org/r/69rfkn

neo4j cypher

c# - regular expressions with the Cyrillic alphabet? -



c# - regular expressions with the Cyrillic alphabet? -

i writing validation validate inputted data. using regular expressions so, working c#.

password = @"(?!^[0-9]*$)(?!^[a-za-z]*$)^([a-za-z0-9]{6,18})$" validate alpha numeric = [^a-za-z0-9ñÑáÁéÉíÍóÓúÚüÜ¡¿{0}]

the above work fine on latin alphabet, how can expand such working cyrillic alphabet?

the basic approach covering ranges of characters using regular expressions build look of form [a-za-z], a first letter of range, , z lastly letter of range.

the problem is, there no such thing "the" cyrillic alphabet: alphabet different depending on language. if cover russian version of cyrillic, utilize [А-Яа-я]. utilize different range, say, serbian, because lastly letter in cyrillic Ш, not Я.

another approach list characters one-by-one. find authoritative reference alphabet want set in regexp, , set characters pair of square brackets:

[АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя]

c# regex latin

c# - What does this code with "?" and "??" mean? -



c# - What does this code with "?" and "??" mean? -

what syntax mean? i'm coding c# 4.0, when came piece of code.

_data = (serializationhelper.deserialize(request.form[_datakey]) ? tempdata[_datakey] ?? new profiledata ()) profiledata;

if write if statements how then?

the compiler gives me error not writing : aswell more things needed?

looks missed ? there. suspect supposed read:

_data = (serializationhelper.deserialize(request.form[_datakey]) ?? tempdata[_datakey] ?? new profiledata() ) profiledata;

in c# operation a ?? b straight equivalent (a == null ? b : a), or if (a == null) homecoming b; homecoming a; if prefer.

so statement above equivalent to:

object tmp = serializationhelper.deserialize(request.form[_datakey]); if (tmp == null) { tmp = tempdata[_datakey]; if (tmp == null) _tmp = new profiledata(); } _data = tmp profiledata;

c# asp.net-mvc syntax operators

Hash id in url php -



Hash id in url php -

logged in user on site can create documents, pretty much on google docs. document can made public user, or private (defualt). documents stored in database table this:

| id | title | content | public | owner | | 1 | asd | asd | 1 | 1 | | 2 | asd | asd | 0 | 1 | | 3 | asd | asd | 0 | 2 |

if public equals 1, public document can viewed link user: site.com/documents/id

the thing is, though documents can public, don't want users able increment url id 1 time access public documents:

site.com/documents/1 site.com/documents/2 site.com/documents/3

and on...

so maybe should hash id or that? so:

<?php echo 'site.com/documents/'.md5($id); ?>

problem is, can't figure out id on server side since hashed...

what can problem?

depending on security requirements, should ensure document ids random , not guessable. if hash auto-incrementing id, resulting hash may seem random, 1 time notices hashing increasing numeric values (and correctly guesses hashing algorithm), easy guess possible document ids.

to accomplish this, hash random numbers (make sure there no hash collisions in database), or work uuids (see this question illustration on how generate them).

in order map hashed identifiers existing documents, store hash alongside document in database (best utilize hash primary key).

php

geography - PostGIS: ST_Intersects() between two geographies, sometimes returns false result -



geography - PostGIS: ST_Intersects() between two geographies, sometimes returns false result -

i have problem intersect between 2 geographies in postgis: have table1 geography-column, filled multi-polygons in wgs84 (one per line). sec table2 has geography-column filled multi-polygons in wgs84 (one per line). intersect (select (..) st_intersects()) between both.

in (very rare) cases seems me, doesn't work right because intersect returns false true expected: have reprojected tif representing geography 1 line in table1, covers big area in tanzania. have reprojected tif 1 line in table2, covers little area of km². in arcmap, both intersect, little area on border of big, postgis returns false st_intsersects(geog1, geog2).

when export table1 shapefile via dumper, corner-points of geography connected direct lines, not parts of big circles. same result: area table2 outside area table1. guess, postgis calculates simplified polygon, far understood geography meant calculate parts of big circles instead of direct lines ?

i tried ensure both tables filled geography , not geometry, explicit cast geography didn't alter results.

did happen before or have thought did wrong ? problem table2 has geometry , raster-column (=3 spatial columns alltogether) ?

without seeing actual geometries, cannot certain, misinterpreting how great circle lines bound area, , postgis getting right, particularly if you're dealing relationships near boundaries. using google earth line strings (not polygons, not rendered using great circles) visualize examples can helpful in clarifying how things working visually.

postgis geography intersect

android - Galaxy tab can't connect to ADB -



android - Galaxy tab can't connect to ADB -

i working in ubuntu. need connect samsung galaxy tab adb on os. doing in manual: http://developer.android.com/tools/device.html galaxy tab still don't connect adb. when execute "./adb devices", 1 device name this: "?????????". problem , how solve it?

p.s. ubuntu , adb work correct. can connect htc wildfire adb, samsung galaxy tab still can't...

not sure if you've done this:

open next file root:

/etc/udev/rules.d/51-android.rules

then, add together next line:

subsystem=="usb", attr{idvendor}=="04e8", mode="0666", group="plugdev"

save file , exit. check if device shown.

edit: may need restart pc , device. not sure that, on safe side...

android ubuntu adb galaxy-tab

Windows Phone Background Transfer Policies Transfer Limits -



Windows Phone Background Transfer Policies Transfer Limits -

on background file transfers windows phone says:

limits

maximum outstanding requests in queue per application (this includes active , pending requests): 25

but seems limit 5. (according debugs , heaps of googling)

is os version difference between 7.1 , 8.0?

if different versions have different limits there away maximum limit without hardcoding it?

you can read here

background file transfers windows phone

windows-phone-7 background-transfer

ios - How to select correct image depending on size -



ios - How to select correct image depending on size -

i have collection view cells different sizes. these cells shall populated images downloaded. images in cells looks nice, want ensure images big plenty (in terms of width x height cell).

my process that, looks kind of ugly , wanted inquire if there smarter way?

basically following:

the size of cells stored in array, e.g. arraycellsizes cgsize. i fetch images web , store in dictonary, e.g. dictwithimages. now iterate through dictwithimages for-loop, extract height , compare against the height of current cell, from arraycellsizes. the width of image in 99% of cases greater width of cell, no need check. if find image greater in height, it selected current cell and entry of dictwithimages removed, ensure image not selected sec time.

this looks kind of ugly me. has theoretically issue, no perfect image found cell, have set image smaller width cell.

edit: looks nsfetchedresultscontroller answer. have dig it.

cheers -- jerik

ios objective-c collections compare uicollectionview

ruby on rails - RSpec: check if any model has been saved -



ruby on rails - RSpec: check if any model has been saved -

in rails application i've created method creates model hierarchy basing on json data. i'd assure method not save database. know can write test like:

expect { importer.import(json) }.not_to change(model1, :count) expect { importer.import(json) }.not_to change(model2, :count) # etc.

but i'd in more generic way. there method in rspec check if model had been saved during test?

not sure if rspec help this, quick manual trip database might job?

[model1, model2].each |model| model.where('updated_at > ?', time.now - 2.seconds).count.should eq 0 end

ruby-on-rails database rspec mocking

linux - converting a shell script into python program -



linux - converting a shell script into python program -

i have tried writing shell script alerts admin when disk usage reaches 70%. want write script in python

#!/bin/bash admin="admin@myaccount.com" inform=70 df -h | grep -ve ‘^filesystem|tmpfs|cdrom’ | awk ‘{ print $5 ” ” $6 }’ | while read output; use=$(echo $output | awk ‘{ print $1}’ | cutting -d’%’ -f1 ) partition=$(echo $output | awk ‘{ print $2 }’ ) if [ $use -ge $inform ]; echo “running out of space \”$partition ($use%)\” on $(hostname) on $(date)” | mail service -s “disk space alert: $(hostname)” $admin fi done

the easiest(understandable) approach run df command on external process , extract details returned output.

to execute shell command in python, need utilize subprocess module. can utilize smtplib module send emails admin.

i cooked little script should job of filtering filesystems don't need monitor, string manipulation pull out filesystem , % used values , prints out when usage exceeds threshold.

#!/bin/python import subprocess import datetime ignore_filesystems = ('filesystem', 'tmpfs', 'cdrom', 'none') limit = 70 def main(): df = subprocess.popen(['df', '-h'], stdout=subprocess.pipe) output = df.stdout.readlines() line in output: parts = line.split() filesystem = parts[0] if filesystem not in ignore_filesystems: usage = int(parts[4][:-1]) # strips out % 'use%' if usage > limit: # utilize smtplib sendmail send email admin. print 'running out of space %s (%s%%) on %s"' % ( filesystem, usage, datetime.datetime.now()) if __name__ == '__main__': main()

the output of executed script this:

running out of space /dev/mapper/arka-root (72%) on 2013-02-11 02:11:27.682936 running out of space /dev/sda1 (78%) on 2013-02-11 02:11:27.683074 running out of space /dev/mapper/arka-usr+local (81%) on 2013-02-11 02:11

python linux

python - postgres : relation there even after dropping the database -



python - postgres : relation there even after dropping the database -

i dropped database had created django using : dropdb <database>

but when go psql prompt , \d, still see relations there :

how remove postgres can scratch ?

most somewhere along line, created objects in template1 database (or in older versions postgres database) , every time create new db thas objects in it. can either drop template1 / postgres database , recreate or connect , drop objects hand.

python django postgresql

jquery - Using $.when and $.done in AJAX and trying to get result when it is done -



jquery - Using $.when and $.done in AJAX and trying to get result when it is done -

i calling ajax calls , everytime phone call ajax phone call pass function handle it. because keeping counter of ajax requests @ 1 time (mainly using development purposes). trying retrieve results of ajax phone call , set manipulate data.

let me paste code improve clarity.

function get_allsystems() { homecoming $.ajax({ type: "get", url: getsystemurl(), // unimportant, phone call url method cache: false, datatype: "json" }); } // automatically increment , decrement semaphore variable // , execute functions when ajax phone call done. function processajaxcall(performajaxcall, dofunctionwhendone) { ajaxcall++; $.when(performajaxcall).done(function (result) { ajaxcall--; dofunctionwhendone(result); }); } // process ajax scheme info set in object processajaxcall(get_allsystems, function (result) { systemmap["systems"] = result; });

currently getting function result, get_allsystems() instead of actual json of info get.

i want pass ajax calls through function because allows me know if ajax phone call in process , provides level of abstraction like.

so doing wrong, imagine $.done execute when ajax phone call finished , pass results back...but doesn't seem case here.

you need invoke performajaxcall:

function processajaxcall(performajaxcall, dofunctionwhendone) { ajaxcall++; $.when(performajaxcall()/* phone call function */).done(function (result) { ajaxcall--; dofunctionwhendone(result); }); }

performajaxcall returns ajax promise object used $.when.

jquery ajax

c++ - boost binary serialization - why does bitwise copying only seem to work on collections? -



c++ - boost binary serialization - why does bitwise copying only seem to work on collections? -

using boost serialization, i'm trying find best settings fast binary serialization of big objects. tests indicate that, construction tagged bitwise serializable, improve performance on arrays (and vectors), not on individual objects.

for instance, have construction made of pod types

struct bigstruct { double m1; long long m2; float m3; // ... bool m499; short m500; }; namespace boost { namespace serialization { template <class archive> void serialize(archive& ioarchive, bigstruct& iostruct, const unsigned int iversion) { ioarchive & iostruct.m1; ioarchive & iostruct.m2; ioarchive & iostruct.m3; // ... ioarchive & iostruct.m499; ioarchive & iostruct.m500; } } } #include <boost/serialization/is_bitwise_serializable.hpp> boost_is_bitwise_serializable(bigstruct);

then, serializing single object

{ std::ofstream outstream(tmpfolder + "/binaryserializationofbigstruct.txt", std::ios_base::binary); boost::archive::binary_oarchive binoutarchive(outstream, boost::archive::no_header); bigstruct bigstruct; std::clock_t c_start = std::clock(); binoutarchive << bigstruct; std::clock_t c_end = std::clock(); // ...compute elapsed time... }

takes 7 times longer serializing array of 1 object

{ std::ofstream outstream(tmpfolder + "/binaryserializationofbigstructarray.txt", std::ios_base::binary); boost::archive::binary_oarchive binoutarchive(outstream, boost::archive::no_header); bigstruct bigstructarray[1]; std::clock_t c_start = std::clock(); binoutarchive << bigstructarray; std::clock_t c_end = std::clock(); // ...compute elapsed time... }

am missing something? oversight in boost serialization?

btw i'm using boost v1.53.

c++ boost binary bit-manipulation boost-serialization

dojo/aspect - .before() fires whilst .after() doesn't -



dojo/aspect - .before() fires whilst .after() doesn't -

i'm having problems dojo/aspect module.

i have widget (let's phone call class 'b') function called 'test'. widget inherits base of operations class (let's phone call class 'a') implements function i'm talking about. - in function 'test' in class 'b' say:

this.inherited(arguments);

... arranges function in class 'a' called well.

then write this:

require(['dojo/aspect'], function (dojoaspect) { dojoaspect.before(basobject, 'test', function () { alert('ok then...'); }); });

note: simplify example, basobject of course of study object of b.

for reason, when utilize .before(), fires, when utilize .after(), doesn't. that's kinda crucial in case. wan't alert fire after 'test' completed in both classes. if not crucial, don't understand difference, , wan't to.

perhaps dojo core bug?

dojo aspect

ruby on rails - How do I define instance abilities in cancan without defining class abilities? -



ruby on rails - How do I define instance abilities in cancan without defining class abilities? -

how define instance abilities in cancan without defining class abilities?

i want allow :manage action particular course instances, not course class.

# ability.rb can :manage, course of study |course| # check if user helper course of study courserole.get_role(user, course) == "helper" end

this works fine instance variables:

# some_view.rb can? :manage, @course # checks instance see if :manage allowed

but if this:

# some_view.rb can? :manage, course of study

it returns true, bad.

some context:

class user < activerecord::base has_many :course_roles has_many :courses, :through => :course_roles ... class courseroles < activerecord::base belongs_to :user belongs_to :course ... class courses < activerecord::base has_many :course_roles has_many :users, :through => :course_roles

instead of can? :manage, course, can utilize can? :manage, course.new , sure new course of study objects fail block passed in ability.rb

ruby-on-rails ruby cancan

java - Quartz-scheduler DB Lock Exception -



java - Quartz-scheduler DB Lock Exception -

we have application using quartz schedule job. uses jdbcjobstore persisting job related meta-data.

hitherto has been using datasource defined in quartz.properties. according upcoming requirement planning move out datasource quartz.properties , provide part of schedulerfactorybean datasource property.

org.springframework.scheduling.quartz.schedulerfactorybean

according schedulerfactorybean documentation:

when using persistent jobs, recommended perform operations on scheduler within spring-managed (or plain jta) transactions. else, database locking not work , might break

and datasource property docs says:

it hence recommended perform operations on scheduler within spring-managed (or plain jta) transactions. else, database locking not work , might break

well, in case breaking. documentation mean "to perform operations on scheduler within spring-managed (or plain jta) transactions".

the datasource have provided not beingness used anywhere else. quartz.properties this:

org.quartz.scheduler.instancename = jobscheduler org.quartz.scheduler.instanceid = pcmlscheduler org.quartz.plugin.shutdownhook.class=org.quartz.plugins.management.shutdownhookplugin org.quartz.plugin.shutdownhook.cleanshutdown = true org.quartz.threadpool.class = org.quartz.simpl.simplethreadpool org.quartz.threadpool.threadcount = 2 org.quartz.threadpool.threadpriority = 4 org.quartz.jobstore.misfirethreshold = 5000 org.quartz.jobstore.class = org.quartz.impl.jdbcjobstore.jobstoretx org.quartz.jobstore.driverdelegateclass = org.quartz.impl.jdbcjobstore.stdjdbcdelegate org.quartz.jobstore.tableprefix = qrtz_

if can context transaction refering can farther 0 downwards on database lock break:

failure obtaining db row lock: no row exists in table qrtz_locks lock named: trigger_access [see nested exception: java.sql.sqlexception: no row exists in table qrtz_locks lock named: trigger_access]

it true qrtz_locks don't have row, should quartz headache manage that. , managing fine, working when datasource provided in quartz.properties.

update: quartz forum, got duplicate of question, per suggestion, adding next rows qrtz_locks solve issue.

insert qrtz_locks values('trigger_access'); insert qrtz_locks values('job_access'); insert qrtz_locks values('calendar_access'); insert qrtz_locks values('state_access'); insert qrtz_locks values('misfire_access');

i don't how reliable this, worked. interesting observation when providing datasource part quary.properties not expecting these rows. providing datasource part schedulerfactorybean, needs these(probably). ideally, if needed, should have taken care quartz itself.

will need expert comment quartz insider/user.

java quartz-scheduler spring-roo

html - Style alternating columns in a table with colspan cells -



html - Style alternating columns in a table with colspan cells -

i've been asked project create table has alternating column background colors. , good, except there few rows need span other columns while still having "checked" background, determined in each td.

please see the jsfiddle, or code:

body { font-family:calibri, trebuchet ms, verdana, tahoma, sans-serif; } table { border:1px solid #444; text-align:center; } th, td { width:200px; padding:2px; } .lg { background-color:#eee; } .dg { background-color:#ddd; } }

corresponding html:

<table> <tr> <th>fruits</th> <td class="lg">peach</td> <td class="dg">blueberry</td> <td class="lg">apple</td> </tr> <tr> <th>chocolate</th> <td class="lg">chocolate-chip</td> <td class="dg">double chocolate</td> <td class="lg">turtle</td> </tr> <tr> <th>peanut butter</td> <td colspan="3">peanut butter swirl , long list of items</td> </tr> <tr> <th>classics</th> <td class="lg">chocolate</td> <td class="dg">vanilla</td> <td class="lg">strawberry</td> </tr> </table>

currently have background image i've inserted replicate effect in td spanning columns. problem doesn't line no matter how seek (taking screen cap of results, etc.); , should note fixed-width table. in honesty, it's pretty dang close in of them except opera, looks way off.

is there way consistently?

this tough problem. here's out-of-the-box kind of solution, may or may not work you. involves linear "gradient" on colspan3 cells, requires:

a given width on columns (which present, @ 200px, in sample code) a table can in fact accommodate width (as in example, min-width of 800px) either include paddings of cells in gradients, or remove them (as in example)

your html updated such class on colspan-cell:

<td class="fullspan" colspan="3">peanut butter swirl , long list of items</td>

and css had added, utilize of gradient generator:

.fullspan { background: #eee; /* old browsers */ background: -moz-linear-gradient(left, #eee 0%, #eee 200px, #ddd 200px, #ddd 400px, #eee 400px); /* ff3.6+ */ background: -webkit-gradient(linear, left top, right top, color-stop(0%,#eee), color-stop(200px,#eee), color-stop(200px,#ddd), color-stop(400px,#ddd), color-stop(400px,#eee)); /* chrome,safari4+ */ background: -webkit-linear-gradient(left, #eee 0%,#eee 200px,#ddd 200px,#ddd 400px,#eee 400px); /* chrome10+,safari5.1+ */ background: -o-linear-gradient(left, #eee 0%,#eee 200px,#ddd 200px,#ddd 400px,#eee 400px); /* opera 11.10+ */ background: -ms-linear-gradient(left, #eee 0%,#eee 200px,#ddd 200px,#ddd 400px,#eee 400px); /* ie10+ */ background: linear-gradient(to right, #eee 0%,#eee 200px,#ddd 200px,#ddd 400px,#eee 400px); /* w3c */ filter: progid:dximagetransform.microsoft.gradient( startcolorstr='#eee', endcolorstr='#eee',gradienttype=1 ); /* ie6-9 */ }

giving in modern browsers, including opera:

html css table

latex - xtable rownames using R -



latex - xtable rownames using R -

i using r , latex , xtable bundle tables. little puzzled why specified rownames aren't showing in tables. here's example:

\documentclass[a4paper, 11pt]{article} \usepackage[english]{babel} \usepackage[t1]{fontenc} \begin{document} \sweaveopts{concordance=true} <<results=tex, fig=false, echo=false>>= library(xtable) table.matrix <- matrix(numeric(0), ncol = 5, nrow = 12) colnames(table.matrix) <- c("$m_t$", "$p_t$", "$r^b_t$", "$r^m_t$", "$y^r_t$") rownames(table.matrix) <- c("$m_{t-1}$", " ", "$p_{t-1}$", " ", "$r^b_{t-1}$", " ", "$r^m_{t-1}$", " ", "$y^r_t$", " ", "$c$", " ") tex.table <- xtable(table.matrix) align(tex.table) <- "c||ccccc" print(tex.table, include.rownames = true, hline.after = c(-1, 0, seq(0, nrow(table.matrix), = 2)), sanitize.text.function = function(x){x}) @ \end{document}

it seems pretty straightforward me. have estimation of simple var model , in rows want variables (t-1) subscript, , every sec row should have p-values (they're empty right in name vector). ideas?

edit: pointed out nograpes, issue rownames duplicates. know how circumvent (without using first column name column)? want evenly numbered rows empty, alternatively sort of indication p-values.

try running r code, , you'll warning tells why row names aren't showing up:

library(xtable) table.matrix <- matrix(numeric(0), ncol = 5, nrow = 12) colnames(table.matrix) <- c("$m_t$", "$p_t$", "$r^b_t$", "$r^m_t$", "$y^r_t$") rownames(table.matrix) <- c("$m_{t-1}$", " ", "$p_{t-1}$", " ", "$r^b_{t-1}$", " ", "$r^m_{t-1}$", " ", "$y^r_t$", " ", "$c$", " ") xtable(table.matrix) # warning message: # in data.row.names(row.names, rowsi, i) : # row.names duplicated: 4,6,8,10,12 --> row.names not used

so can't have duplicated rownames in r. solve making name "column" instead of using rownames.

r latex sweave xtable

post - Postal Code verification in Scheme (Dr. Racket) -



post - Postal Code verification in Scheme (Dr. Racket) -

i writing programme in scheme (dr. racket) verify canadian postal-codes. user inputs postal code , gets response whether valid or not. got boolean logic downwards stumped how tell right format is.

ex. (valid-postal-code? n2l 3g1) => true

how do this?

thanks

if want know if string has format of valid postal code, can utilize regular expression. canadian postal codes consist of 6 characters, alternating letters , digits origin letter, space embedded between 3rd , 4th characters. suitable regular look ^[a-z][0-9][a-z] [0-9][a-z][0-9]$.

if want know if string valid format on list of postal codes, easiest solution bloom filter. provide bloom filter, written in scheme, @ my blog.

post scheme racket postal-code

mobile - Text in block layout in Appixia app isn't visible -



mobile - Text in block layout in Appixia app isn't visible -

i have genericstaticblockscellview within categorygridview custom category list. followed tutorial , added few blocks row view. have text block holding title, , image block holding row background.

for reason, text of titles still hidden. can't see it.

if can't see text blocks, may have 1 of these potential problems:

make sure background behind text. if background image block defined after text block (ie. block 1 text, block 2 background), in case of overlap drawn on it. can swap order in case. create sure blocks want in front end lastly ones.

if can't see text block, create sure it's positioned properly. seek setting width 100%, height 100%, left 0%, top 0%. create sure see , create appear in middle of row.

last problem, bit crazy, possible this: if background image big, may exceed row boundaries. default, block canvas not clipping, meaning content jumps out, rendered outside row. if background image height big, bigger canvas height, might drawn outside , cover titles of next rows. effect seen in case titles appear in of rows - , not of them. prepare this, can either create background image bit smaller, or create row bigger. alter row height, go categorygridview , find widthheightratio field. if create number bigger create rows taller. best result, number there should background pixel height divided background pixel width.

mobile appixia

javascript - Can't bind script to new elements in the DOM -



javascript - Can't bind script to new elements in the DOM -

so i've working on while, still can't seem figure out.

i have page here: http://taste.fourseasons.com/ingredients/

the show more button @ bottom calls posts on page next script:

$("a.view-more").bind('click',function(event){ event.preventdefault(); if($('.post-holder').hasclass('ingredients')) { posttype = 'ingredient'; } if($('.post-holder').hasclass('recipe')) { posttype = 'recipe'; } if($('.post-holder').hasclass('cmed')) { posttype = 'cmed'; } filter = 'none'; moreposts(posttype,filter); });

and alternative allow people vote works this:

$.post('http://taste.fourseasons.com/wp-admin/admin-ajax.php', data, function(response){ if(response!="-1") { el.find('.vote-sm').removeclass('vote-sm').addclass('unvote-sm'); el.find('.vote-text').html("voted"); el.unbind("click"); if(response!="null") { el.find(".vote-count").html(response); } var cookie = getcookie("better_votes_"+postid); if(!cookie) { var newcookie = postid; } else { var newcookie = postid; } setcookie("better_votes_"+postid, newcookie, 365); } else { } }); homecoming false; });

but when user clicks show more , elements added dom, vote options isn't working new elements. assumed add together them together:

$("a.view-more").bind('click',function(event){ event.preventdefault(); if($('.post-holder').hasclass('ingredients')) { posttype = 'ingredient'; } if($('.post-holder').hasclass('recipe')) { posttype = 'recipe'; } if($('.post-holder').hasclass('cmed')) { posttype = 'cmed'; } filter = 'none'; moreposts(posttype,filter); $(".vote").bind('click',function(event) { event.preventdefault(); postid = $(this).attr('data-post'); var el = $(this); //el.html('<span id="loader"></span>'); var nonce = $("input#voting_nonce_"+postid).val(); var info = { action: 'add_votes_options', nonce: nonce, postid: postid, ip: '66.252.149.82' }; $.post('http://taste.fourseasons.com/wp-admin/admin-ajax.php', data, function(response){ if(response!="-1") { el.find('.vote-sm').removeclass('vote-sm').addclass('unvote-sm'); el.find('.vote-text').html("voted"); el.unbind("click"); if(response!="null") { el.find(".vote-count").html(response); } var cookie = getcookie("better_votes_"+postid); if(!cookie) { var newcookie = postid; } else { var newcookie = postid; } setcookie("better_votes_"+postid, newcookie, 365); } else { } }); homecoming false; }); });

but doesn't seem work , creates scenario adds 2 votes sum instead of one, every time vote.

thanks help.

this code wp-function page:

function add_votes_options() { $postid = $_post['postid']; $ip = $_post['ip']; if (!wp_verify_nonce($_post['nonce'], 'voting_nonce_'.$postid)) return; $voter_ips = get_post_meta($postid, "voter_ips", true); if(!empty($voter_ips) && in_array($ip, $voter_ips)) { echo "null"; die(0); } else { $voter_ips[] = $ip; update_post_meta($postid, "voter_ips", $voter_ips); } $current_votes = get_post_meta($postid, "votes", true); $new_votes = intval($current_votes) + 1; update_post_meta($postid, "votes", $new_votes); $return = $new_votes>1 ? $new_votes : $new_votes; echo $return; die(0); }

you've run mutual issue event binding.

$("a.view-more").bind('click',function(event){

the above line of code wrote attaches event listener dom elements available @ time. why new elements added dom not respond event; because don't have event listener attached.

to work around can utilize called event delegation. works attaching event parent of dom elements wanted hear event on. can work out kid event started on when event propagates parent.

jquery makes easy do. can utilize delegate() method suggest utilize on() method method handles event operations in jquery. others such click(), mouseover() , bind() aliases of on()

anyway, delegate event need specify selector parent event attach to, , selector elements interested in. line of code this:

$("body").on('click', "a.view-more", function(event){

you should utilize other body example.

further reading: http://api.jquery.com/on/

javascript ajax bind

xml parsing - How to perform coreference Resolution in Java using Standford core NLP? -



xml parsing - How to perform coreference Resolution in Java using Standford core NLP? -

i have paragraph of text, , want perform coref resolution on it, pronouns in replaced nouns. here's code i'm using:

properties props = new properties(); props.put("annotators", "tokenize, ssplit,pos,lemma,ner,parse,dcoref"); stanfordcorenlp pi= new stanfordcorenlp(props); string text = "delhi capital city of india.it sec populous metropolis in republic of india after bombay , largest city in terms of area."; annotation doc = new annotation(text); pi.annotate(doc); map<integer, corefchain> graph = doc.get(corefchainannotation.class); (map.entry entry : graph.entryset()) { corefchain c = (corefchain) entry.getvalue(); corefmention cm = c.getrepresentativemention(); system.out.println(c); }

java xml-parsing stanford-nlp

javascript - binding a custom event using knockout -



javascript - binding a custom event using knockout -

this question has reply here:

using knockout js jquery ui sliders 3 answers

i using jquery ui slider command raises alter event. want utilize knockout bind alter event , phone call method within model. how done? confused, because event isn't related dom or typically used bind.

why not utilize event listener sets model variable, ie

var callback = function(value) { komodel.somevariable(value); }

and utilize callback slider.

javascript knockout.js

iphone - Is there any way to add pre-existing users to the "paid list" for new iOS in-app purchases? -



iphone - Is there any way to add pre-existing users to the "paid list" for new iOS in-app purchases? -

i in tricky spot , trying figure out best way proceed. released app few months ago , have charged few hundred people $.99 it. interested in making app free in-app purchases. how can create whoever has paid it, doesn't need pay again? can programmatically "white list" them? , charge future users?

i have integrated game center toying around thought of checking users on leader boards already?

i can't create separate app, wondering if there api or route utilize accomplish this.

thanks!

here's potential strategy:

1) create in-app purchase toggle enables access features or resources in app.

2) alter name or location of key file. database easiest (if have one), user defaults or other saved files.

3) on launch of new version, check see if older thing exists - if so, save marker key keychain app (and if renamed database move old version new name/location!). keychain nice place set persists between app installs. i'm not sure if icloud backs though.

4) when checking feature marker key in keychain in add-on asking storekit if have purchased items want unlocked them.

5) in ui block purchase , indicate have paid.

that's best can do, may have deleted app altogether , in case there's nil can help them... may want create kind of one-time utilize code unlock feature in same way (except code verified app against server used when allowed it), way help out individuals contacting saying had purchased app before. there's no way verify it's client service allow them have upgrade anyway.

iphone ios in-app-purchase upgrade

change color of hyperlink in alternate rows of table CSS -



change color of hyperlink in alternate rows of table CSS -

i have changed color of alternate rows of table using next css:

tr:nth-child(odd) { background-color:#dedede; color: black; } tr:nth-child(even) { background-color:none; }

but want alter color of hyperlinks in alternate rows using css. tried alter color using

tr:nth-child(odd) a{ background-color:#dedede; color: black; } tr:nth-child(even) a{ background-color:none; }

but doesn't works me

please help in advance

it's working fine dear seek :

tr:nth-child(odd) a{ background-color:#dedede; color: #996633; } tr:nth-child(even) a{ background-color:none; color : #ff0000}

css table

java - SNMP4J: how to limit received trap by community string or at least know the community string of the trap? -



java - SNMP4J: how to limit received trap by community string or at least know the community string of the trap? -

i wrote application based on snmp4j sending snmp requests , receiving traps. works fine couldn't find how set community string received traps or how see community string each received trap.

help highly appriciated

i'm afraid it's not true "community name".

the method "event.getsecurityname()" gives "securityname" of trap package. , set when config trap info on device.

the true "community name" used config device snmpv2 api. example, community of device "public", , can set snmpv2c trap info security name of "mypublic". "mypublic" calling event.getsecurityname() not "public".

java snmp trap snmp4j

python - Why does my naive implementation of the Sieve of Atkins exclude 5? -



python - Why does my naive implementation of the Sieve of Atkins exclude 5? -

i wrote extremely naive implementation of sieve of atkin, based on wikipedia's inefficient clear pseudocode. wrote algorithm in matlab, , omits 5 prime number. wrote algorithm in python same result.

technically, know why 5 beingness excluded; in step n = 4*x^2 + y^2, n == 5 when x == 1 , y == 1. occurs once, 5 flipped prime nonprime , never flipped back.

why doesn't algorithm match 1 on wikipedia? although have made few superficial adjustments (e.g. calculating x^2 1 time in each iteration, storing value of mod(n, 12) when using in first equation, etc.) shouldn't alter logic of algorithm.

i read on several discussions related sieve of atkin, can't tell differences creating problems in implementations.

python code: def atkin1(limit): res = [0] * (limit + 1) res[2] = 1 res[3] = 1 res[5] = 1 limitsqrt = int(math.sqrt(limit)) x in range(1, limitsqrt+1): y in range(1, limitsqrt+1): x2 = x**2 y2 = y**2 n = 4*x2 + y2 if n == 5: print('debug1') nmod12 = n % 12 if n <= limit , (nmod12 == 1 or nmod12 == 5): res[n] ^= 1 n = 3*x2 + y2 if n == 5: print('debug2') if n <= limit , (n % 12 == 7): res[n] ^= 1 if x > y: n = 3*x2 - y2 if n == 5: print('debug3') if n <= limit , (n % 12 == 11): res[n] ^= 1 ndx = 5 while ndx <= limitsqrt: m = 1 if res[ndx]: ndx2 = ndx**2 ndx2mult =m * ndx2 while ndx2mult < limit: res[ndx2mult] = 0 m += 1 ndx2mult = m * ndx2 ndx += 1 homecoming res matlab code function p = atkin1(limit) % 1. create results list, filled 2, 3, , 5 res = [0, 1, 1, 0, 1]; % 2. create sieve list entry each positive integer; entries of % list should marked nonprime (composite). res = [res, zeros(1, limit-5)]; % 3. each entry number n in sieve list, modulo-sixty remainder r: limitsqrt = floor(sqrt(limit)); x=1:limitsqrt y=1:limitsqrt x2 = x^2; y2 = y^2; % if r 1, 13, 17, 29, 37, 41, 49, or 53, flip entry each % possible solution 4x^2 + y^2 = n. n = 4*x2 + y2; nmod12 = mod(n, 12); if n <= limit && (nmod12 == 1 || nmod12 == 5) res(1, n) = ~res(1, n); end % if r 7, 19, 31, or 43, flip entry each possible solution % 3x^2 + y^2 = n. n = 3*x2 + y2; if n <= limit && mod(n, 12) == 7 res(1, n) = ~res(1, n); end % if r 11, 23, 47, or 59, flip entry each possible solution % 3x^2 - y^2 = n when x > y. if x > y n = 3*x2 - y2; if n <= limit && mod(n, 12) == 11 res(1, n) = ~res(1, n); end end % if r else, ignore completely. end end % 4. start lowest number in sieve list. ndx = 5; while ndx < limitsqrt m = 1; if res(ndx) % 5. take next number in sieve list still marked prime. % 6. include number in results list. % 7. square number , mark multiples of square nonprime. ndx2 = ndx^2; ndx2mult = m * ndx2; while ndx2mult < limit res(ndx2mult) = 0; m = m + 1; ndx2mult = m * ndx2; end end % 8. repeat steps 5 through eight. ndx = ndx + 1; end p = find(res); % find indexes of nonzerogo end wikipedia pseudocode // arbitrary search limit limit ← 1000000 // initialize sieve is_prime(i) ← false, ∀ ∈ [5, limit] // set in candidate primes: // integers have odd number of // representations quadratic forms (x, y) in [1, √limit] × [1, √limit]: n ← 4x²+y² if (n ≤ limit) , (n mod 12 = 1 or n mod 12 = 5): is_prime(n) ← ¬is_prime(n) n ← 3x²+y² if (n ≤ limit) , (n mod 12 = 7): is_prime(n) ← ¬is_prime(n) n ← 3x²-y² if (x > y) , (n ≤ limit) , (n mod 12 = 11): is_prime(n) ← ¬is_prime(n) // eliminate composites sieving n in [5, √limit]: if is_prime(n): // n prime, omit multiples of square; // sufficient because composites managed // on list cannot square-free is_prime(k) ← false, k ∈ {n², 2n², 3n², ..., limit} print 2, 3 n in [5, limit]: if is_prime(n): print n

in wikipedia's text description of algorithm, "results list" , "sieve list" 2 different things. matlab code has 1 vector used both. initial value in sieve list 5 should "non-prime".

python matlab sieve-of-atkin

binding - WPF DataTemplate for Collection -



binding - WPF DataTemplate for Collection -

i must hang head, have scoured google hours , still have no clue i'm doing wrong.

<datatemplate datatype="{x:type local:controllers}"> <listbox> <listbox.itemtemplate> <datatemplate> <wrappanel> <textblock text="{binding path=port}" /> </wrappanel> </datatemplate> </listbox.itemtemplate> </listbox> </datatemplate>

what i'm trying display arbitrary number of controller objects in list. "controllers" alias "list<controller>". "port" property of each "controller" object, of course of study that's not showing on list. items beingness correctly added collection list based on (the collection stored content property of contentcontrol displaying collection of objects), no item in collection beingness displayed.

i thought @ first might update issue--that collection beingness correctly displayed in initial, empty state, isn't case; if start collection populated, still no items.

help me, obi wan. :(

you need bind listbox. {binding}, refers instance of datatemplates datatype passed in @ run-time.

<datatemplate datatype="{x:type local:controllers}"> <listbox itemssource="{binding}"> <listbox.itemtemplate> <datatemplate> <wrappanel> <textblock text="{binding path=port}" /> </wrappanel> </datatemplate> </listbox.itemtemplate> </listbox> </datatemplate>

wpf binding collections datatemplate

asp.net - It is possible to have this format in ASP .Net GridView? -



asp.net - It is possible to have this format in ASP .Net GridView? -

i have been

name | age | sex | id no.

abc | 24 | m | 12312131

address:3rd street(colspan of whole row above)

fdc | 26 | f | 1232131 address:4rd street

(see there http://i46.tinypic.com/xymna.jpg) while in gridview didn't find way add together new row every record (like repeater want stick gridview create info manageable.

thank much.

you need utilize listview instead , employ templates accomplish layout you're seeking:

listview web server command overview

asp.net gridview