Monday, 15 June 2015

mips - Count number of lowercase letters -



mips - Count number of lowercase letters -

so have created programme count number of lowercase letters in string. problem having when reach end of string , nl character reached, line beq $t0, $t1, end not beingness executed; continues indefinitely. i'm not sure i'm doing incorrectly.

.data msg1: .word 0:24 .text .globl main main: addu $s0, $0, $ra li $v0, 8 la $a0, msg1 la $a1, 100 syscall loop: lb $t0, 4($a0) li $t1, 0x0a beq $t0, $t1, end continue: li $t1, 'a' blt $t0, $t1, count li $t1, 'z' bgt $t0, $t1, count count: addi $t4, $t4, 1 j loop end: li $v0, 1 addu $a0, $t2, $0 syscall jr $ra

you compare 4($a0) 0x0a on each iteration of loop, never alter $a0 in loop, not advancing through string , never @ \n @ end of string.

there few other bugs in code.

use @ start of loop:

loop: lb $t0, 0($a0) addiu $a0, $a0, 1 ...

mips

Half Duplex RS485 linux Serial USB Programing in C -



Half Duplex RS485 linux Serial USB Programing in C -

i'm trying setup half duplex communication in ubuntu 14.04 in program. have rs485 transceiver using rts line toggle , forth between transmit , receive. i'm using speak when spoken scheme , programme master. problem rts isn't toggling off when i'm done sending bundle can receive data. want turn rts high, send data, turn rts low, read data. help great.

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <termios.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <sys/signal.h> #include <sys/types.h> #define baudrate b38400 #define comport "/dev/ttyusb0" #define _posix_source 1 #define false 0 #define true 1 #define stx_keypad 0xe1 #define payload_buff_size 256 #define crc_hi 0xd8 #define crc_low 0xc3 volatile int stop=false; int ser_port; int bus_address = 1; int message_length = 0; struct termios oldtio,newtio; unsigned char rxbuf[256]; unsigned char tx_flags = 0; void opencommport(); void sendserial(); int setrts(int level); int main(void) { printf("starting...\r\n"); opencommport(); setrts(1); printf("sending serial data\r\n"); sendserial(); setrts(0); //close(ser_port); printf("all done\r\n"); homecoming exit_success; } void opencommport() { ser_port = open(comport, o_rdwr | o_noctty | o_nonblock); if (ser_port == -1) { perror(comport); perror("unable open port"); exit(-1); } if(tcgetattr(ser_port,&oldtio) <0)// save current port settings { perror(comport); perror("couldn't old terminal attributes"); exit (-1); } bzero(&newtio, sizeof(newtio)); newtio.c_cflag = baudrate | cs8 | clocal | cread | crtscts; newtio.c_iflag = ignpar | icanon; newtio.c_oflag = 0; // set input mode (non-c, no echo,...) newtio.c_lflag = 0; newtio.c_cc[vtime] = 0; // inter-character timer unused newtio.c_cc[vmin] = 0; // blocking read until 5 chars received tcflush(ser_port, tciflush); tcsetattr(ser_port,tcsanow,&newtio); } void sendserial() { unsigned char tx_header[6]; tx_header[0] = stx_keypad; tx_header[1] = bus_address; tx_header[2] = tx_flags; tx_header[3] = message_length; tx_header[4] = crc_hi; tx_header[5] = crc_low; if((write(ser_port, tx_header, 6)) != 6) { printf("error sending data! not bytes sent\r\n"); } } int setrts(int level) { int status; if (ioctl(ser_port, tiocmget, &status) == -1) { perror("getrts(): tiocmset"); homecoming 0; } if(level) { status |= tiocm_rts; } else { status &= ~tiocm_rts; } if (ioctl(ser_port, tiocmset, &status) == -1) { perror("setrts(): tiocmset"); homecoming 0; } homecoming 1; }

c linux ubuntu serial-port rs485

c# - How to tell count of non-empty strings in string array -



c# - How to tell count of non-empty strings in string array -

i have string pipe delimited:

string line = "test|||tester||test||||||test test|"

i reading intro string array:

string[] wordsarr = line.split(new string[] { "|" }, stringsplitoptions.none);

my goal without manually writing loop myself if there way built framework see how many items in array not empty. can't utilize removeemptyentries property on stringsplitoptions b/c items fall within pipes matter.

any ideas?

if looking count, utilize .count after split.

string line = "test|||tester||test||||||test test|"; int notemptycount = line .split('|') .count(x => !string.isnullorempty(x));

if want filter out items empty , access items remain, utilize .where instead.

var notemptycollection = line .split('|') .where(x => !string.isnullorempty(x));

c# arrays string

Windows Batch - Change the beginning of a path but keep the rest -



Windows Batch - Change the beginning of a path but keep the rest -

i'm running ffmpeg video encoding. have batch file encode files drop on it, keeping file's original name , re-create encoded files specific directory. script "know" original's file path , re-create encoded file path relative it, meaning: original file dropped on batch file in c:\some\folder\show\season\episode\file.mov encoded file should encoded d:\different\directory\show\season\episode\file.mp4 part of path until \show fixed.

this have far:

@echo on set count=0 %%a in (%*) (<br> if exist %%a ( md \\specific\path\"%%~na" %myfiles%\ffmpeg.exe -i "%%~a" -vcodec libx264 -preset medium -vprofile baseline -level 3.0 -b 500k -vf scale=640:-1 -acodec aac -strict -2 -ac 2 -ab 64k -ar 48000 "%%~na_500.mp4" re-create "%%~na_500.mp4" "\\specific\path\"%%~na"\%%~na_500.mp4" re-create "%%~na_500.mp4" "\\specific\path\"%%~na"\%%~na_500.mp4" del "%%~na_500.mp4"

set /a count+=1

) else ( echo skipping non-existent %%~a

thank you, oren

class="lang-dos prettyprint-override">@echo off setlocal set "myfiles=my_files" set "fixed_path=u:\destdir" %%a in ("%*") if exist "%%a" ( /f "tokens=3*delims=\" %%b in ("%%~dpa") ( echo(md "%fixed_path%\%%c" echo(%myfiles%\ffmpeg.exe -i "%%~a" -vcodec libx264 -preset medium -vprofile baseline -level 3.0 -b 500k -vf scale=640:-1 -acodec aac -strict -2 -ac 2 -ab 64k -ar 48000 "%%~na_500.mp4" echo(copy "%%~na_500.mp4" "%fixed_path%\%%c%%~na_500.mp4" echo(del "%%~na_500.mp4" ) ) else (echo(%%~a not exist ) goto :eof

the required md commands simply echoed testing purposes. after you've verified commands correct, alter echo(md md create directories. append 2>nul suppress error messages (eg. when directory exists)

similarly, del , copy commands simply echoed.

i set myfiles constant - no uncertainty yours different , set fixed _path constant convenience of editing.

no thought whether ffmpeg command right - edited yours, , i'm puzzled utilize of 2 apparently identical copy commands in succession, maybe eyes playing tricks...

windows batch-file ffmpeg

opencv - Draw minimum enclosing circle around a contour in EmguCV -



opencv - Draw minimum enclosing circle around a contour in EmguCV -

how draw minimum enclosing circle around contour in emgucv?. findcontours() method returns set of points. draw circle asks pointf. there work around this? thanks.

yes there way. have convert contour array of pointf this:

for (var contour = binaryimage.findcontours(chain_approx_method.cv_chain_approx_simple, retr_type.cv_retr_ccomp, mem); contour != null; contour = contour.hnext) { //assuming have way of getting index of //point wanted extract current contour var index = 0; pointf[] pointfs = array.convertall(contour.toarray(), input => new pointf(input.x, input.y)); //just illustration var circle = new circlef(pointfs[index], 2.0f); }

opencv image-processing emgucv

linux kernel - Adding boot argument -



linux kernel - Adding boot argument -

i trying understand, how boot arguments created , passed kernel.

i thinking next steps, please confirm.

1.add new boot argument in header file under u-boot source(include/configs/)

my understanding is, each board having 1 header file under "include/configs" of u-boot source. please right me if wrong.

2.modify kernel take new boot argument.

doubht) please tell me modify kernel take new boot argument.

could please guide me understand 1 existing boot arg implementation.

thanks in advance.

correct 1.

i don't know kernel modification. in function receiving arguments (i think stacked in main() function).

linux-kernel u-boot

assembly language, strange loop -



assembly language, strange loop -

i'm struggling understand code does

ldi r20, 80 loop: asr r20 brsh loop nop

what code doing , how many clock cycles code take execute?

this seems atmel avr assembly code. in loop continues until carry bit of status register set, shifts hexadecimal 80 arithmetically right 1 position r20 takes successive values of 80, c0, e0, f0, f8, fc, fe, ff. until now, low bit has been 0, , value has been shifted carry bit of status register. on next shift, low bit of ff shifted, 1. causes loop exit.

see http://www.atmel.com/webdoc/avrassembler/avrassembler.wb_asr.html on asr instruction.

the net effect cause little delay.

assembly

Wordpress - admin pre-output hook with permission check -



Wordpress - admin pre-output hook with permission check -

on wordpress plugin, want create "export table csv" feature can downloaded highest kind of admin.

what best hook utilize , how check permission?

<?php add_action( 'admin_init', 'xxxxxx_admin_init' ); function xxxxxx_admin_init() { # admin.php?page=xxxxxx_admin_page&&mode=export_csv if ($_get['page'] == 'xxxxxx_admin_page' && $_get['mode'] == 'export_csv') { if (!user_can('export')) { die("permission denied"); } header("content-type:text/csv"); echo "column\r\nvalue\r\nvalue"; die(); } }

thanks in advance

edit: added die(); after csv echo

check 1 of admin abilities, user_can('manage_options')

wordpress roles , capabilities

wordpress

git - Source control confusion -



git - Source control confusion -

im pretty new android development although ive been working on kernel time. questions is: ive made changes across modules in kernel , top level directory of kernel, if git diff or git status, shows changes ive made. fine.

now, coming android, ive made changes across multiple modules of android source , ive lost track of changes ive made. thought issuing git diff fetch me changes have gone android source. unfortunately, when did that, there message saying not git repository.

now how can find changes ive made in android source? should have go each individual module build/abi/bionic etc , git diff? other way?

the android project utilize git-repo manage git repositories.

so, see diff in android tree utilize repo diff.

git git-repo

android - DriveResource.listParents does not work -



android - DriveResource.listParents does not work -

i developing application android, need list of parents of file taken google drive.

i correctly obtain driveid using drive.driveapi.newopenfileactivitybuilder(), when utilize driveresource.listparents obtain empty list if resource have parent.

i utilize same googleapiclient drive.driveapi.newopenfileactivitybuilder() , driveresource.listparents, not think scope problem.

@override public void onactivityresult(int requestcode, int resultcode, intent data) { if (requestcode == constants.request_code_google_drive_file_picker) { if (resultcode == result_ok) { mselectedfiledriveid = (driveid) data.getparcelableextra(openfileactivitybuilder.extra_response_drive_id); } else { setresult(constants.result_code_ko); finish(); } } } ... private resultcallback<metadatabufferresult> metadatabuffercallback = new resultcallback<metadatabufferresult>() { @override public void onresult(metadatabufferresult result) { if (!result.getstatus().issuccess()) { sdkutils.showmessage(thisactivity, "impossible salvare l'ultima posizione aperta in google drive"); return; } metadatabuffer metadatabuffer = result.getmetadatabuffer(); // here obtain empty object } }; ... mgoogleapiclient = new googleapiclient.builder(this) .setaccountname(driveaccontname) .addapi(drive.api) .addscope(drive.scope_file) .addconnectioncallbacks(this) .addonconnectionfailedlistener(this).build(); ... drivefile drivefile = drive.driveapi.getfile(getgoogleapiclient(), mselectedfiledriveid); drivefile.listparents(googleapiclient apiclient).setresultcallback(metadatabuffercallback);

have suggestions? thanks!

so not think scope problem.

it's - scope problem !!!

google drive android api provides drive.file , drive.appfolder scope.

file scope means access files user chooses application. drive.driveapi.newopenfileactivitybuilder() dialog allow user browse through whole drive application granted access file or folder user select's.

suppose have next folder construction on drive -

/root | +---books +---c++ +---programming_gems.pdf +---c++_notes.docs

now using drive.driveapi.newopenfileactivitybuilder() pick programming_gems.pdf. app has obtained access pdf. can retrieve file , metadata. app won't able obtain access parent folder, c++ in case. why? because user has not yet given access c++ folder; specific file within folder. makes sense also; otherwise can retrieve file folder leaving user worried.

pick c++ folder using same drive.driveapi.newopenfileactivitybuilder(). if app tries retrieve parent folder of programming_gems.pdf, granted access.

try 1 more thing now; seek list contents of c++ folder itself. wil returned app? - programming_gems.pdf. why, because user has not granted access other file, c++_notes.docs.

i hope clear.

p.s.

by way, select between picking files or folder, have set mime type. see next code e.g.,

if (openfolder) { mime_type = new string[]{drivefolder.mime_type}; } else { mime_type = new string[]{}; } intentsender intentsender = drive.driveapi .newopenfileactivitybuilder() .setmimetype(mime_type) .build(getgoogleapiclient());

if scheme of scopes don't match requirements can alternatively utilize google drive rest apis - read on - http://stackoverflow.com/a/25871516/1363471

android google-drive-sdk

How can I do branching in a SQL Server Stored Procedure? -



How can I do branching in a SQL Server Stored Procedure? -

i have next table:

create table [dbo].[test] ( [testid] int identity (1, 1) not null, [testtypeid] int not null, [examid] int not null, [teststatusid] int not null, [topicid] int not null );

i using stored procedure created inserting data:

create procedure dbo.sp_ins_test @examid int , @teststatusid int , @testtypeid int , @topicid int begin

how can different action depending on value of @testtypeid ?

what want if testtypeid = 1 update test records have topicid = @topicid , alter teststatusid 2.

if testtypeid = 2 update test records have examid = @examid , alter teststatusid 2.

here have far:

update dbo.test set teststatusid = 2 testtypeid = @testtypeid , title = @title; update dbo.test set teststatusid = 2 examid = @examid , title = @title;

however not sure how select 1 or other update depending on value of testtypeid.

create procedure dbo.sp_ins_test @examid int , @teststatusid int , @testtypeid int , @topicid int begin if @testtypeid = 1 begin update dbo.test set teststatusid = 2 testtypeid = @testtypeid , title = @title; end if @testtypeid = 2 begin update dbo.test set teststatusid = 2 examid = @examid , title = @title; end end

sql-server

wxpython display a corupted image -



wxpython display a corupted image -

does out there have process or solution displaying corrupted image using wxpython. clear image corrupted acdsee still able display (all displayed corrupted), default windows fax/image viewer can display image (all corrupted). when seek process image wx error , script stops:

image.thumbnail((newwidth, temp_height), image.antialias) file "c:\python27\lib\site-packages\pil\image.py", line 1559, in thumbnail self.load() file "c:\python27\lib\site-packages\pil\imagefile.py", line 215, in load raise_ioerror(e) file "c:\python27\lib\site-packages\pil\imagefile.py", line 52, in raise_ioerror raise ioerror(message + " when reading image file") ioerror: broken info stream when reading image file

i realize find error occurs , "skip" corrupted images rather able display them (than skip them) despite corruption, 2 programs mention above can. help/suggestions/guidance appreciated.

fyi. not downing wx, love it! ms paint cannot display image, gracefully fails , gives message image corrupted (the equivalent of skipping) , ms image manager hung on image. if consensus wx can't handle corrupted images willing take , add together "skipping" code corrupted images, wanted inquire question before did so.

i don't think wxpython supports currently. create kind of default broken image or message can display instead. might seek using python imaging library open image.

if can find open source image viewer work corrupt images, should take @ code see if patch wxpython.

image wxpython corrupt

jQuery: Match elements between .class and items // Combine nextAll() and nextUntil() -



jQuery: Match elements between .class and items // Combine nextAll() and nextUntil() -

i have dom

<div class="c">c</div> <div class="a">match me not</div> <div class="c">c</div> <div class="c wrapper">c .wrapper</div> <div class="a">match me!</div> <div class="a">match me!</div> <div class="c">c</div> <div class="a">match me not</div> <div class="c">c</div>

and need match .a after .wrapper until next .c

nextall() matches after

nextuntil() selects lastly element

test: http://jsfiddle.net/d4sss/1/

use way

$(".wrapper").nextuntil('.c').filter(".a").addclass("matched");

demo

jquery nextuntil

xslt - How to place one particular element from an XML array into an FO object? -



xslt - How to place one particular element from an XML array into an FO object? -

xml code:

<eusesummary> <name>eusummary</name> <title1 index="1">proposed</title1> <title1 index="2">proposed</title1> <title1 index="3">proposed</title1> <title1 index="4">standard</title1> <title1 index="5">standard</title1> <title1 index="6">standard</title1> <title1 index="7">compliance</title1> <title1 index="8">cahp</title1> <title2 index="1">design</title2> <title2 index="2">design</title2> <title2 index="3">design</title2> <title2 index="4">design</title2> <title2 index="5">design</title2> <title2 index="6">design</title2> <title2 index="7">margin</title2> <title2 index="8">design</title2> <title3 index="0">end use</title3> <title3 index="1">site (kwh)</title3> <title3 index="2">site (therms)</title3> <title3 index="3">(ktdv/ft²-yr)</title3> <title3 index="4">site (kwh)</title3> <title3 index="5">site (therms)</title3> <title3 index="6">(ktdv/ft²-yr)</title3> <title3 index="7">(ktdv/ft²-yr)</title3> <title3 index="8">(ktdv/ft²-yr)</title3> <enduse1 index="0">space heating</enduse1> <enduse1 index="1">246</enduse1> <enduse1 index="2">286.5</enduse1> <enduse1 index="3">21.04</enduse1> <enduse1 index="4">255</enduse1> <enduse1 index="5">296.8</enduse1> <enduse1 index="6">21.80</enduse1> <enduse1 index="7">0.76</enduse1> <enduse1 index="8">23.18</enduse1> </eusesummary>

a little piece of xsl code pasted below. defining 1 cell within table. want grab enduse values @ position index=8 , place in remaining cells of table. now, need clarification how select specific value object of xml:

<fo:table-row xsl:use-attribute-sets="row"> <fo:table-cell xsl:use-attribute-sets="datacell"> <fo:block> <xsl:value-of select="/sddxml/model/proj/eusesummary/enduse1/*[@index=8]"/> </fo:block> </fo:table-cell>

what i'm expecting homecoming cell value (within larger table haven't provided code for) of: 23.18

thanks,

your current xpath ends in this...

enduse1/*[@index=8]

but /* means looking kid element under enduse1 of there none! there text node, not element.

try instead:

<xsl:value-of select="/sddxml/model/proj/eusesummary/enduse1[@index=8]"/>

xml xslt xsl-fo

c++ - Using DirectXTex Library -



c++ - Using DirectXTex Library -

i trying update directx project new windows 8.1 sdk (2013 or something) , rid of directx sdk june 2010. have come far, stuck @ linker error lnk2001

error 3 error lnk2001: unresolved external symbol "long __cdecl directx::createddstexturefromfile(struct id3d11device *,wchar_t const *,struct id3d11resource * *,struct id3d11shaderresourceview * *,unsigned int,enum directx::dds_alpha_mode *)" (?createddstexturefromfile@directx@@yajpauid3d11device@@pb_wpapauid3d11resource@@papauid3d11shaderresourceview@@ipaw4dds_alpha_mode@1@@z) c:\users\dimmerfan\documents\visual studio 2013\projects\mikaeld3d\mikaeld3d\textureclass.obj mikaeld3d

i guess doesnt much. code error:

hresult result; result = directx::createddstexturefromfile(device, filename, nullptr, &m_texture, 0, nullptr); if (failed(result)) { homecoming false; } homecoming true;

where function directx::createddstexturefromfile directxtex sdk. somehow fail include library project. dont know have gone wrong. intellisence pops , looks good. have included d:\directxtex\ddstextureloader include directorys , including #include <ddstextureloader.h> help error

//mikael törnqvist

you can seek add together ddstextureloader.h , ddstextureloader.cpp project, directxtex provided source code, if want utilize it, should add together solution/project.

you can build directxtex project yourself, , utilize headers , libs.

c++ directx

powershell - Argument errors with office 365 cmdlet -



powershell - Argument errors with office 365 cmdlet -

i'm having issues feeding variables new-msoluser cmdlet. i'm getting next error.

new-msoluser : positional parameter cannot found accepts argument 'â?userprincipalname ausertest@test.ie â?usagelocation'. @ c:\users\test\documents\test.ps1:148 char:1 + new-msoluser -displayname $targetfullname â?"userprincipalname $targetemail â?" ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + categoryinfo : invalidargument: (:) [new-msoluser], parentcontainserrorrecordexception + fullyqualifiederrorid : positionalparameternotfound,microsoft.online.administration.automation.newuser

the code using is:

$source = "anotheraduser" $targetfname = "new" $targetlname = "user" $target = "ausertest" $targetfullname = [string]::concat($targetfname ," ", $targetlname) $sourceemail = (get-aduser $source -property emailaddress).emailaddress $sourcedomain = $sourceemail.split("@")[1] $targetemail = ([string]::concat($target , "@" , $sourcedomain)) new-msoluser -displayname $targetfullname –userprincipalname $targetemail –usagelocation "ie" | set-msoluserlicense -addlicenses "testinstall:exchangestandard"

this command works when hardcode details..

–userprincipalname , –usagelocation utilize not minus character character code 8211. maybe it's fine seek utilize standard minus instead, sure.

powershell office365

how to pass objects in sockjs connection? -



how to pass objects in sockjs connection? -

i want send objects between client , server. however, when seek pass object, find unable utilize (values undefined).

to around this, passing object through connection string using

json.stringify @ source

and

json.parse @ destination

this working far worried inelegant solution , when start working complex object (graphics objects etc), end in bad place.

is there native way in sockjs working objects?

thanks.

using network, transferred in binary form 0/1. regardless of info (image, json, string, audio, video, etc..).

the process of converting 1 form called serialisation/deserialisation. websockets default back upwards binary , text based messages. text utf-8, overkill send images in representation of characters text, or base64 not best way require more 1 conversion.

for binary type of info (images, audio, video) should sent binary (blobs), , strings should sent text.

json - text based human readable format , parsers pretty fast today "ok" stringify , parse send around. if there actual problem performance atm, need address logic info protocol here, consider using protobuff or bson send in more efficient way info around.

but should not worry on stage of development. way improve work on real problems.

object sockjs

php - CakePHP: Always use clear() instead of create()? -



php - CakePHP: Always use clear() instead of create()? -

there's small, of import difference, between calling clear() , create() within loop:

let's assume next code:

foreach ($posts $post) { $this->post->create(); $this->post->id = $post['post']['id']; $this->post->save(['column3' => 'foo', 'column4' => 'bar']); }

when doing create(): column 1, might default boolean false, magically added updated-fields , can lead info loss (think of post column1 = true).

when doing clear() instead of create(): column 1, not mentioned in save-statement not touched @ all.

so, safe rely on clear() in foreach, existing info partially updated?

second party of question: always improve rely on clear()? (when looking @ code of clear(), see, it's convenience wrapper create(false)). , difference in create() , create(false) initialization of default values. think, default values should improve set straight on database-level.

btw: proposed small doc change. sense free +1 this:

so, safe rely on clear() in foreach, existing info partially updated?

yes.

is improve rely on clear()?

the benefit of using create() when adding records form pre-populated default values shown user. if don't care can utilize clear().

php cakephp cakephp-2.5

python - Django restframework browsable api login with ouath -



python - Django restframework browsable api login with ouath -

i have created sample api using djangorestframework worked fine , utilize browsable api without problem. added outh2 authentication mentioned on official website worked fine. can utilize next access token.

curl -x post -d "client_id=your_client_id&client_secret=your_client_secret&grant_type=password&username=your_username&password=your_password" http://localhost:8000/oauth2/access_token/

i can utilize curl browse api using access token.

but while using browsable api can't browse api due obvious reason browsable api neither getting access token nor using any. think need have login this. not getting can customise current login having utilize oauth.

web browsers don't allow set custom headers, there's no way can provide oauth token.

in general, if want utilize browsable api need allow session based (i.e. cookie based auth).

you can allow both authentication methods, perhaps restricting session auth development if that's necessary.

i hope helps.

python django django-rest-framework

How to intercept ruby on Rails (framework) warnings -



How to intercept ruby on Rails (framework) warnings -

according problem: def .. else .. end in ruby, missing ror warning, because did not there (in output)

i want prevent self stepping similar 'pitfalls' in way, show warning(s) on html-page (development), there hits eye sure.

so there way intercept warnings, illustration putting (or getting) @env or alike?

i dont know (or'who') source or improve transport layer of such warnings (rails?)

in short words: no not - not realy

because:

1st) warning not thrown how, 'happens' here : result = kernel.load path in activesupport::dependencies : load_file processed ruby command itself

2nd) warning apears, if alter source warning (rails things ...)

3rd) depends of programming environment using

but: can read (tail of the) log file of environment (rubymine or ever using), eg. little rails extention, , set warning then. not precise, improve nil

ruby-on-rails

Excel Ado sql concatenate queries -



Excel Ado sql concatenate queries -

now count if "br" in cell with

query 1 sql activeworkbook.fullname, "select " & _ " trim(`f1`), " & _ " sum(iif( trim(`f1`) null ,1,1)), " & _ " sum(iif(`f2` in ('sk','tp'),1,)), " & _ " sum(iif(`f2` in ('br'),1,)), " & _ " sum(iif(`f2` in ('pg'),1,)), " & _ " sum(iif(`f2` in ('rin'),1,)) " & _ " [sh1$] " & _ " grouping trim(`f1`) " & _ " order trim(`f1`) asc ", worksheets("sh1").range("e6"), "no", 1

but not unique count of "br" contains cell

distinct count query, if f2 contains "br" , f4 not contain "-" , not blank count f4

query 2 sql activeworkbook.fullname, "select " & _ " sum(iif(`f2` in ('br') , `f4` not in ('','-'),1,)) c " & _ " ( " & _ " select distinct `f4`, `f2` " & _ " [sh1$] ) tmp " & _ " grouping `f4` " & _ , worksheets("sh1").range("h6"), "no", 0

but how can concatenate thoose queries in 1 query? set query2 instead of query 1

" sum(iif(`f2` in ('br'),1,)), " & _ field

code:

sub sql(sourcefile variant, sqlstr string, pasterng range, yesno string, imex byte) dim con object dim rstdata object dim sdatabaserangeaddress string set con = createobject("adodb.connection") set rstdata = createobject("adodb.recordset") if imex = 1 imexx = "imex=1;" else imexx = "" con.open "provider=microsoft.ace.oledb.12.0;data source=" & sourcefile & ";extended properties = ""excel 12.0 macro;" & imexx & "hdr=" & yesno & """;" rstdata.open sqlstr, con, 1, 1, 1 pasterng.copyfromrecordset rstdata rstdata.close set rstdata = nil set con = nil end sub

sql excel vba excel-vba ado

responsive design - Keep absolute divs always on image parent container -



responsive design - Keep absolute divs always on image parent container -

im working on interactive show room. in showroom visitors can click on products lichtbox more info product.

see: http://codepen.io/xiniyo/pen/wloxe

is possible maintain dots on same position image below when rescale browser. normal width = 1140px minimum width = 960px. imag scales dots remain on absolute position.

i`ve tried % calculations didn't work either. image scales faster dots do.

with hard % calculations? or javascript. or possible calculate absolute position canter of div?

position: fixed;

this should work

responsive-design position absolute interactive

Why Activity Monitor shows different memory usage of Java then Java running itself? -



Why Activity Monitor shows different memory usage of Java then Java running itself? -

so have code:

public class testclass { public static void main(string[] args) throws interruptedexception { runtime runtime = runtime.getruntime(); arraylist<integer> integers = new arraylist<integer>(); integers.ensurecapacity(integer.max_value/5); system.out.println(runtime.totalmemory()/1000000); thread.sleep(10000); } }

which prints out around 1975 me.

but @ same time watching activity monitor in mac os , says java process using 1.62gib

why difference?

your programm shows memory of jvm of little programm. other programms utilize own jvm, own memory. special native libraries opencl not total visualized.

for memory analyse please utilize java visualvm (jdk 1.7 or higher in ./bin (installation folder of java) or http://visualvm.java.net/ ). there concrete list of running jvms , memory-usage. can heap dump , look, how much memory used object.

java memory

multithreading - Synchronizing on function parameter for multithreaded memoization -



multithreading - Synchronizing on function parameter for multithreaded memoization -

my core question is: how can implement synchronization in method on combination of object instance , method parameter?

here details of situation. i'm using next code implement memoization, adapted this answer:

/** * memoizes unary function * @param f function memoize * @tparam t argument type * @tparam r result type */ class memoized[-t, +r](f: t => r) extends (t => r) { import scala.collection.mutable private[this] val cache = mutable.map.empty[t, r] def apply(x: t): r = cache.getorelse(x, { val y = f(x) cache += ((x, y)) y }) }

in project, i'm memoizing futures deduplicate asynchronous api calls. worked fine when using for...yield map on resulting futures, created standard excecutioncontext, when upgraded scala async nicer handling of these futures. however, realized multithreading library uses allowed multiple threads come in apply, defeating memoization, because async blocks executed in parallel, entering "orelse" thunk before cache updated new future.

to work around this, set main apply function in this.synchronized block:

def apply(x: t): r = this.synchronized { cache.getorelse(x, { val y = f(x) cache += ((x, y)) y }) }

this restored memoized behavior. drawback block calls different params, @ to the lowest degree until future created. i'm wondering if there way set finer grained synchronization on combination of memoized instance , value of x parameter apply. way, calls deduplicated blocked.

as side note, i'm not sure performance critical, because synchronized block release 1 time future created , returned (i think?). if there concerns i'm not thinking of, know.

akka actors combined futures provide powerful way wrap on mutable state without blocking. here simple illustration of how utilize actor memoization:

import akka.actor._ import akka.util.timeout import akka.pattern.ask import scala.concurrent._ import scala.concurrent.duration._ class memoize(system: actorsystem) { class cacheactor(f: => future[any]) extends actor { private[this] val cache = scala.collection.mutable.map.empty[any, future[any]] def receive = { case x => sender ! cache.getorelseupdate(x, f(x)) } } def apply[k, v](f: k => future[v]): k => future[v] = { val fcast = f.asinstanceof[any => future[any]] val actorref = system.actorof(props(new cacheactor(fcast))) implicit val timeout = timeout(5.seconds) import system.dispatcher x => actorref.ask(x).asinstanceof[future[future[v]]].flatmap(identity) } }

we can utilize like:

val scheme = actorsystem() val memoize = new memoize(system) val f = memoize { x: int => println("computing " + x) scala.concurrent.future.successful { thread.sleep(1000) x + 1 } } import system.dispatcher f(5).foreach(println) f(5).foreach(println)

and "computing 5" print single time, "6" print twice.

there scary looking asinstanceof calls, type-safe.

multithreading scala asynchronous memoization thread-synchronization

Pre requisties for setting different Screen Resolution layouts in android -



Pre requisties for setting different Screen Resolution layouts in android -

i developing android app. faced problem different screen resolution, images overlapping in little size screen , looks fine in normal size screen. tried layout-small xml little screen size little images in drawable-ldpi.but doesn't work.does layout-small supported api level 13 or below or such specification?

does layout-small supported api level 13 or below or such specification?

res/layout-small/ has been supported since api level 1.

i tried layout-small xml little screen size little images in drawable-ldpi.

-ldpi low-density screens. while most -small screens -ldpi, not will.

but doesn't work

nobody can help if unwilling explain problem in greater detail. "it doesn't work" same going doctor, saying "i don't sense well", , expecting doc cure without farther info you.

android

What is the format for javascript datetime that Google Requires for charts? -



What is the format for javascript datetime that Google Requires for charts? -

i'm working google chart , i've tried many date formats , nil working. i'm ready utilize moments format feature, need google date format datetime.

thanks!

what kind of chart trying utilize google? check out has illustration code, can play around in "visualization playground"

https://developers.google.com/chart/interactive/docs/gallery/annotatedtimeline https://code.google.com/apis/ajax/playground/?type=visualization#annotated_time_line

in illustration using javascript date objects. there's section on date format (date or datetime): https://developers.google.com/chart/interactive/docs/gallery/annotatedtimeline#data_format

javascript datetime google-visualization

javascript - JQM programatically RENAMING controlgroup's legend -



javascript - JQM programatically RENAMING controlgroup's legend -

i want rename programatically text of legend id=item_30

<fieldset data-role='controlgroup'> <legend id='item_30'>js</legend> <input id ='server1' type='radio' name='serveridor' value='1' onclick=definirserver('www.rotatorsurvey.com') ><label for='server1'>www.encuesta.ws</label> <input id ='server2' type='radio' name='serveridor' value='2' onclick=definirserver('www.rotatortablet.com') ><label for='server2'>www.onlinesurvey.co</label>

i tried:

document.getelementbyid('item_30').innerhtml = 'hello guys';

but chrome dramatically chash , says: uncaught typeerror: cannot set property 'innerhtml' of null

document.getelementbyid case-sensitive. alter to:

document.getelementbyid('item_30').innerhtml = 'hello guys';

javascript jquery jquery-mobile

forms - Combobox Dependant on Checkbox -



forms - Combobox Dependant on Checkbox -

i have been able alter list (or rowsource) of combobox dependant on whether optionbox has been selected using next code:

private sub optyes_click() options end sub private sub optno_click() options end sub private sub options() select case true case optyes.value = true cmb.enabled = true cmb.rowsource = "=options!a1:a4" case optno.value = true cmb.enabled = false end select end sub

i modify combobox list limited grouping of checkboxes have been selected. if have 10 checkboxes denoting different options, , user selects 4 of them, 4 appear in combobox.

here's how it:

private sub algeria_change() options end sub private sub bangladesh_change() options end sub private sub canada_change() options end sub private sub denmark_change() options end sub private sub options() dim names variant, name variant dim old string names = array("algeria", "bangladesh", "canada", "denmark") old = cmb cmb.clear cmb.enabled = false each name in names if me.controls(name) cmb.additem me.controls(name).caption cmb.enabled = true if name = old cmb.seltext = old end if next name end sub

if need more checkboxes add together name names , phone call options when change.

forms excel vba checkbox combobox

c# - nest query returns weird results. elasticsearch -



c# - nest query returns weird results. elasticsearch -

this client code:

settings

var defaultsettings = new connectionsettings( uri: new system.uri("http://localhost:9200") ); defaultsettings.setjsonserializersettingsmodifier(s => { s.referenceloophandling = referenceloophandling.ignore; }); defaultsettings.setconnectionstatushandler(c => { if(!c.success) throw new exception(c.tostring()); }); defaultsettings.setdefaultindex("projects");

executing code

public actionresult search(string searchterm) { var result = this.searchclient.search<projectindexmodel>( descriptor: new searchdescriptor<projectindexmodel>().index("projects").alltypes().query( query: q => q.querystring(qs => qs.query(searchterm) ) )); // or /* var results = this.searchclient.search<projectindexmodel>(s => s.index("projects").type("project").query(q => q.term(f => f.problemdefinition, searchterm) || q.term(f => f.name, searchterm) || q.term(f => f.suggestedsolution, searchterm) || q.term(f => f.initiator, searchterm) ) ); */ homecoming json(result.documents.tolist()); }

indexing launched @ application start:

foreach(var project in this.dbcontext.projects) { var indexmodel = mapper.map<projectindexmodel>(project); searchclient.index(indexmodel, "projects", "project", indexmodel.id.tostring()); }

indexes nowadays in database (that's not quite same have now, schema stayed same).

what have tried:

controller action returns (default) 10 hits of 11 documents. it's searching ignored entirely, without visible errors.

fiddler gave positive result (1 hit) both {host:9200}/_search , {host:9200}/projects/project/_search post requests query:

{ "query": { "query_string": { "query": "original" } } }

what's problem?

problem not in nest. after exploring results.connectionstatus.tostring(), showed nail fiddler did, found problem in client code. overlooked sending post without {searchterm: $scope.searchterm} specified:

$http({ url: '/projects/search', method: "post", data: { searchterm: $scope.searchterm } }) .success(function(data, status, headers, config) { $scope.projects = data.documents; }).error(function(data, status, headers, config) { console.log('error: ' + data); });

c# .net json elasticsearch nest

windows store apps - Validation error:The following display name doesn't match any of your reserved names:Something -



windows store apps - Validation error:The following display name doesn't match any of your reserved names:Something -

i trying upload window app window app store,

while uploading packages of application facing next errors,

validation error: next display name doesn't match of reserved names: 9848centaur.something

validation error: publisher attribute of identity element in app manifest doesn't match publisher id, is: cn=something

the manifest file looks like

i found out errors in manifest file .

but not getting how solve since less info available

i have tried out solutions posted next links,

http://vbcity.com/blogs/xtab/archive/2013/02/14/windows-store-apps-validation-error-publisher-attribute-doesn-t-match.aspx

http://mattduffield.wordpress.com/2012/10/15/windows-8-resolving-package-upload-errors/

i next steps , still not getting rid of these validations .

glad found solution ,

i checked this link

and solution simple

right click on project in solution explorer in visual studio.

select store --> associate app store... follow dialogs come up.

thanks anyways.

windows-store-apps windows-applications windows-store microsoft-appstore

java - Android error when convert month name -



java - Android error when convert month name -

with query select month in database. cursor returns exact month, when conversion display total name appears next month. example, cursor returns 6, instead method returns getdisplayname july.

sqlitedatabase db = new databasehelper(getactivity()).getreadabledatabase(); string sql = "select distinct strftime('%m',"+table.data+") "+table.table_name; cursor c = db.rawquery(sql, null); while (c.movetonext()){ int monthnumero = (c.getint(0)); calendar ca = calendar.getinstance(); ca.set(calendar.month, monthnumero); string monthname = ca.getdisplayname (calendar.month, calendar.long, locale.getdefault()).touppercase(); result1.add(monthname); } db.close();

for example, cursor returns 6, instead method returns getdisplayname july.

yes, would. because calendar.month "logical field" 0-based. (crazy decision, but...)

basically need subtract 1 month number:

ca.set(calendar.month, monthnumero - 1);

for illustration calendar.january documented having value of 0.

java android sqlite date calendar

java - Control number of parallel Threads -



java - Control number of parallel Threads -

i have many calculations do. run parallel... if there no limit of ram. :/

because of want command number of threads working parallel.

i wrote next code:

list<thread> threadlist = new arraylist<thread>(); threadlist.add(new thread(new runnable() { @override public void run() { .... } })); threadlist.get(threadlist.size()-1).start(); if(threadlist.size() >= 5){ threadlist.remove(0).join(); }

with 1 works fine if there no multithreading. if allow 2 gets crazy , ram getting filled up.

am doing wrong?

please not seek create own thread-list. utilize existing methods , mutual ways doing this.

one proper way using threadpoolexecutor. check that. multithreading vs threadpoolexecutor

you should utilize executor allow limit number of threads used in parallel/max. example:

executorservice executor = executors.newfixedthreadpool(10); executor.submit(yourfirstthread); executor.submit(secondthread); // , on..

java multithreading

android - Find out which button was clicked from the Custom ListView -



android - Find out which button was clicked from the Custom ListView -

in application t have custom listview 2 buttons.now want when user clicks on particular button in listview async task called sends few parameters server.the parameters comming arraylist.now how come know button clicked listview , @ particular position same info should sent arraylist.

customadapter.java

public class searchjobscustomlist extends baseadapter implements view.onclicklistener { context c; arraylist<hashmap<string, string>> data; hashmap<string, string> resultp = new hashmap<string, string> (); public searchjobscustomlist(context c, arraylist<hashmap<string, string>> data) { super (); this.c = c; this.data = data; } @override public int getcount() { homecoming data.size (); } @override public object getitem(int i) { homecoming null; } @override public long getitemid(int i) { homecoming 0; } @override public view getview(int i, view view, viewgroup viewgroup) { if (view == null) { view = layoutinflater.from (c).inflate (r.layout.custom_search_jobs_lists, viewgroup, false); resultp = data.get (i); view.settag (resultp); textview jobcode = (textview) view.findviewbyid (r.id.tv_job_code); textview category = (textview) view.findviewbyid (r.id.tv_name); textview expyrs = (textview) view.findviewbyid (r.id.tv_exp_yrs); textview expmnths = (textview) view.findviewbyid (r.id.tv_exp_mnths); textview date = (textview) view.findviewbyid (r.id.tv_date); button bestcandidate = (button) view.findviewbyid (r.id.bt_best_candidates); button appliedjobs = (button) view.findviewbyid (r.id.bt_applied_jobs); bestcandidate.setonclicklistener (this); appliedjobs.setonclicklistener (this); if (resultp.get ("counts").equals (0)) { bestcandidate.setfocusable (false); bestcandidate.settext (0); } else { bestcandidate.settext (resultp.get ("counts")); } if (resultp.get ("applied").equals (0)) { appliedjobs.setfocusable (false); appliedjobs.settext (0); } else { appliedjobs.settext (resultp.get ("applied")); } jobcode.settext (resultp.get ("code")); category.settext (resultp.get ("category")); expyrs.settext (resultp.get ("minexp")); expmnths.settext (resultp.get ("maxexp")); date.settext (resultp.get ("postedon")); } homecoming view; } @override public void onclick(view view) { switch (view.getid ()){ case r.id.bt_best_candidates: bestcandidatedisplay display=new bestcandidatedisplay (); display.execute (); } } public class bestcandidatedisplay extends asynctask<string,string,string>{ @override protected string doinbackground(string... strings) { string response= httprequest.post ("https://beta135.hamarisuraksha.com/web/webservice/hsjobservice.asmx/getbestcandidates").send ("vendor_ientity_code=" + "&ijob_req_id=" + resultp.get ("reqid") + "&ijob_requestor_id=" + resultp.get ("ireqid") + "&mode=" + "ttl").body (); homecoming null; } } }

list image

try way,hope help solve problem. public class searchjobscustomlist extends baseadapter{ context context; arraylist<hashmap<string, string>> data; public searchjobscustomlist(context context, arraylist<hashmap<string, string>> data) { super (); this.context = context; this.data = data; } @override public int getcount() { homecoming data.size (); } @override public object getitem(int i) { homecoming null; } @override public long getitemid(int i) { homecoming 0; } @override public view getview(final int i, view view, viewgroup viewgroup) { viewholder holder; if (view == null) { holder = new viewholder(); view = layoutinflater.from(context).inflate(r.layout.custom_search_jobs_lists, null, false); holder.jobcode = (textview) view.findviewbyid(r.id.tv_job_code); holder.category = (textview) view.findviewbyid(r.id.tv_name); holder.expyrs = (textview) view.findviewbyid(r.id.tv_exp_yrs); holder.expmnths = (textview) view.findviewbyid(r.id.tv_exp_mnths); holder.date = (textview) view.findviewbyid(r.id.tv_date); holder.bestcandidate = (button) view.findviewbyid(r.id.bt_best_candidates); holder.appliedjobs = (button) view.findviewbyid(r.id.bt_applied_jobs); view.settag(holder); }else{ holder = (viewholder) view.gettag(); } if (data.get(i).get("counts").equals("0")) { holder.bestcandidate.setfocusable (false); holder.bestcandidate.settext (0); } else { holder.bestcandidate.settext (data.get(i).get("counts")); } if (data.get(i).get("applied").equals("0")) { holder.appliedjobs.setfocusable (false); holder.appliedjobs.settext (0); } else { holder.appliedjobs.settext (data.get(i).get ("applied")); } holder.jobcode.settext (data.get(i).get("code")); holder.category.settext (data.get(i).get("category")); holder.expyrs.settext (data.get(i).get("minexp")); holder.expmnths.settext (data.get(i).get("maxexp")); holder.date.settext (data.get(i).get("postedon")); holder.appliedjobs.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { hashmap<string,string> row = data.get(i); bestcandidatedisplay display=new bestcandidatedisplay (); display.execute(row.get("reqid"), row.get("reqid")); } }); holder.appliedjobs.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { hashmap<string,string> row = data.get(i); bestcandidatedisplay display=new bestcandidatedisplay (); display.execute(row.get("reqid"),row.get("reqid")); } }); homecoming view; } class viewholder { textview category; textview expyrs; textview expmnths; textview date; textview jobcode; button bestcandidate; button appliedjobs; } } public class bestcandidatedisplay extends asynctask<string,string,string> { @override protected string doinbackground(string... strings) { string response= httprequest.post("https://beta135.hamarisuraksha.com/web/webservice/hsjobservice.asmx/getbestcandidates").send ("vendor_ientity_code=" + "&ijob_req_id=" +strings[0]+ "&ijob_requestor_id=" +strings[1]+ "&mode=" + "ttl").body (); homecoming null; } }

android listview android-asynctask onitemclicklistener custom-lists

java - How to show PopUpWindow after it has been inflated -



java - How to show PopUpWindow after it has been inflated -

i have popupwindow needs load activity starts, uses displaymetrics of screen, other things. however, getting error "unable add together window -- token null not valid; activity running?" line welcome.showatlocation(popupview2, gravity.center, 0, 0);.

how can have popupwindow shown when resources have been retrieved? popupwindow acts splash (so can fade out instantly onclick), window must first thing user sees.

my code:

@override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); layoutinflater inflater = (layoutinflater) .getsystemservice(context.layout_inflater_service); displaymetrics displaymetrics = getresources().getdisplaymetrics(); dpwidth = displaymetrics.widthpixels / displaymetrics.density; dpheight = displaymetrics.heightpixels / displaymetrics.density; popupview2 = inflater.inflate(r.layout.start_layout, null); welcome = new popupwindow(popupview2, (int) dpwidth, (int) dpheight); welcome.setanimationstyle(r.style.animation2); welcome.showatlocation(popupview2, gravity.center, 0, 0); }

basically, there sort of "onresourcesloaded"-like thing can use? help appreciated.

when code invoked scheme not ready measure metrics

move code method :

@override public void onattachedtowindow() { // todo auto-generated method stub super.onattachedtowindow(); }

this method invoked when metrics can used because activity displayed.

java android android-popupwindow

A sample test java code which can demonstrate memory fragmentation in heap -



A sample test java code which can demonstrate memory fragmentation in heap -

i understand on how memory fragmentation can occur writing bad code in java user space.

please point out me ideas can help me understand this.

in understanding thinking like, java heap fragmentation can occur because of buggy garbage collection, of friends argued opposite.

i want understand java heap fragmentation can occur writing bad java code applications well.

nb: looking code snippets can demonstrate argument.

update:

actually jvm have in embedded device java 1.3.

thanks, sen

first of all, garbage collector jvm specific. know openjre , sun jre. garbage collectors used there compact heap during collection, heap fragmentation can not occur due design of memory management.

other algorithms memory management, got used more in past, utilize free list , did not move memory around in heap. such management schemes heap fragmentation can issue.

java heap-memory memory-fragmentation heap-fragmentation

node.js - How can get a non-trivial i18n translation to work using Sails.js? -



node.js - How can get a non-trivial i18n translation to work using Sails.js? -

using sails.js version 0.10.x , trying i18n stuff work.

i have next in config/locales/en.json

{ "countries": { "au": { "name": "australia", "fiatcurrency": "aud", "subnationaldivisions": { "nsw": "new south wales", "wa": "western australia", "vic": "victoria", "qld": "queensland", "tas": "tasmania", "sa": "south australia", "nt": "northern territory", "act": "australian capital territory" } } } }

my config/i18n.js file looks like

module.exports.i18n = { // locales supported? locales: ['en', 'es', 'fr', 'de'], objectnotation: true };

in controller trying retrieve right subnationaldivision name via

res.i18n("countries." + country + ".subnationaldivisions." + state)

but gives me "countries.au.subnationaldivisions.act", not "australian capital territory"

i've check trivial example:

given en.json file containing { "bingo" : "sparky" }, res.i18n("bingo") outputs "sparky"

but examples using objectnotation don't work despite instructions in the i18n-node documentation.

how should work?

the problem tuned out bug in sails - using older version of i18n package. found , fixed error , sent pr sails team , incorporated v 0.10.3 of sails. (at current writing sails on 0.10.5)

node.js internationalization sails.js i18n-node

select - MySQL: Selecting distinct with aggregate functions -



select - MySQL: Selecting distinct with aggregate functions -

i'm having problem selecting distinct order id orderitems table.

my orderitems table contains: orderid | itemid | orderedquantity | instockquantity | backorderquantity | isbackorderofid | id.

orderedquantity total ordered amount, instockquantity quantity available @ time of purchase , backorderquantity rest. isbackorderofid correlates id column when order item backorder of order item.

my query trying select distinct orderid of entries backorderquantity < sum(instockquantity) isbackorderofid = id. result in list if distinct order ids have remaining backorders shipped.

test data:

orderid | itemid | orderedquantity | instockquantity | backorderquantity | isbackorderofid | id 1 | 114 | 10 | 6 | 4 | 0 | 23 1 | 255 | 4 | 3 | 1 | 0 | 24 2 | 114 | 3 | 3 | 0 | 23 | 25

query:

select items1.* orderitems items1 left bring together orderitems items2 on items2.isbackorderofid = items1.id items1.backorderquantity > '0' grouping items2.isbackorderofid having sum(items2.instockquantity) < items1.backorderquantity or sum(items2.instockquantity) null`

this results in both first , sec row has same orderid. can't utilize select distinct because of utilize of aggregate functions.

any help appreciated.

select items1.orderid orderitems items1 left bring together orderitems items2 on items2.isbackorderofid = items1.id grouping items1.orderid having coalesce(sum(items2.instockquantity), 0) < sum(items1.backorderquantity)

mysql select distinct

Find replace using PowerShell get-content -



Find replace using PowerShell get-content -

i attempting mask ssn numbers random ssns in big text file. file 400m or .4 gigs.

there 17,000 instances of ssns want find , replace.

here illustration of powershell script using.

(get-content c:\trainingfile\trainingfile.txt) | foreach-object {$_ -replace "123-45-6789", "666-66-6666"} | set-content c:\trainingfile\trainingfile.txt

my problem that have 17,000 lines of code have in .ps1 file. ps1 file looks similar

(get-content c:\trainingfile\trainingfile.txt) | foreach-object {$_ -replace "123-45-6789", "666-66-6666"} | set-content c:\trainingfile\trainingfile.txt (get-content c:\trainingfile\trainingfile.txt) | foreach-object {$_ -replace "122-45-6789", "666-66-6668"} | set-content c:\trainingfile\trainingfile.txt (get-content c:\trainingfile\trainingfile.txt) | foreach-object {$_ -replace "223-45-6789", "666-66-6667"} | set-content c:\trainingfile\trainingfile.txt (get-content c:\trainingfile\trainingfile.txt) | foreach-object {$_ -replace "123-44-6789", "666-66-6669"} | set-content c:\trainingfile\trainingfile.txt

for 17,000 powershell commands in .ps1 file. 1 command per line.

i did test on 1 command , took 15 secoonds execute. doing math, 170000 x 15 seconds comes out 3 days run .ps1 script of 17,000 commands.

is there faster way this?

the reason poor performance lot of work beingness done. let's process pseudoalgorithm so,

select ssn (x) , masked ssn (x') list read rows file each file row string x if found, replace x' save rows file loop until ssns processed

so what's problem? each ssn replacement, process rows. not need masking don't. that's lot of work. if got, 100 rows , 10 replacements, going utilize 1000 steps when 100 needed. in addition, reading , saving file creates disk io. whlist that's not issue single operation, multiply io cost loop count , you'll find quite big time wasted disk waits.

for great performance, tune algorithm so,

read rows file loop through rows current row, alter x -> x' save result

why should faster? 1) read , save file once. disk io slow. 2) process each row once, work not beingness done. how perform x -> x' transform, got define more masking rule is.

edit

here's more practical resolution:

since know f(x) -> x' results, should have pre-calculated list saved disk so,

ssn, mask "123-45-6789", "666-66-6666" ... "223-45-6789", "666-66-6667"

import file hash table , work forwards stealing juicy bits ansgar's answer so,

$ssnmask = @{} $ssn = import-csv "c:\temp\ssnmasks.csv" -delimiter "," # add together x -> x' hashtable $ssn | % { if(-not $ssnmask.containskey($_.ssn)) { # it's error add together existing key, check first $ssnmask.add($_.ssn, $_.mask) } } $datatomask = get-content "c:\temp\training.txt" $datatomask | % { if ( $_ -match '(\d{3}-\d{2}-\d{4})' ) { # replace ssn look-a-like value hashtable # nb: removes ssns don't have match in hashtable $_ -replace $matches[1], $ssnmask[$matches[1]] } } | set-content "c:\temp\training2.txt"

powershell

How to get the fingerprint image from a 4000B DigitalPersona to SQL Database C#? -



How to get the fingerprint image from a 4000B DigitalPersona to SQL Database C#? -

i'm using digital persona biometrics u.are.u 4000b fingerprint reader , i'm using neurotechnology sdk. , have sample programme can fingerprint scanner don't have thought how fingerprint image neurotech database store in sql database?

from i'm getting in request, want store scanned image in sql db right? why when samples provided in neurotechnology store in "sql lite database" you. need find way link database application.

edit: database create appropriate table , stores template blob think you'd go.

c# sql biometrics

Smartbind date format and error in R -



Smartbind date format and error in R -

i'm getting error using smartbind append 2 datasets. first, i'm pretty sure error i'm getting:

> error in as.vector(x, mode) : invalid 'mode' argument

is coming date variable in both datasets. date variable in it's raw format such: month/day/year. transformed variable after importing info using as.date , format

> rs.month$xdeeddt <- as.date(rs.month$xdeeddt, "%m/%d/%y") > rs.month$deed.year <- as.numeric(format(rs.month$xdeeddt, format = "%y")) > rs.month$deed.day <- as.numeric(format(rs.month$xdeeddt, format = "%d")) > rs.month$deed.month <- as.numeric(format(rs.month$xdeeddt, format = "%m"))

the resulting date variable such:

> [1] "2014-03-01" "2014-03-13" "2014-01-09" "2013-10-09"

the transformation date applied both datasets (the format of raw info identical both datasets). when seek utilize smartbind, gtools package, append 2 datasets returns error above. removed date, month, day, , year variables both datasets , able append datasets smartbind.

any suggestions on how can append datasets date variables.....?

i came here after googling same error message during smartbind of 2 info frames. give-and-take above, while not conclusive solution, helped me move through error.

both info frames contain posixct date objects. numeric vector of unixy seconds-since-epoch, along couple of attributes provide construction needed interpret vector date object. solution strip attributes variable, perform smartbind, , restore attributes:

these.atts <- attributes(df1$date) attributes(df1$date) <- null attributes(df2$date) <- null df1 <- smartbind(df1,df2) attributes(df1$date) <- these.atts

i hope helps someone, sometime.

-andy

r date append

matlab - Using Embedded coder to generate subsystem level code? -



matlab - Using Embedded coder to generate subsystem level code? -

i want know whether embedded coder used generate subsystem level code , not whole model, model working on has multiple complex logic running on memory constrained real time system.

i want generate logic subsystem , analyze it, before proceeding others. because these systems interdependent,reducing complexity @ later stage in development hard task.

yes, believe so. if right-click on subsystem, should have alternative "generate code" or similar.

matlab simulink

debugging - Compilation failed. Unable to write to path: Getting build error -



debugging - Compilation failed. Unable to write to path: Getting build error -

i having epic issues seemingly no reason in xcode 5. did add together button hyperlink , got issue:

compilation failed. unable write path: /users/zachary/library/developer/xcode/deriveddata/chinaertranslator1.0-fiqldcleohdvjqflowczefzthkwc/build/products/debug-iphonesimulator/chinaertranslator1.0.app/base.lproj/main.storyboardc underlying errors:

after saw reddish flag, deleted code had entered, reason, buggy warning keeps showing.

any tips?

debugging build compilation xcode5

php - add_editor_style always loads old css file from my wordpress plugin -



php - add_editor_style always loads old css file from my wordpress plugin -

add_editor_style loads old css file plugin.

my code below :

function admin_add_editor_styles() { $filepath = plugins_url( 'css/style.css', __file__); add_editor_style($filepath); } add_action( 'init', 'admin_add_editor_styles' );

the css file dynamic. first time runs perfect. when add together css classes style.css so newly added classes not include editor css. if rename style.css style2.css works.

on admin panel there textarea can set custom css class , content of textarea saved style.css file.

then, should add together form of version control. like:

$filepath = plugins_url( 'css/style.css', __file__) . '?ver=' . rand(0,100); add_editor_style($filepath);

but instead of random, internal command using get_option , update_option whenever style saved in custom css editor. like:

// on editor, when saving modifications $old_value = get_option( 'my_css_version' ); $new_value = $old_value + 1; update_option( 'my_css_version', $new_value ); // on style load $version = get_option( 'my_css_version' ); $filepath = plugins_url( 'css/style.css', __file__) . '?ver=' . $version;

php wordpress plugins

paypal payflow pro cancelling recurring billings -



paypal payflow pro cancelling recurring billings -

i using payflow pro recurring payment using below code, per knowledge code homecoming profileid.

do need store profile id in database user can cancel subscription in future.

please reply useful comments .

----------------------------------------------------------------------------------------- paypalrequest = "trxtype=r" + "&tender=c" //c - credit card + "&action=a" + "&optionaltrx=a" + "&term=0" //0 - recuring never stops + "&comment1=advertisement bundle subscription (recurring)" + "&profilename=" + viewmodel.packagename + "-" + userid + "&user=" + appproperties.paypalflowuser + "&vendor=" + appproperties.paypalflowvendor + "&partner=" + appproperties.paypalflowpartner + "&pwd=" + appproperties.paypalflowpassword + "&amt=" + viewmodel.payamount + "&currency=" + appproperties.currencyid + "&acct=" + viewmodel.cardnumber //card number + "&expdate=" + viewmodel.expirationmonth + viewmodel.expirationyear.substring(2, 2) + "&start=" + datetime.now.date.tostring(appconstants.ddmmyyyy) + "&payperiod=" + getpayflowperiodvariables(viewmodel);

payflownetapi payflownetapi = new payflownetapi();

string paypalresponse = payflownetapi.submittransaction(paypalrequest,payflowutility.requestid);

yes, store profile id in database along order/customer info can lookup details in future or update status accordingly.

the next api's used manage profiles using id.

managerecurringpaymentsprofilestatus updaterecurringpaymentsprofile transactionsearch

paypal

parsing - String parser for Swift? -



parsing - String parser for Swift? -

i'm working on project draws functions on plane (similar apple's grapher utility).

i'have compiled app few months ago in obj-c, , was running clean , fast.

with swift, changed bit scheme of app, i'm still using cgmathparser, great collection of classes manipulate , evaluate strings like y=sin(x) or y=log(tan(x))

however the app slow , laggy, , i'm thinking reason hides in fact i'm mixing swift obj-c.

do know if there kind of parser optimized for swift fast enough?

the swift compiler enforces bounds checks , various other 'safety' features. if compile -ofast alternative these checks removed, typically makes app run lot faster.

parsing swift

android - math.random image re-appearing off screen -



android - math.random image re-appearing off screen -

having little issue collision , math.random sending images off screen.

so have ball hits brick , brick randomly re-locate, brick image keeps going off screen. brick rotated 90 degrees i'm not sure if effects anything. there 61px tall image @ top of screen image keeps re-locating behind , thinking - 61 added help, haven't had luck.

xrandom = math.random(display.contentwidth - brick.width) yrandom = math.random(display.contentheight - brick.height) transition.to(brick, {delay = 200, x = xrandom, y= yrandom , time=0})

as have it, xrandom between 1 , display.contentwidth - brick.width: if anchor point of brick x=0, ensures brick can't positioned far right. perhaps x anchor not @ 0, or anchor x=0 not correspond left side of image (perhaps way loaded? can't tell without seeing code).

same goes y coordinate: 0 @ top of screen , increases downward. yrandom between 1 , display.contentheight - brick.height ensure brick visible if y anchor @ y=0 , anchor top of image.

if have image @ top of screen, should limit smallest y larger image's height, ie utilize yrandom = math.random(topimageheight, display.contentheight - brick.height).

it impossible tell if part of problem due rotation without seeing code. if can post minimal illustration can run create lot easier provide more accurate answer.

android lua corona

c# - How could I access checkbox control placed in WPF datagrid columnHeaderStyle as ContentTemplate -



c# - How could I access checkbox control placed in WPF datagrid columnHeaderStyle as ContentTemplate -

i have placed checkbox command in auto-generated wpf datagrid columnheaderstyle shown below:

<datagrid.columnheaderstyle> <style targettype="datagridcolumnheader"> <setter property="contenttemplate"> <setter.value> <datatemplate> <checkbox x:name="headercheckbox" content="{binding}" /> </datatemplate> </setter.value> </setter> </style> </datagrid.columnheaderstyle>

how access checkbox in code behind? there multiple columns in datagrid, how find out (column-wise) checkbox selected or not ? please suggest.

just add together events checked , unchecked , 1 time checked event ll raised

<datagrid.columnheaderstyle> <style targettype="datagridcolumnheader"> <setter property="contenttemplate"> <setter.value> <datatemplate> <checkbox x:name="headercheckbox" content="{binding}" checked="checkboxchanged" unchecked="checkboxchanged"/> </datatemplate> </setter.value> </setter> </style> </datagrid.columnheaderstyle>

c# wpf wpfdatagrid

3d - If two plane orthogonal with each other, the transparency of the first plane is wrong -



3d - If two plane orthogonal with each other, the transparency of the first plane is wrong -

in three.js, if 2 plane orthogonal each other, transparent of 1 plane wrong.

var material = new three.meshbasicmaterial({ transparent: true, side: three.doubleside, fog: false, color: 0x00ff00, opacity: 0.3 });

jsfiddle code

if add together 3 plane, result same, there no transparent effect in first plane. jsfiddle code1

problem solved : three.js / webgl - transparent planes hiding other planes behind them

thanks @alex under

jsfiddle code

var material = new three.meshbasicmaterial({ transparent: true, side: three.doubleside, fog: false, color: 0x00ff00, opacity: 0.2, depthwrite: false, depthtest: false });

3d three.js transparent plane

java - Docx4j difference between two Word docs -



java - Docx4j difference between two Word docs -

i need check difference between 2 word docx files. iam using docx4j. @ first had alter smartxmlformatter:

public smartxmlformatter(writer w) throws ioexception { this.xml = new xmlwriternsimpl(w, false); if (this.writexmldeclaration) { this.xml.xmldecl(); this.writexmldeclaration = false; } this.xml.setprefixmapping("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w"); this.xml.setprefixmapping("http://schemas.microsoft.com/office/word/2010/wordml", "w14"); this.xml.setprefixmapping("http://schemas.microsoft.com/office/word/2012/wordml", "w15"); this.xml.setprefixmapping("http://schemas.openxmlformats.org/officedocument/2006/relationships", "r"); this.xml.setprefixmapping("http://schemas.openxmlformats.org/drawingml/2006/wordprocessingdrawing", "wp"); this.xml.setprefixmapping("http://schemas.openxmlformats.org/drawingml/2006/main", "a"); this.xml.setprefixmapping("http://schemas.openxmlformats.org/drawingml/2006/picture", "pic"); this.xml.setprefixmapping(constants.base_ns_uri, "dfx"); this.xml.setprefixmapping(constants.delete_ns_uri, "del"); this.xml.setprefixmapping(constants.insert_ns_uri, "ins"); }

after had changed code without russian letters works fine. when diff 2 docx documents russian characters next exception raises:

org.xml.sax.saxparseexception; linenumber: 1; columnnumber: 10510; präfix "w14" für attribut "w14:paraid", das mit elementtyp "w:p" verknüpft ist, ist nicht gebunden. @ com.sun.org.apache.xerces.internal.util.errorhandlerwrapper.createsaxparseexception(unknown source) @ com.sun.org.apache.xerces.internal.util.errorhandlerwrapper.fatalerror(unknown source) @ com.sun.org.apache.xerces.internal.impl.xmlerrorreporter.reporterror(unknown source) @ com.sun.org.apache.xerces.internal.impl.xmlerrorreporter.reporterror(unknown source) @ com.sun.org.apache.xerces.internal.impl.xmlerrorreporter.reporterror(unknown source) @ com.sun.org.apache.xerces.internal.impl.xmlnsdocumentscannerimpl.scanstartelement(unknown source) @ com.sun.org.apache.xerces.internal.impl.xmldocumentfragmentscannerimpl$fragmentcontentdriver.next(unknown source) @ com.sun.org.apache.xerces.internal.impl.xmldocumentscannerimpl.next(unknown source) @ com.sun.org.apache.xerces.internal.impl.xmlnsdocumentscannerimpl.next(unknown source) @ com.sun.org.apache.xerces.internal.impl.xmldocumentfragmentscannerimpl.scandocument(unknown source) @ com.sun.org.apache.xerces.internal.parsers.xml11configuration.parse(unknown source) @ com.sun.org.apache.xerces.internal.parsers.xml11configuration.parse(unknown source) @ com.sun.org.apache.xerces.internal.parsers.xmlparser.parse(unknown source) @ com.sun.org.apache.xerces.internal.parsers.abstractsaxparser.parse(unknown source) @ com.sun.org.apache.xerces.internal.jaxp.saxparserimpl$jaxpsaxparser.parse(unknown source) @ com.sun.xml.internal.bind.v2.runtime.unmarshaller.unmarshallerimpl.unmarshal0(unknown source) @ com.sun.xml.internal.bind.v2.runtime.unmarshaller.unmarshallerimpl.unmarshal(unknown source) @ javax.xml.bind.helpers.abstractunmarshallerimpl.unmarshal(unknown source) @ javax.xml.bind.helpers.abstractunmarshallerimpl.unmarshal(unknown source) @ org.docx4j.xmlutils.unmarshalstring(xmlutils.java:381) @ org.docx4j.xmlutils.unmarshalstring(xmlutils.java:361) @ docx4jdiff.comparedocumentsusingdriver.main(comparedocumentsusingdriver.java:88) exception in thread "main" javax.xml.bind.unmarshalexception - linked exception: [org.xml.sax.saxparseexception; linenumber: 1; columnnumber: 10510; präfix "w14" für attribut "w14:paraid", das mit elementtyp "w:p" verknüpft ist, ist nicht gebunden.] @ javax.xml.bind.helpers.abstractunmarshallerimpl.createunmarshalexception(unknown source) @ com.sun.xml.internal.bind.v2.runtime.unmarshaller.unmarshallerimpl.createunmarshalexception(unknown source) @ com.sun.xml.internal.bind.v2.runtime.unmarshaller.unmarshallerimpl.unmarshal0(unknown source) @ com.sun.xml.internal.bind.v2.runtime.unmarshaller.unmarshallerimpl.unmarshal(unknown source) @ javax.xml.bind.helpers.abstractunmarshallerimpl.unmarshal(unknown source) @ javax.xml.bind.helpers.abstractunmarshallerimpl.unmarshal(unknown source) @ org.docx4j.xmlutils.unmarshalstring(xmlutils.java:381) @ org.docx4j.xmlutils.unmarshalstring(xmlutils.java:361) @ docx4jdiff.comparedocumentsusingdriver.main(comparedocumentsusingdriver.java:88) caused by: org.xml.sax.saxparseexception; linenumber: 1; columnnumber: 10510; präfix "w14" für attribut "w14:paraid", das mit elementtyp "w:p" verknüpft ist, ist nicht gebunden. @ com.sun.org.apache.xerces.internal.parsers.abstractsaxparser.parse(unknown source) @ com.sun.org.apache.xerces.internal.jaxp.saxparserimpl$jaxpsaxparser.parse(unknown source) ... 7 more

so please can help me?

here maincode:

public class comparedocumentsusingdriver { public static jaxbcontext context = org.docx4j.jaxb.context.jc; /** * @param args */ public static void main(string[] args) throws exception { system.setproperty("file.encoding", "utf-8"); string newerfilepath = "b.docx"; string olderfilepath = "a.docx"; // 1. load packages wordprocessingmlpackage newerpackage = wordprocessingmlpackage .load(new java.io.file(newerfilepath)); wordprocessingmlpackage olderpackage = wordprocessingmlpackage .load(new java.io.file(olderfilepath)); body newerbody = ((document) newerpackage.getmaindocumentpart() .getjaxbelement()).getbody(); body olderbody = ((document) olderpackage.getmaindocumentpart() .getjaxbelement()).getbody(); system.out.println("differencing.."); // 2. differencing stringwriter sw = new stringwriter(); docx4jdriver.diff(xmlutils.marshaltow3cdomdocument(newerbody) .getdocumentelement(), xmlutils.marshaltow3cdomdocument(olderbody) .getdocumentelement(), sw); // signature takes reader objects appears broken // 3. result string contentstr = sw.tostring(); system.out.println("result: \n\n " + contentstr); body newbody = (body) xmlutils.unwrap(xmlutils.unmarshalstring(contentstr)); // in general case, need handle relationships. not done here! // relationshipspart rp = // newerpackage.getmaindocumentpart().getrelationshipspart(); // handlerels(pd, rp); newerpackage.setfontmapper(new identityplusmapper()); newerpackage.save(new java.io.file("compared.docx")); } /** * in general case, need handle relationships. although not * necessary in simple example, anyway purposes of * illustration. */ private static void handlerels(differencer pd, relationshipspart rp) { // since going add together rels appropriate docs beingness // compared, neatness , avoid duplication // (duplication of internal part names fatal in word, // , export xslt makes images internal, though avoid // duplicating // part ), // remove existing rels point images list<relationship> relstoremove = new arraylist<relationship>(); (relationship r : rp.getrelationships().getrelationship()) { // type="http://schemas.openxmlformats.org/officedocument/2006/relationships/image" if (r.gettype().equals(namespaces.image)) { relstoremove.add(r); } ti } (relationship r : relstoremove) { rp.removerelationship(r); } // add together rels composed list<relationship> newrels = pd.getcomposedrels(); (relationship nr : newrels) { rp.addrelationship(nr); } } }

best regards,

tim

edit:

public static void openresult(string nodename, author out) throws ioexception { // in general, need avoid writing straight author out... // since can happen before formatter output gets there // namespaces not declared: // 4 options: // 1: // openelementevent containeropen = new openelementeventnsimpl(xml1.getnamespaceuri(), rootnodename); // formatter.format(containeropen); // // attributeevent wns = new attributeeventnsimpl("http://www.w3.org/2000/xmlns/" , "w", // // "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); // // formatter.format(wns); // attributeevent late in process set mapping. // can comment out. // still have add together w: , other namespaces in // smartxmlformatter constructor. may 2.: // 2: stick known namespaces on our root element above // 3: prepare smartxmlformatter // go alternative 2 .. since clear out.append("<" + nodename + " xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"" // w: namespace + " xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\"" + " xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\"" + " xmlns:r=\"http://schemas.openxmlformats.org/officedocument/2006/relationships\"" + " xmlns:v=\"urn:schemas-microsoft-com:vml\"" + " xmlns:w14=\"http://schemas.microsoft.com/office/word/2010/wordml\"" + " xmlns:w15=\"http://schemas.microsoft.com/office/word/2012/wordml\"" + " xmlns:w10=\"urn:schemas-microsoft-com:office:word\"" + " xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingdrawing\"" + " xmlns:dfx=\"" + constants.base_ns_uri + "\"" // add together these, since smartxmlformatter writes them on first fragment + " xmlns:del=\"" + constants.delete_ns_uri + "\"" + " xmlns:ins=\"" + constants.base_ns_uri + "\"" + " >" ); }

java ms-word diff docx4j

vb.net - How to pass a parameter of a .exe made in VB .net to a javascript function -



vb.net - How to pass a parameter of a .exe made in VB .net to a javascript function -

im trying pass parameter how title says .exe app have made vb .net, app u have madem wich send letter "p" , recibe weight, when button pressed convert integer , utilize "environment.exitcode = integerval" homecoming value javascript running it.

imports scheme imports system.io.ports imports system.componentmodel public class form1 dim test string dim doublelval double dim integerval integer delegate sub settextcallback(byval [text] string) 'added prevent threading errors during receiveing of info '------------------------------------------------ private sub form1_load(sender system.object, e system.eventargs) handles mybase.load serialport1.portname = "com5" serialport.getportnames() serialport1.open() serialport1.write("p") end sub '------------------------------------------------ private sub button4_click(sender system.object, e system.eventargs) handles button4.click doublelval = cdbl(val(test)) integerval = convert.toint32(doublelval * 1000) serialport1.close() msgbox(integerval) environment.exitcode = integerval me.close() end sub private sub serialport1_datareceived(sender system.object, e system.io.ports.serialdatareceivedeventargs) handles serialport1.datareceived receivedtext(serialport1.readexisting()) end sub private sub receivedtext(byval [text] string) 'input readexisting if me.richtextbox2.invokerequired dim x new settextcallback(addressof receivedtext) me.invoke(x, new object() {(text)}) else test = trim(text) me.richtextbox2.text &= test end if end sub end class

what im trying utilize "environment.exitcode = integerval" homecoming value javascript:

<script languaje="text/javascript"> function runfile(){ var file = "c:\\users\\luisrodrigo\\desktop\\serialcom\\serialcom\\bin\\debug\\serialcom.exe"; var exeactive = new activexobject("wscript.shell"); var flag = exeactive.run(file,1,true); $s('p120_output',flag); } </script>

so javascript working on ie(i know suck request) cuz using activex, javascript expect "exitcode" , when run exe local send me weight correctly when run on web(using javascript function) returns 0.

when run vb .net in visual studio 2013 on output debug(the screen of bottom) send follow:

programme '[1068] serialcom.vshost.exe: programme trace' has exited code 0 (0x0). programme '[1068] serialcom.vshost.exe' has exited code 255 (0xff).

as can see send exit code 2 times, guess javascript function getting first returning code insted of sec one, 1 need.

so question is, how did pass variable "integerval" vb variable "flag" in javascript

thanks yor time.

javascript vb.net exe

php - Maximum number of files being uploaded by input type file -



php - Maximum number of files being uploaded by input type file -

possible duplicate: max file number can php upload @ same time

i'm trying upload multiple files using html , php

<input type="file" name="upload[]" accept="image/gif, image/jpeg, application/x-tar, application/x-zip-compressed" multiple="true">

in php when using

print count($_files['upload']);

i maximum 5 files if i've selected 20 in html. should able upload, let's say, 20 files @ time?

you may need alter in php.ini file , increment limit of max_file_uploads (it mustbe 5 in server now)

also create sure create relevant changes these parameters (if needed)

upload_max_filesize post_max_size max_input_time max_execution_time

levsahakyan solved problem.

he using

for($i=0; $i<count($_files['upload']); $i++)

and because 'upload' array , has 5 parameters (name, type, tmp_name, error , size) uploading 5 items. using right parameter -

for($i=0; $i<count($_files['upload']['name']); $i++)

php html file-upload types input

delphi - Insert DBGrid data into a multi-dimensional array -



delphi - Insert DBGrid data into a multi-dimensional array -

i have set connection delphi pgsql using adoconnection, adoquery, datasource , dbgrid nowadays results of query. database contains 2 columns of values of type double, of thousands of rows, insert two-dimensional array.however, quite new not sure how insert contents of dbgrid array. help much appreciated.

first of if there thousands of rows need assign fields variables before reading rid of unnecessary text lookup time when using fieldbyname.

i dont't have delphi @ hand should work or @ to the lowest degree help started.

uses math; procedure processarray(adataset: tdataset); var field1: tfield; field2: tfield; len: integer; a: array of array[2] of double; begin len := 0; setlength(a, 0); field1 := adataset.fieldbyname('field1'); field2 := adataset.fieldbyname('field2'); adataset.first; while not adataset.eof begin inc(len); if len > length(a) setlength(a, len + min(len, 16384)); a[len - 1][0] := field1.value; a[len - 1][1] := field2.value; adataset.next; end; setlength(a, len); // process results in array end;

what alexsc suggesting utilize tadodataset.recordcount property set size of array initially. please note if tdataset not loaded database (uses server cursor example), recordcount not contain number of records , original solution above able cope this. made correction won't grow more 16k items @ 1 time , overhead @ 16k - 1 array entries. info tdataset "lazy loading" refer dbgrid read ahead capability using ado

please find code using recordcount below:

procedure processarray(adataset: tdataset); var field1: tfield; field2: tfield; len: integer; a: array of array[2] of double; begin len := 0; setlength(a, adataset.recordcount); field1 := adataset.fieldbyname('field1'); field2 := adataset.fieldbyname('field2'); adataset.first; while not adataset.eof begin a[len][0] := field1.value; a[len][1] := field2.value; inc(len); adataset.next; end; // process results in array here end;

arrays delphi dbgrid

oracle11g - How to extract text including spaces in XMLTYPE oracle -



oracle11g - How to extract text including spaces in XMLTYPE oracle -

when using next query,

select xmlcast(xmlquery('/books/book' passing xmlcolumn returning content) clob) "book" samplexml;

against xml below,

<books> <book> <title>basics</title> <price>10</price> </book> </books>

i expect info returned as,

basics 10 , due space between title tag , cost tag, instead getting basics10

edit : this example, there may number of tags within them. want spaces included if between 2 tags

try this

select x.title || ' ' || x.price samplexml s, xmltable('/books/book' passing xmltype('<books><book> <title>basics</title> <price>10</price> </book></books>') columns title varchar2(150) path '/*/./title', cost varchar2(1000) path '/*/price') x

into xmltible set name of column samplexml table, e.g. if column named xdata transform such

select x.title || ' ' || x.price samplexml s, xmltable('/books/book' passing xmltype(s.xdata) columns title varchar2(150) path '/*/./title', cost varchar2(1000) path '/*/price') x

oracle oracle11g xquery xmltype

c# - multiple drillthrough events in one report ssrs -



c# - multiple drillthrough events in one report ssrs -

i have main study linked 2 subreports, problem can access 1 of reports using drillthrough event, when seek utilize if statement no longer recognize info source, used "go url" action link other report. solved problem not wanted.

you can utilize go report alternative selecting required parameters if any.

c# asp.net reporting-services report drillthrough

python - Filtering top-level categories in hierarchical Pandas Dataframe using lower-level data -



python - Filtering top-level categories in hierarchical Pandas Dataframe using lower-level data -

i have pandas dataframe contains big number of categories each have features , each of have own subfeatures grouped pairs. simple version looks following:

0 1 ... categories features subfeatures cat1 feature1 subfeature1 -0.224487 -0.227524 subfeature2 -0.591399 -0.799228 feature2 subfeature1 1.190110 -1.365895 ... subfeature2 0.720956 -1.325562 cat2 feature1 subfeature1 1.856932 nan subfeature2 -1.354258 -0.740473 feature2 subfeature1 0.234075 -1.362235 ... subfeature2 0.013875 1.309564 cat3 feature1 subfeature1 nan nan subfeature2 -1.260408 1.559721 ... feature2 subfeature1 0.419246 0.084386 subfeature2 0.969270 1.493417 ... ... ...

it can generated using next code:

import pandas pd import numpy np np.random.seed(seed=90) results = np.random.randn(3,2,2,2) results[2,0,0,:] = np.nan results[1,0,0,1] = np.nan results = results.reshape((-1,2)) index = pd.multiindex.from_product([["cat1", "cat2", "cat3"], ["feature1", "feature2"], ["subfeature1", "subfeature2"]], names=["categories", "features", "subfeatures"]) df = pd.dataframe(results, index=index)

now retrieve top-level categories (cat1 etc) have difference between subfeature1 , subfeature2 in same column (0 or 1) above threshold.

for example: if threshold 1 expect cat2 , cat3 returned because difference between subfeature1 , subfeature2 in column 0 1.856932 - (-1.354258), 3.21119 > threshold = 1 feature1 in cat2. similarly, difference between subfeature1 , subfeature2 in column 1 in cat3, feature2 1.493417 - 0.084386 = 1.409031 > 1. on other hand, cat1 not returned because none differences between subfeature pairs greater 1. nan values invalidate pair , ignored.

what have tried

i have managed implement iterative approach, sense not taking advantage of pandas' total capabilities , performance lacking:

for cat in df.index.levels[0]: feature in df.index.levels[1]: df2 = df.xs((cat, feature)) diffs = abs(df2.loc['subfeature1'] - df2.loc['subfeature2']) if max(diffs) > threshold , cat not in results: results.append(cat)

yielding:

['cat2', 'cat3']

how go implementing using pandas' built-in vectorized abilities?

edit: using jeff's reply below, noticed funky:

def f(x): = max(abs(x.xs('subfeature1',level='subfeatures')-x.xs('subfeature2',level='subfeatures'))) print homecoming > 1 result = df.groupby(level=['categories','features']).filter(f) print(result)

gives:

0.366912262765 0.571703714569 1 0.469153603312 0.0403331129905 3.2111900125 <------------------------------------------------ nan 0.220200012413 2.67179897269 <--------------------------------------------------- nan nan 0.550023734074 1.40903094796 <-----------------------------------------------------!!!!!!!!!!! 0 1 categories features subfeatures cat2 feature1 subfeature1 1.856932 nan subfeature2 -1.354258 -0.740473

i've highlighted places algorithm should include category based on score. yet, doesn't cat3. nans have it?

groupby top-2 levels. utilize filter homecoming max difference of features want (threshold here 0)

in [41]: df.groupby(level=['categories','features']).filter(lambda x: (x.xs('subfeature1',level='subfeatures')-x.xs('subfeature2',level='subfeatures')).max()>0) out[41]: 0 1 categories features subfeatures cat1 feature1 subfeature1 -0.224487 -0.227524 subfeature2 -0.591399 -0.799228 feature2 subfeature1 1.190110 -1.365895 subfeature2 0.720956 -1.325562 cat2 feature1 subfeature1 1.856932 nan subfeature2 -1.354258 -0.740473 feature2 subfeature1 0.234075 -1.362235 subfeature2 0.013875 1.309564

a useful debugging aid to this:

def f(x): print x homecoming (x.xs(......)) # e.g. filter above df.groupby(.....).filter(f)

python pandas hierarchical-data