Friday, 15 February 2013

XCode force touch -



XCode force touch -

how can forcefulness xcode (4.5.x) forcefulness "touch" on file (foo.m) every time nail build button.

i file compiled every time though nil has changed (it contains date & time macro in case curious).

that's poor solution. improve run build script generate source file containing current date , time. can compile , link generated source file final binary.

this create easier manage git, foo.m won't seen alter though no functional changes have occurred.

xcode touch

Using session object in Django unit test -



Using session object in Django unit test -

i writing login view , add together unit test view. view looks this:

def login(request): if request.post: usrname = request.post.get('username') password = request.post.get('password') user = authenticate(username=usrname, password=password) if user not none: auth_login(request, user) homecoming redirect('/core/home/') else: context = {'error_message': "invalid username or password"} homecoming render(request, 'core/login.html', context) else: c = {} c.update(csrf(request)) homecoming render_to_response('core/login.html',c) def home(request): if request.user.is_authenticated(): context = {'user' : request.user} homecoming render(request, 'core/home.html', context) else: homecoming render(request, 'core/login.html')

and unit test looks this:

class coreviewtests(testcase): def setup(self): self.factory = requestfactory() def test_login_view_with_valid_user(self): uf = userfactory() user = uf.make_user("validuser1", "12345", "user@abc.com") self.assertequal(user.username, "validuser1") request = self.factory.post('/core/login', {"username": "validuser1", "password": "12345"}) response = login(request) self.assertequal(response.status_code, 200)

the unit test crash because cannot find session object. follow couple tutorial on websites defining dummy session dictionary doesn't help.

can shed lite me how write unit test view need deal session object?

thanks.

from documentation requestfactory object:

it not back upwards middleware. session , authentication attributes must supplied test if required view function properly.

you seek manually setting request.session dictionary appropriate stuff in it, say. might turn out easier utilize old-fashioned django test client though.

django session

java - Trouble with my algorithm to solve a boggle board -



java - Trouble with my algorithm to solve a boggle board -

so i'm relatively new java (i'm taking ap java @ school currently) , trying develop recursive algorithm solve n*n board , sense close not quite there yet. have written out traverse dictionary find if letters sending words or not etc. algorithm have starting letter (n,p) in array, send cordinates method go in every direction find possible combinations. 1 time combinations starting (n,p) have been found, increment p until got end of row increment n , start p 0 again. (i go through half letters because combinations same backwards , forwards)

the part have problem recursive sequence because 1 time go on position on board want mark create sure never go on 1 time again rest of sequence. doesn't work , wondering if tell me why/help me write improve algorithm. in advance

public void allletters(int n, int p, int x, int y,string word, string myletteres[][]){ int temp=0; int startletter =(int)(math.pow(myletteres.length,2)); while(temp<startletter)//runs through every letter { if(temp==0) getpaths(p, n,x,y,word, myletteres); else if(temp%(myletteres.length-1)==temp){ getpaths(p, n+1,x,y,word, myletteres); } else { getpaths(p+1, 0,x,y,word, myletteres); } if(temp==(startletter/2-1)){ temp=startletter; } temp++; } } public void getpaths(int p, int n, int x, int y,string word, string myletteres[][]){ if( x ==p-1 && y == n-1){//reach (n,p) point system.out.print(""); }else if( x >= myletteres.length || y >= myletteres.length||x < 0 || y < 0){//out of bounds return; }else { if(x+1<myletteres.length&&!myletteres[x+1][y].equals("0")){//up{ word=word+""+myletteres[x+1][y]; check(word);//function checks if word reverse(word);//checks word backwards (for efficenicy) myletteres[x+1][y]="0";//marking i've used position system.out.print("1");//debugging purposes getpaths(n,p, x +1, y,word , myletteres); } if(x-1>0&&!myletteres[x-1][y].equals("0")){//down word=word+""+myletteres[x-1][y]; check(word); reverse(word); myletteres[x-1][y]="0"; system.out.print("2"); getpaths(n,p, x -1, y ,word, myletteres); } if(y+1<myletteres.length&&!myletteres[x][y+1].equals("0")){//right word=word+""+myletteres[x][y+1]; check(word); reverse(word); myletteres[x][y+1]="0"; system.out.print("3"); getpaths(n, p,x , y +1,word, myletteres); } if(y-1>0&&!myletteres[x][y-1].equals("0")){//left word=word+""+myletteres[x][y-1]; check(word); reverse(word); myletteres[x][y-1]="0"; system.out.print("4"); getpaths(n,p, x , y -1,word, myletteres); } if(x+1<myletteres.length&&y+1<myletteres.length&&!myletteres[x+1][y+1].equals("0")){//right, word=word+""+myletteres[x+1][y+1]; check(word); reverse(word); myletteres[x+1][y+1]="0"; system.out.print("5"); getpaths(n,p, x +1, y +1,word, myletteres); } if(x-1>0&&y-1>0&&!myletteres[x-1][y-1].equals("0")){//down, left word=word+""+myletteres[x-1][y-1]; check(word); reverse(word); myletteres[x-1][y-1]="0"; system.out.print("6"); getpaths(n,p, x-1 , y -1,word, myletteres); } if(x-1>0&&y+1<myletteres.length&&!myletteres[x-1][y+1].equals("0")){//down, right word=word+""+myletteres[x-1][y+1]; check(word); reverse(word); myletteres[x-1][y+1]="0"; system.out.print("7"); getpaths(n,p, x+1, y-1, word,myletteres); } if(x+1<myletteres.length&&y-1>0&&!myletteres[x+1][y-1].equals("0")){//up, left word=word+""+myletteres[x+1][y-1]; check(word); reverse(word); myletteres[x+1][y-1]="0"; system.out.print("8"); getpaths(n, p,x-1 , y +1, word,myletteres); } } }

you write 0's myletteres maintain recursion looping on itself. 1 time recursive phone call has returned, need restore original letter in position. otherwise search can @ each position once, on branches tries.

(also, simplify code lot looping through list of (x, y) offsets rather having separate if statement each one)

edit:

int[][] offsets = { {-1, -1}, {0, -1}, {1, -1}, {-1, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1} }; for(int[] off : offsets) { nx = x + off[0]; ny = y + off[1]; if(nx < 0 || ny < 0 || nx >= myletteres.length || ny >= myletteres[nx].length) { continue; } string letter = myletteres[nx][ny]; if(letter.equals("0")) { continue; } myletteres[nx][ny] = "0"; check(word + letter); reverse(word + letter); getpaths(n,p, nx, ny, word + letter, myletteres); myletteres[nx][ny] = letter; }

java array-algorithms

asp.net - Integrate SVN with Visual Studio 2003 -



asp.net - Integrate SVN with Visual Studio 2003 -

i trying find free tool not visualsvn(i know visualsvn integrates visual studio 2003/2005/2008/2010....) integrate sub version/tortoisesvn visual studio 2003. there tool integrates visual studio 2005/2008/2010 svn, given in hyperlink here -> http://garrys-brain.blogspot.ca/2007/07/tortoisesvn-and-visual-studio.html not integrate visual studio 2003.

agent svn ms-scci subversion plug-in should work vs 2003.

asp.net visual-studio svn visualsvn

Local variables, "dead code" and 2D arrays problems in Java -



Local variables, "dead code" and 2D arrays problems in Java -

i'm having few problems while developing next code in java:

setpos(x, y); (int = 0; x < size; i++) { (int j = 0; y < size; j++) { if (board[x][y] == 'k') { system.out.println("you've found key! congrats!"); homecoming true; }

eclipse notice me i , j, local variables, they're not used : the value of local variable not used . if alter i , write x instead, tells me i'm repeating variable.

j++ tagged dead code ?

also, have search concrete type of element on diagonal of bidimensional array, i've been trying 2 loops, above, no result yet.

hope can help me, in advance!

eclipse notice me i , j, local variables, they're not used

that's because you're not using them. you've assigned them values, , you've later incremented (added to) values, you've never used them anything.

j++ tagged "dead code" (?)

for same reason, code increments value of j, j never used, code nothing. "dead code" refers code has no purpose or never run.

your loops don't create lot of sense. instance:

for (int = 0; x < size; i++) {

normally for loop, command variable (i in case) should appear in all three of parts of for statement (the initializer, test, , increment), this:

for (int = 0; < size; i++) { // alter here -^

but you're not doing that, you're using i in initializer , increment, never in test (x < size). same true of loop j.

similarly, unless there's changing value of x, y, and/or size, loops either never run (because x or y >= size), run once (because happens board[x][u] == 'k'), or they'll run forever (because x or y < size , since nil changes that, maintain looping...).

java arrays local

mono - Portable Class Library in Monodevelop:incompatible target framework -



mono - Portable Class Library in Monodevelop:incompatible target framework -

i error when trying compile portable class library mono project.

c:\program files (x86)\mono-2.10.9\lib\mono\xbuild\microsoft\portable\v4.0\microsoft.portable.csharp.targets: project file not imported, beingness imported portabletest.csproj: imported project: "c:\program files (x86)\mono-2.10.9\lib\mono\xbuild\microsoft\portable\v4.0\microsoft.portable.csharp.targets" not exist. (portabletest)

i utilize modified 3.1.1 version of monodevelop supporting portable class library , think working before reinstall mono. suppose folder has been deleted.

is there easy way able compile portable library in monodevelop again?

thanks in advance help.

try targeting scheme (microsoft) .net framework instead of mono .net framework.

mono monodevelop

c# - Deserialization with options -



c# - Deserialization with options -

i achieving serialization of collection file. results how expect

<persons> <person> <identity>1234</identity> <name>asd</name> </person> <person> <identity>12345</identity> <name>asdd</name> </person> </persons>

now, don't want deserialize whole collection want deserialize object file specific options. example,

object getpersonwithidentity(int identity ) { // here } object asd = getpersonwithidentity(1234); // expected person identity "1234" , name "asd"

is reasonable deserialize whole collection , find specific object , homecoming it, or there other solution this?

xml not seekable @ to the lowest degree have read forwards till find first match. framework not back upwards automatically have manually using xmlreader laborious.

if file little and/or performance not issue, deserialize , done it.

if dataset big i'd consider moving more scalable format embedded sql database. sql databases have capability inherently.

c# deserialization

iphone - self.layer renderInContext:context in drawRect method gives Bad Access in ipad but not in simulator -



iphone - self.layer renderInContext:context in drawRect method gives Bad Access in ipad but not in simulator -

i working in app , in video recording. capture images , create video code follows

- (void) drawrect:(cgrect)rect { nsdate* start = [nsdate date]; cgcontextref context = [self createbitmapcontextofsize:self.frame.size]; nslog(@"context value %@",context); [self.layer renderincontext:context]; cgimageref cgimage = cgbitmapcontextcreateimage(context); uiimage* background = [uiimage imagewithcgimage: cgimage]; cgimagerelease(cgimage); self.currentscreen = background; if (_recording) { float milliselapsed = [[nsdate date] timeintervalsincedate:startedat] * 1000.0; [self writevideoframeattime:cmtimemake((int)milliselapsed, 1000)]; } float processingseconds = [[nsdate date] timeintervalsincedate:start]; delayremaining = (1.0 / self.framerate) - processingseconds; [self performselectorinbackground:@selector(setneedsdisplay) withobject:nil]; }

now problem method called recursively , when stop recording gives me exc_bad_access.

it works fine in simulatoor bot crash in device, how can solve issue?

you shouldn’t doing in drawrect:, reason override drawrect: custom drawing (which not). shouldn’t phone call setneedsdisplay on background thread, gui method can called main thread. depending on how createbitmapcontextofsize: method , environment might need release bitmap context object.

iphone ios objective-c xcode

html - Controlling ActiveX Control via Javascript -



html - Controlling ActiveX Control via Javascript -

i trying utilize software wonderware via activex. have gotten object appear, want pass parameters , eliminate having setup object everytime. there 2 versions of command activex , .net. haven't gotten .net command work @ all, can activex 1 / not parameters.

here manual says it:

the aahistclienttrend command allows run wonderware historian client trend programme (or functional subset) within wonderware intouch hmi software or .net container visual basic .net or net explorer.

the html code have:

<html> <head> <body> <object id="atrend1" classid="clsid:e08609f1-58cc-11d3-b1cf-00105aa45077" viewastext="" height="100%" width="100%" /> </body> </head> </html>

i seek pass parameter via:

<script language="javascript"> document.atrend1.tagpickervisible = false; </script>

and crashes net explorer.

edit : ideas?

i figured out way it. not sure it's way, works.

<html> <head> <script> function fxntrend() { atrend1.toolbarvisible = false; atrend1.tagpickervisible = false; atrend1.realtimemode = true; atrend1.timebarvisible = false; atrend1.gridvisible = false; } fxntrend(); </script> <body onload="fxntrend()"> <object id="atrend1" classid="clsid:e08609f1-58cc-11d3-b1cf-00105aa45077" viewastext="" height="100%" width="100%" /> </body> </head> </html>

javascript html activex wonderware

How to curl file to hadoop through Hoop using PHP -



How to curl file to hadoop through Hoop using PHP -

i want curl big file hoop using php. if normal php file upload there's headers prepended file.

when seek this:

$url = http://hoop:14000/filename?op=create&user.name=root $ch = curl_init(); curl_setopt($ch, curlopt_url, $url); curl_setopt($ch, curlopt_binarytransfer, true); curl_setopt($ch, curlopt_returntransfer, 1); curl_setopt($ch, curlopt_post, 1); curl_setopt($ch, curlopt_binarytransfer, true); curl_setopt($ch, curlopt_postfields, array("file" => "@" . $this->filepath)); curl_setopt($ch, curlopt_httpheader, array('content-type: application/octet-stream', 'expect:')); $content = curl_exec($ch);

the file on hoop have these headers:

------------------------------f0f063939ed8 content-disposition: form-data; name="file"; filename="phpbsa4ty" content-type: application/octet-stream {binary info here........}

i'm guessing needs raw post data. can work this:

$url = http://hoop:14000/filename?op=create&user.name=root $filedata = file_get_contents($this->filepath); $ch = curl_init(); curl_setopt($ch, curlopt_url, $url); curl_setopt($ch, curlopt_binarytransfer, true); curl_setopt($ch, curlopt_returntransfer, 1); curl_setopt($ch, curlopt_post, 1); curl_setopt($ch, curlopt_binarytransfer, true); curl_setopt($ch, curlopt_postfields, $filedata); curl_setopt($ch, curlopt_httpheader, array('content-type: application/octet-stream', 'expect:')); $content = curl_exec($ch);

but big files cause memory errors:

php fatal error: allowed memory size of 33554432 bytes exhausted (tried allocate 8388608 bytes)

is there way post raw files without loading file memory?

i can on command line using instructions hoop documentation

curl -x post -c ~/.hoopauth "http://<hoop_host>:14000/<path>?op=create[&<option>]*" \ --data-binary @data.txt --header "content-type: application/octet-stream"

from http://cloudera.github.com/hoop/docs/latest/httprestapi.html

php curl hadoop hdfs

linux - shell script terminating program but not the script itself -



linux - shell script terminating program but not the script itself -

i using shell script automatically search network access points, , in airodump utilize ctrl + c stop search, , wanting cancel search maintain shell script running. since wanting user input after done searching wifi networks. tried utilize trap, , stops airodump, , script.

i wanting stop airodump wifi search , move onto shell script of user input.

it's not exclusively clear me, believe wanting user able interactively stop search via ctrl-c , prompted input. should that:

#!/bin/sh trap 'test "$airo" && kill -2 $airo' 2 airodump ... & airo=$! wait unset airo # commands here execute after user hits ctrl-c terminate search

linux shell trap

symfony2 - Symfony 2 form associated entity with relation to the parent fails to save -



symfony2 - Symfony 2 form associated entity with relation to the parent fails to save -

i trying follow tutorial have many many relation bring together table form entity: http://www.prowebdev.us/2012/07/symfnoy2-many-to-many-relation-with.html

in case have next classes:

issue / user / assigneduser

the assigneduser entity bring together table between issue , user.

in form:

$builder->add('assigned', 'entity', array( 'required' => false, 'class' => 'mybundle:user', 'expanded' => true, 'multiple' => true ));

my issue class. omited parts namespaces.

(...)

/** * * @orm\onetomany(targetentity="(...)assigneduser", mappedby="issue",cascade={"persist", "remove"}) * */ protected $assignedusers; /** * needed form renders users select. */ protected $assigned; public function getassigned() { $assigned = new arraycollection(); foreach($this->assignedusers $value) { $assigned[] = $value->getuser(); } homecoming $assigned; } // of import public function setassigned($users) { foreach($users $user) { $au = new issueassigneduser(); $au->setissue($this); $au->setuser($user); $this->addassigneduser($au); } } /** * build */ public function __construct(){ $this->assignedusers = new arraycollection(); $this->assigned = new arraycollection(); } public function addassigneduser($assigneduser) { $this->assignedusers[] = $assigneduser; homecoming $this; }

the problem lies setassigned method.

$au->setissue($this);

my issueassigneduser:

/** * issueassigneduser * * @orm\table(name="sup_issue_assigned_user") * @orm\entity(repositoryclass="ueb\support\bundle\issuebundle\entity\repository\issueassigneduserrepository") */ class issueassigneduser { /** * @var integer * * @orm\manytoone(targetentity="...\issue",inversedby="assignedusers",cascade={"persist"}) * @orm\joincolumn(name="issue_id", referencedcolumnname="id",nullable=false,ondelete="cascade") * @orm\id */ private $issue; /** * @var \ueb\accounts\bundle\userbundle\entity\user * * @orm\manytoone(targetentity="...\user") * @orm\joincolumn(name="user_id", referencedcolumnname="id",nullable=false,ondelete="cascade") * @orm\id */ private $user; /** * @var \datetime * * @orm\column(name="created_at", type="datetime") * @gedmo\timestampable(on="create") */ private $createdat; /** * @var \datetime * * @orm\column(name="updated_at", type="datetime") * @gedmo\timestampable */ private $updatedat;

i error:

entity of type ... issueassigneduser has identity through foreign entity issue, entity has no identity itself. have phone call entitymanager#persist() on related entity , create sure identifier generated before trying persist

is not suposed doctrine persist issue entity first , them seek persist associated entities?

what doing wrong?

you have persist issue database before calling setassignedusers() on issue.

$em->persist($issue);

forms symfony2 doctrine2 associations

c++ - String gets cut off during RC4 decryption -



c++ - String gets cut off during RC4 decryption -

edit:

it seems error lies within readresource() function. when printing output before decryption code cutting off.

old text:

i storing rc4 encrypted string within application's resource. because rc4 encryption has maximum string size split big string substrings , split them delimiter.

now, app supposed read resource. split them using delimiter, decrypt each substring , combine them again.

when trying 'testestestestest........test' string works, if utilize illustration 'lorem ipsum dolor sit down amet, consetetur sadipscing elitr' cuts of part of string during decryption.

this rc4-code:

char* rc4_crypt( char *s, size_t datalen, char *d, size_t keylen) { unsigned char s[size]; char *data = s; char *key = d; int i,j,k,tmp; for(i = 0; < size;i++) s[i] = i; for(j = = 0; < size;i++) { j = (j + s[i] + key[i%keylen]) % size; tmp = s[i]; s[i] = s[j]; s[j] = tmp; } for(i = j = k = 0; k < datalen;k++) { = (i + 1) % size; j = (j + s[i]) % size; tmp = s[i]; s[i] = s[j]; s[j] = tmp; tmp = s[(s[i] + s[j]) % size]; data[k] ^= tmp; } homecoming data; }

this code handling splitting:

std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while(std::getline(ss, item, delim)) { elems.push_back(item); } homecoming elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; homecoming split(s, delim, elems); } void print (std::string &elem) { //this because somehow 'ul' still included //as element, sorts out if(elem.length() !=2) { cout << elem << '\n'; char *output = rc4_crypt((char *)elem.c_str(), strlen(elem.c_str()),key, strlen(key)); cout << output << '\n'; finalstring = finalstring + output; } }

and main function:

int main() { char *output; output = readresource(); std::string stringy; stringy = output; std::vector<std::string> splitted = split(stringy,'+ul+'); for_each (splitted.begin(), splitted.end(), print); cout << endl; cout << finalstring << '\n'; }

does have thought why happening?

edit:

i adding rc4 function utilize in vb.net encrypt code. maybe can help:

private shared function proper_rc4(byval input byte(), byval key byte()) byte() dim i, j, swap uinteger dim s uinteger() = new uinteger(255) {} dim output byte() = new byte(input.length - 1) {} = 0 255 s(i) = next = 0 255 j = (j + key(i mod key.length) + s(i)) , 255 swap = s(i) 'swapping of s(i) , s(j) s(i) = s(j) s(j) = swap next = 0 : j = 0 c = 0 output.length - 1 = (i + 1) , 255 j = (j + s(i)) , 255 swap = s(i) 'swapping of s(i) , s(j) s(i) = s(j) s(j) = swap output(c) = input(c) xor s((s(i) + s(j)) , 255) next homecoming output end function

edit2:

here readresource() function:

char *readresource() { tchar buffer[max_path]; getmodulefilename(null,buffer,sizeof(buffer)); hmodule moduleh = getmodulehandle(buffer); hrsrc res = findresource(moduleh, l"1", l"data"); hglobal globalh = loadresource(moduleh,res); void * ptr = lockresource(globalh); size = sizeofresource(moduleh,res); char *m_presourcebuffer = new char[size]; if (m_presourcebuffer != null) { memcpy(m_presourcebuffer, ptr, size); } homecoming m_presourcebuffer; }

if understand correctly, readresource reading encrypted data. if so, info have 0 in middle of it. 0 treated null terminator when assigned string. decrypt until first zero. first illustration did not end 0 in encrypted result, sec illustration did.

but others have pointed out in comments, there should no need rc4 break pieces. should able encrypt in 1 call. , in reality, bad (insecure) maintain encrypting same key while resetting s-box each time. result vulnerable. described in wikipedia article.

if encrypt single stream, logic becomes much simpler deal with. when read info (e.g., via readresource) need length. function need homecoming length. utilize length in phone call decrypt data.

c++ encryption

solr - about search using Lucene? -



solr - about search using Lucene? -

i using lucene based search engine.

for example, have field "name": "blue sky"

i can search utilize bluish or sky, not blu. think blu part of blue, why cannot search blu?

you need utilize wildcard (blu*) or fuzzy searches (blu~). more info available here.

solr lucene elasticsearch

ios - How to determine closest CGPoint with an angle and another CGPoint -



ios - How to determine closest CGPoint with an angle and another CGPoint -

i calculate angle between 2 cgpoints :

//calculate radian , grade cgpoint diff = ccpsub(center, location);//return ccp(v1.x - v2.x, v1.y - v2.y); float rads = atan2f( diff.y, diff.x); float degs = -cc_radians_to_degrees(rads); nslog(@"rad %.2f degs %.2f",rads,degs);

now in function have pre known cgpoint , grade of above function, want calculate closest point satisfies degree.

i thinking maybe below code help me in below code start point , rotation point known, in situation know start point.

-(void) rotatearoundpoint:(cgpoint)rotationpoint angle:(cgfloat)angle { cgfloat x = cos(cc_degrees_to_radians(-angle)) * (self.position.x-rotationpoint.x) - sin(cc_degrees_to_radians(-angle)) * (self.position.y-rotationpoint.y) + rotationpoint.x; cgfloat y = sin(cc_degrees_to_radians(-angle)) * (self.position.x-rotationpoint.x) + cos(cc_degrees_to_radians(-angle)) * (self.position.y-rotationpoint.y) + rotationpoint.y;

lets have point 800,600 , have grade of 70, how can calculate closest point point , degree?

edit:::

normally in game sprites moved button hence rotation,movement,speed etc handled when button pressed [sprite movetopregivenpostion:cgpoint]

but compass added , when user take angle on compass need move sprite in direction of grade on compass, since [sprite movetopregivenpostion:cgpoint] handles rotation , other stuff want determine cgpoint should send movetopregivenpostion function.

as @trumpetlicks said cant find closest point that, guess understood want , function -(void) rotatearoundpoint:(cgpoint)rotationpoint angle:(cgfloat)angle trying utilize fine accomplish want.

all need take float radius.

you know current point , lets radius 1, can calculate previous point without degree, assuming 0 degrees left of point , lets point 200,200 1 radius 0 grade previous point automatically becomes 199,200. have reference point calculate point want move sprite:

//choose feasable radius float radius = 0.5; //position_ preknown position said //find point roate //position_.x-radius 0 degrees of current point cgfloat x = cos(rads) * ((position_.x-radius)-position_.x) - sin(rads) * ((position_.y)-position_.y) + position_.x; cgfloat y = sin(rads) * ((position_.x-radius)-position_.x) + cos(rads) * ((position_.y)-position_.y) + position_.y; //get new point cgpoint newlocation = ccp(x, y);

ios objective-c cocos2d-iphone angle

facebook - Like Box works for users logged into FB - but not otherwise -



facebook - Like Box works for users logged into FB - but not otherwise -

i have weird problem cannot fb box show in chrome, chrome incognito / firefox / opera doesn't render @ all. shows fine if log in facebook first.

inside <head>:

<script>(function(d, s, id) { var js, fjs = d.getelementsbytagname(s)[0]; if (d.getelementbyid(id)) return; js = d.createelement(s); js.id = id; js.src = "//connect.facebook.net/en_us/all.js#xfbml=1&appid=409074972499544"; fjs.parentnode.insertbefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script>

after opening tag of <body>

<div id="fb-root"></div>

located @ want box rendered at:

<div style="padding-bottom: 10px;"><fb:like-box href="https://www.facebook.com/leagueoflegendsfinland" width="250" show_faces="false" colorscheme="dark" stream="false" header="false"></fb:like-box></div>

my fb app:

so experienced dev there point out mistake? :) tried html5/iframe versions it's same deal. tried moving code right before body closes.

oh, if wants straight go inspect page: http://leagueoflegends.fi

check page dat if there restrictions.it happens because of restrictions made. age restrictions,country that. remove restrictions,it works fine. utilize iframe fb box or javascript.it wrks fine.

facebook

actionscript 3 - Set an item flex Combo box -



actionscript 3 - Set an item flex Combo box -

i have 1 combo box(flex 4),i want set item.

var tempobject:object; tempobject.clientname="raju"; clientlist.selecteditem = tempobject;

is correct? .but shows error

*typeerror: error #1009: cannot access property or method of null object reference.*

my combo box:

<s:combobox id="clientlist" width="14%" height="85%"change="clientlist_changehandler(event)" dataprovider="{clientlistforcombo}" labelfield="clientname" prompt="select one"/>

why not init tempobject?

try this:

var tempobject:object = new object(); tempobject.clientname="raju"; clientlist.selecteditem = tempobject;

actionscript-3 flex actionscript air

ekeventkit - Get events from all the EKCalendar -



ekeventkit - Get events from all the EKCalendar -

i want events calendars (home,work,calendar , birthday). getting events defaultcalendar, cannot fetch events birthday calendar. help great.

this answer might help you:

nsdate* enddate = [nsdate datewithtimeintervalsincenow:[[nsdate distantfuture] timeintervalsincereferencedate]]; nsarray *calendararray = [nsarray arraywithobject:cal]; nspredicate *fetchcalendarevents = [eventstore predicateforeventswithstartdate:[nsdate date] enddate:enddate calendars:calendararray]; nsarray *eventlist = [eventstore eventsmatchingpredicate:fetchcalendarevents]; for(int i=0; < eventlist.count; i++){ nslog(@"event title:%@", [[eventlist objectatindex:i] title]); }

ekeventkit

ruby - Lazy loading: How do I do Model.include(:name) when foreign key has a different name than the model? -



ruby - Lazy loading: How do I do Model.include(:name) when foreign key has a different name than the model? -

i want lazy load user target objects in active record this:

target.include(:user)

but problem user_id foreign key named 'targeted_user_id', not 'user_id'. how can accomplish this?

class target < activerecord::base belongs_to :user, foreign_key: 'targeted_user_id' end target.includes(:user)

good explanation here

ruby ruby-on-rails-3

CSS select with rounded corner and overlapping background color -



CSS select with rounded corner and overlapping background color -

i applying border radius on select element has background color. instead of next curvers of border, background color overlaps curves , appears in square box. can't figure out css property must utilize solve issue.

background-color: #ff0; border-radius: 24px; border: 4px solid #f09;

here jsfiddle: http://jsfiddle.net/jsgnr/

thanks help

my feeling is, work in every mutual browser, have rebuild select js ... unfortuneatly styling selects css divbox still not possible expect. in latest firefox code looks nice in browser, because firefox decided allow border overlap select, in latest opera border underneath select, because decided to.

you see on options , seek style them via css, not able , ugly

css background-color css3

c++ - Independent multithreaded processes block simultaneously -



c++ - Independent multithreaded processes block simultaneously -

the scheme linux (gentoo x64), code c++. have daemon application, several instances of run on same machine. application multithreaded itself. time, have been observing unusual delays in performance.

after putting debugging code, came unusual thing when several instances of daemon literally block simultaneously allegedly caused external reason or something. set simple, have sequence this:

log time (t1) lock mutex call c++ std::list::push_back()/pop_back() (i.e. simple math) unlock mutex log time (t2)

from time time, see sequence above running in several independent (!) processes blocks @ step 2 (or probaby @ step 4) excessive time concerning math @ step 3 (for instance, 0.5 - 1.0 seconds). proof, see t2 in logs processes literally same (different in microseconds). looks threads of processes come in section @ relatively different times (i can see 0.5 - 1 seconds difference t1), lock in mutex, , unlock @ same time having allegedly spent unreasonable amount of time in lock according log (t2 - t1 difference). looks creepy me.

the manifestation of issue relatively rare, 1 time 5-10 minutes under moderate load. no ntp time shifts logged within test (that first thought actually). if ntp, there not actual delays in service, wrong times in log.

where start? start tuning scheduler? can theoretically block entire multithreaded process in linux?

run programme with:

valgrind --tool=helgrind ./your_program

you find more issues expect.

valgrind (helgrind) give detailed scenario of threaded application, nowadays must before deployment.

c++ linux-kernel mutex blocking scheduler

html5 - Color transitions animation in jquery -



html5 - Color transitions animation in jquery -

how animate between colors using jquery, i.e. fade out 1 color , fade in another.

i know can done css3 keyframes, doesn't work in net explorer mentioned w3schools. want standard method can work in browsers.

on search in stackoverflow, mentioned jquery color plugin required. know simpler method doing it?

you can seek this: live demo

css

#content { width: 100%; background: #eff6f4; transition: background 4s linear; -webkit-transition: background 4s linear; -moz-transition: background 4s linear; }

jquery

$('#content').css('background', '#c89cbd');

this alter background color in 4 seconds.

update

if need ie, can have this:

$('#content').fadeout(500, function(){ $(this).css('background', bg).fadein(2000); });

it won't good, works. live demo

jquery html5 css3

Save all meta tags name and value to an object using JavaScript -



Save all meta tags name and value to an object using JavaScript -

i need read meta tags on specific page , store each meta name , content values in datalayer array used google tag manager.

i want fetch meta tags want able force each value in array accordingly.

i have next code don't think best way if have 20-30 meta tags.i hope can help me improve code!!

<html> <head> <title> test metas</title> <meta name="abc" content="dummy"/> <meta name="def" content="dummy"/> <meta name="jhk" content="dummy"/> </head> <body> <script type="text/javascript" charset="utf-8"> function gtmmeta(name) { var metas = document.getelementsbytagname('meta'); (i=0; i<metas.length; i++) { if (metas[i].getattribute('name') == name) { homecoming metas[i].getattribute('content'); } } homecoming ''; } datalayer = [{}]; if (gtmmeta('abc') !=''){ datalayer.push({'cmsname': gtmmeta('abc')}) }; if (gtmmeta('def') !=''){ datalayer.push({'transactiontotal': gtmmeta('def')}); } if (gtmmeta('jhk') !=''){ datalayer.push({'market': gtmmeta('jhk')}); } </script> </body> </html>

to save having through each <meta> every time, 1 way set name/content pairs object.

var metaobj = {}, m = document.head.getelementsbytagname('meta'), = m.length; while (i--) { // looping downwards result in same behaviour stopping @ 1st metaobj[m[i].name] = m[i].content; }

and take want straight object

if (metaobj['abc']) { datalayer.push({'cmsname': metaobj['abc']}); }

you automate these too, looping on sec object, similar suggested manishearth

var metainterest = {'abc':'cmsname','def':'transactiontotal', 'jhk':'market'}, o; (i in metainterest) if (metainterest.hasownproperty(i) && metaobj[i]) o = {}, o[metainterest[i]] = metaobj[i], datalayer.push(o);

javascript

javascript - What is swarminject used for? -



javascript - What is swarminject used for? -

i can see in tests of jquery ui components there include of swarminject.js file:

<script src="../swarminject.js"></script>

what doing?

testswarm provides distributed continuous integration testing javascript. created john resig basic tool back upwards unit testing of jquery javascript library. later moved become official mozilla labs , has since moved 1 time again become jquery project. primary goal of testswarm take complicated, , time-consuming, process of running javascript test suites in multiple browsers , grossly simplify it. achieves goal providing tools necessary creating continuous integration workflow javascript project.

source: https://github.com/jquery/testswarm/wiki

javascript jquery jquery-ui

c# - object of Interop Word Document Class is null on Windows Server 2008 - Word Open method -



c# - object of Interop Word Document Class is null on Windows Server 2008 - Word Open method -

while opening word document , saving on machine working fine, when uploading on server , opening there, going in if (doc == null) block, should not go.

please update question title if not relevant or inquire clarification.

here class:

using system; using system.collections.generic; using system.web; using microsoft.office.interop.word; /// <summary> /// summary description clswordexmanager /// </summary> public class clswordexmanager { public enum extension { webpage = 0 } private static string htmextension { { homecoming ".htm"; } } private static application objwordapp = null; private static object objmissing = system.reflection.missing.value; private static document doc = null; static clswordexmanager() { seek { objwordapp = new application(); } grab (exception ex) { throw ex; } } public static void initializeclass() { objwordapp.visible = false; } private static string open(object strfilepath) { string str = string.empty; seek { objwordapp.visible = false; str += "<br /> word app visiblitly false"; } grab (exception ex) { objwordapp = new application(); str += ex.message; } seek { doc = objwordapp.documents.open(ref strfilepath, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing); str += "<br /> word document opened"; if (doc == null) { // null when upload on windows server 2008 office 2007 installed. str += "<br /> after openging null"; } } grab (exception ex) { close(); objwordapp.visible = false; str += "<br /> word document closed : " + ex.message; } homecoming str; } private static void close() { seek { doc.close(ref objmissing, ref objmissing, ref objmissing); } grab { } } private static string saveas(string filepath, string strfileextension, wdsaveformat objsaveformat) { seek { if (clscommon.isvaliduser()) // impersonating user { filepath = system.io.path.changeextension(filepath, strfileextension); seek { if (doc != null) { object objfilepath = filepath; object objformat = objsaveformat; doc.saveas(ref objfilepath, ref objformat, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing, ref objmissing); } else { filepath += "document value null"; } } grab { filepath += "<br /> saving document throwing expe"; homecoming filepath; } } else { filepath += "<br /> not valid saving file "; } } grab (exception ex) { filepath += ex.message; } { close(); } homecoming filepath; } public static string readwordfile(string strfilepath, extension objextension) { string strfilecontent = "<br /> reading word file not completed"; seek { strfilecontent += open(strfilepath); if (objextension == extension.webpage) { seek { string strnewfilename = saveas(strfilepath, htmextension, wdsaveformat.wdformatfilteredhtml); if (strnewfilename != "") { strfilecontent += strnewfilename + clscommon.readfile(strnewfilename, true); // ignore line read html file. } else { strfilecontent += "file not saved"; } } grab (exception ex) { strfilecontent += ex.message; } } else { close(); } } grab (exception exx) { strfilecontent += exx.message; } homecoming strfilecontent; } public static void quit() { seek { objwordapp.quit(ref objmissing, ref objmissing, ref objmissing); } grab { } } }

creating desktop folder asp.net user might have solved one problem, you'll run many more. word might pop dialog box, , you'll stuck.

office automation explicitly unsupported on server-side, , trust me - you'll have lots of problem:

microsoft not recommend, , not support, automation of microsoft office applications unattended, non-interactive client application or component (including asp, asp.net, dcom, , nt services), because office may exhibit unstable behavior and/or deadlock when office run in environment.

i suggest go on article in link above quote came, , utilize alternatives.

c# ms-word interop windows-server-2008 office-interop

Javascript inside php code not displaying -



Javascript inside php code not displaying -

i have within php code

var_dump($var); $var =' <script type="text/javascript"> '.$var.' </script>' ; var_dump($var);

the first var_dump displays correctly value, sec displays empty string.

exemplary output:

notice: undefined variable: var in /code/idpgmo on line 3 null notice: undefined variable: var in /code/idpgmo on line 7 string(50) " " php notice: undefined variable: var in /code/idpgmo on line 3 php notice: undefined variable: var in /code/idpgmo on line 7

why so?

it because browser handling script. scripts not shown run script in source not displayed on screen

php javascript

c# - ASP.NET Generated Output Not Effected By JQuery/Javascript -



c# - ASP.NET Generated Output Not Effected By JQuery/Javascript -

i have below code dynamically generates directory tree in html list format. when seek manipulate list items javascript add together '+' end of item, doesn't work. know jquery correct, have used on page on same server. jquery not able manipulate info dynamically generated server side asp.net?

<script langauge="c#" runat="server"> string output; protected void page_load(object sender, eventargs e) { getdirectorytree(request.querystring["path"]); itemwrapper.innerhtml = output; } private void getdirectorytree(string dirpath) { seek { system.io.directoryinfo rootdirectory = new system.io.directoryinfo(dirpath); foreach (system.io.directoryinfo subdirectory in rootdirectory.getdirectories()) { output = output + "<ul><li>" + subdirectory.name + "</li>"; getdirectorytree(subdirectory.fullname); if (subdirectory.getfiles().length != 0) { output = output + "<ul>"; foreach (system.io.fileinfo file in subdirectory.getfiles()) { output = output + "<li><a href='" + file.fullname + "'>" + file.name + "</a></li>"; } } output = output + "</ul>"; } } grab (system.unauthroizedaccessexception) { //this throws when don't have access, nil , move one. } } </script>

i seek manipulate output following:

<script langauge="javascript"> $('li > ul').not('li > ul > li > ul').prev().append('+'); </script>

just fyi code div below:

<div id="itemwrapper" runat="server"> </div>

it looks have couple of problems here. first should set jquery code within of $(document).ready. ensures dom has loaded before seek mess it. secondly, selector looking ul elements direct children of li elements. code not generate such html. have li's within of ul's not other way around. also, if directory has files in it, going leave ul elements unclosed mess html , javascript.

c# jquery asp.net css

python - Best practices in sanitizing public facing API? -



python - Best practices in sanitizing public facing API? -

as part of our service building publicly available api allow user perform simple tasks (mainly automation purposes) on our platform (like commenting, closing finished tasks , creating new ones).

api https based , requires authorization in form of calling /login login , password recieve token (that can devalidated in profile). utilize pyramid, postgresql , nginx if matters.

this first project of kind , wondering how should secure thing eating of our transfer or processing powerfulness (some of api functions quite heavy). want think in context of illustration in makes little error in script (that uses our api) , post comment every sec under same task (or list comments task). 2 days.

if forcefulness reads through cache (valid, example, next 10 seconds) nail our memcached servers , not postgres base of operations - sufficient in offloading issue (so other users not affected) or silly?

if check kind of timer , wait @ to the lowest degree 5 seconds before making write (5 seconds between writes) - ok or kill our server timer checking?

i guess more of question best practices in sanitizing public api wouldn't bite creators. how do it?

what you're looking rate limiting. without more knowledge how api written can't give specific advice on how implement it, best bet rate limit api consumers can't adversely impact other users of service.

python postgresql nginx memcached pyramid

Looking for some REGEX help in PHP -



Looking for some REGEX help in PHP -

i have string:

[color=gray]a bunch of text.[/color]

and write preg_replace removes between "[color=gray]" , "[/color]" -- if it's possible remove tags well, that's great, otherwise can simple replace afterward.

$str = 'dfgdfg[color=gray]a bunch of text.[/color]dfgdfgdfgfg'; $str1 = preg_replace('/\[color=gray\].*\[\/color\]/',"",$str); echo $str1;

or

if color not gray

$str = 'dfgdfg[color=gray]a bunch of text.[/color]dfgdfgdfgfg'; $str1 = preg_replace('/\[color=\w+\].*\[\/color\]/',"",$str); echo $str1;

php regex

android - WebView appears as plain white box after the second time it's been initialised -



android - WebView appears as plain white box after the second time it's been initialised -

edit: tl;dr: webview appears white box, though appear setting correctly, , indeed work first 2 times, fails subsequently)

edit: video showing problem in action...

i have next bit of code inflates view (which contains webview) xml defines it:

private void createcard(viewgroup cvframe, card card) { //... setup vairables... cvframe.cleardisappearingchildren(); cvframe.clearanimation(); seek { view cv = layoutinflater.from(getbasecontext()).inflate(r.layout.card_back_view, cvframe, true); cv.setbackgrounddrawable(drawable.createfromstream(mngr.open(deckname + "_card_back.png"), deckname)); textview suit = (textview)cv.findviewwithtag("card_back_suit"); //...setup text view suit, code works fine every time... webview title = (webview)cv.findviewwithtag("card_back_title"); //this webview doesn't appear 1 appears on screen (i can alter settings till i'm bluish in face, no effect) if (title != null) { title.setbackgroundcolor(0x00000000); title.loaddata(titletext, "text/html", "utf-8"); } else { log.e("cardview", "error can't find title webview"); } } grab (ioexception e) { log.e("cardview", "error making cards: ", e); } }

when method called part of oncreate method in activity, webview contains right code, , suitably transparent.

i have gesture listener replaces contents of viewgroup different content (it animates top card off left, replaces contents of top card card 2, puts top card back, replaces card 2 card 3)

//gesture listener event viewgroup cvframe = (viewgroup)findviewbyid(r.id.firstcard); cardloc++ cvframe.startanimation(slideleft);

(onanimationend code)

public void onanimationend(animation animation) { if (animation == slideleft) { viewgroup cvframeoldfront = (viewgroup)findviewbyid(r.id.firstcard); viewgroup cvframenewfront = (viewgroup)findviewbyid(r.id.secondcard); createcard(cvframeoldfront, cards.get((cardloc)%cards.size())); createcard(cvframenewfront, cards.get((cardloc+1)%cards.size())); translateanimation slideback = new translateanimation(0,0,0,0); slideback.setduration(1); slideback.setfillafter(true); cvframeoldfront.startanimation(slideback); } }

when animation has happened , replace contents of cards, textview suit replaced fine , code passes through code replace webview contents, reason end white rectangle size , shape of webview, no content, no transparency.

if alter webview textview, it's contents replaced fine, it's issue occurs webview command :s

can tell me why / suggest fix?

it turns out webview doesn't cleared downwards when using layoutinflater replace contents of viewgroup. other controls seem removed (or @ to the lowest degree findviewwithtag() returns right reference every other control). i've added in line cvframe.removeallviews() before layoutinflater it's stuff , fixed issue. if has improve explanation i'll throw points way otherwise go ether...

android android-webview layout-inflater

MATLAB student-t test from boxplot input -



MATLAB student-t test from boxplot input -

in matlab created boxplots of data. now, statistical analysis student-t test, see if difference significant. info paired, others not, difference in variance. think 2 tailed test should used. function in matlab calculate student-t test from boxplot, not need calculated imput values again?

regards,

vincent

the boxplot figure contains info shown, i.e. size of box , lines. theoretically possible estimate variance of distribution inter-quartile-distance (you have assume distribution follows specific shape, though), there way guess number of info points went plot.

to accurate test, you're hence much improve off re-calculate input values.

matlab boxplot significance

Facebook GraphAPI 'An error occured. Please try again later" -



Facebook GraphAPI 'An error occured. Please try again later" -

i've been getting error since around 7:15 ish, working fine before. went check on 'health status' , noticed following.

push: finish of today @ 7:25pm

coincidence?

my site url ip based , i've made several apps in facebook developer's portal using same ip while testing out permission settings.

is else having issue? having multiple apps same site url cause ip banned?

there's problem on variety of sites supporting oauth, check out similar post stackoverflow , corresponding facebook thread

facebook facebook-graph-api oauth

ant - Android Jenkins Build - debug "target" does not exist in the project error -



ant - Android Jenkins Build - debug "target" does not exist in the project error -

i set jenkins server along android sdk on headless linux build server. create android project via typical "android create project ..." command.

after "cd" new project, can "ant clean debug" jenkins user on command line. running jenkins workspace directory (.jenkins/workspace/<project name>):

# su jenkins $ ant clean debug .... successful ....

however, when jenkins job builds target "debug" not exist in project "projectname" error

i set sdk.dir variable android sdk directory, command in jenkins log runs like:

$ ant -dsdk.dir=/opt/java/android clean debug

i've set permissions 777 on entire android sdk folder:

# chmod -r 777 /usr/java/android/android-sdk

i'm @ loss else might missing? why command run on command line unsuccessful jenkins job?

thanks!

are running command line ant build same place jenkins trying to?

double check

.jenkins/workspace/<project-name>

directory create sure has same project files you're running things command line manually.

android ant jenkins

Grail command objects instance validation? -



Grail command objects instance validation? -

let's have command-object containing 7 fields(string monday, string tuesday, ..) , need validate check if @ to the lowest degree 1 of them exists.

because of working grails 1.3.7 tried utilize instance validation extended-validation-plugin(not rich-domain) couldn't create work. basically, not recognise non-field validator within of static constraints block.

static constraints = { availabilityselected(validator: { ... }) ...

and get:

exception message: no such property: availabilityselected

is there other smart way it? not want add together validator every single field in command object.

thanks

you can access object beingness validated via 2 / 3 parameter form of custom validator.

myfield(validator: { val, obj, errors -> if( obj.blah.empty && obj.blah.empty ) { errors.reject( ... ) } )

http://grails.org/doc/1.3.7/ref/constraints/validator.html

validation grails command-objects

java - neo4j slow lucene index query -



java - neo4j slow lucene index query -

i'm retrieving info index in neo4j database, , i'm having problems execution time. i'm trying query count resulting values. in production database i'm doing more complex calculations. anyway, query looks this,

start person = node:user_index('muncipalitycode:(1278 or 1285 or 1283 or 1293 or 1284 or 1261 or 1282 or 1262 or 1281 or 1280 or 1273) ') homecoming count(person)

the count returns 278418 in approximately 20 seconds(2.5-3 seconds sec time, when cache warm). sure, i'm returning quite big dataset. however, not immense.

is there somewhere can cut down bottleneck or configuration settings should into? i've tried warming cache on startup, can't fit info in ram on production server, backfires(my server has 16gb ram).

my database has next attributes. 10 329 245 nodes 97 923 564 properties 50 697 532 relationships

i utilize luke verify whether problem in index or elsewhere in code. if corresponding luke query fast, problem lies elsewhere.

java neo4j cypher

windows - Replacing a specific line in batch and reading and setting what i read as a variable -



windows - Replacing a specific line in batch and reading and setting what i read as a variable -

i wanted create menu this:

mode 59, 300 set line=========================================================== echo %line% echo tool colour menu! echo %line% echo. echo take background colour! echo. echo 1 = bluish echo 2 = greenish echo 3 = aqua echo 4 = reddish echo 5 = violet echo 6 = yellowish echo 7 = white echo 8 = grayness echo 9 = lite bluish echo 10 = lite greenish echo 11 = lite aqua echo 12 = lite reddish echo 13 = lite violet echo 14 = lite yellowish echo 15 = bright white echo. set /p background_app=enter number of colour want background (or come in default):

so menu background_app variable!

and then:

mode 59, 300 set line=========================================================== echo %line% echo tool color menu! echo %line% echo. echo take text color! echo. echo 1 = bluish echo 2 = greenish echo 3 = aqua echo 4 = reddish echo 5 = violet echo 6 = yellowish echo 7 = white echo 8 = grayness echo 9 = lite bluish echo 10 = lite greenish echo 11 = lite aqua echo 12 = lite reddish echo 13 = lite violet echo 14 = lite yellowish echo 15 = bright white echo. set /p text_app=enter number of color want text (or come in default):

this variable %text_app%

after user input wanted save variables in txt file retrieve values later in case user runs tool (to maintain colours person choosing)

but have tried:

:savevars ( echo backuground=%background_app% echo text=%text_app% ) >colors.txt goto :eof

for illustration save this:

background=1 text=7

and comes dilemma, because wanted read value colors.txt , set variables as:

%background_apptxt% %text_apptxt%

how can read value of background , text? help :)

well it's pretty easy understand example:

colors.txt contains lines:

background=1 text=2

so illustration used batch create test batch:

@echo off set background_app=black set text_app=green :savevars ( echo background=%background_app% echo text=%text_app% ) >colors.txt /f "tokens=1,2 delims==" %%a in (colors.txt) set "%%a_app=%%b"

how echo %background_app% , echo 1 time again %text_app% ? give thanks you

use /f loop read , parse each line. can set token delimiter = 2 tokens.

for /f "tokens=1,2 delims==" %%a in (colors.txt) set "%%a_app=%%b"

the code easier if text file contains total name of each variable. use

for /f "delims=" %%a in (colors.txt) set "%%a"

windows command-line batch-file dos

java - DragSource - InvalidDnDOperationException on starting DragAction -



java - DragSource - InvalidDnDOperationException on starting DragAction -

my application contains few jpanels sould moved dnd. have implemented listeners , handlers, seems right. when dragging 1 panel mouse draggesturelistener recognizes , wants start new dragaction:

@override public void draggesturerecognized(draggestureevent dge) { // when drag begins, need grab reference // parent container can homecoming if drop // rejected container parent = getpanel().getparent(); setparent(parent); // remove panel parent. if don't this, // can cause serialization issues. on come // allowing drop target remove component, that's // argument day parent.remove(getpanel()); // update display parent.invalidate(); parent.repaint(); // create our transferable wrapper tickettransferable transferable = new tickettransferable(getpanel()); // start "drag" process... dge.startdrag(null, transferable); }

but next exception occurs:

exception in thread "awt-eventqueue-0" java.awt.dnd.invaliddndoperationexception: cannot find top-level drag source component @ sun.awt.x11.xdragsourcecontextpeer.startdrag(xdragsourcecontextpeer.java:126) @ sun.awt.dnd.sundragsourcecontextpeer.startdrag(sundragsourcecontextpeer.java:134)

i checked xdragsourcecontextpeer , found out component triggers dragaction (in case jpanel move itself) must of type "window" start drag properly. point jpanel isnt window , mentioned exception thrown back.

what doing wrong?

p.s.: "moveable" panels in different cells of jtable.

java swing drag-and-drop

Simple SQL query for Min and Max -



Simple SQL query for Min and Max -

so trying find age of oldest , youngest male , female patients along average age of male , female patients in clinic work. new sql comes 1 table believe named "patients". within patients table there column gender has either m male or f female. there age column. guessing simple , making complicated seek help me out?

my query pretty limited. know if along lines of:

select min(age) agemin, max(age) agemax patients

use group by clause:

select * @mytable m 10 m 15 m 20 f 30 f 35

f 40

select gender, min(age), max(age), avg(age) @mytable grouping gender

f 30 40 35

m 10 20 15

sql

android - Simple way to get which image was clicked when running same function -



android - Simple way to get which image was clicked when running same function -

i'm making card game android. select first card clicking image1, sec card clicking image2, etc. these images run same function in java, how can pass variable clicked image1, image2, or image3? i'd avoid having 3 functions exact same aside 1 variable. input.

i'm not sure mean "images run same function in java", if mean have same onclicklistener utilize getid() determine view clicked.

public void onclick(view v) { switch(v.getid()) { case r.id.one: // break; case r.id.two: // break; } }

android

ruby - Issue with session redirect in rails 3 -



ruby - Issue with session redirect in rails 3 -

i'm having little problem using sessions in rails 3. detail of work environment first.

i have application hosted on heroku, let's url http://myapp.herokuapp.com

and have domain cname pointed heroku, let's it's http://www.myapp.com

when send email app client, contains url restricted area of application, way done is:

http://www.myapp.com -> email -> http://www.myapp.com/secret

but how secret area user redirected http://www.myapp.com/log_in

here's problem: rails saves actual url of application, in case http://myapp.herokuapp.com, , after login redirects user http://myapp.herokuapp.com/secret! , not want it, want go on in field http://myapp.com.

is there way this?

try :

redirect_to secret_path( host: 'myapp.com' )

or

redirect_to url_for( action: 'my_action', host: some_default_host )

edit

i'm not sure understood question - mean save uris in db ?

imho, saving hardcoded urls can become hassle.

if possible, seek save deconstructed uri parts instead of total string path, can send args url_for or path helper later (and tweak needed, or update whole table @ 1 time alter host example).

if not, can parse saved uri lib of choice, , tweak before redirection

ruby-on-rails ruby session redirect heroku

symfony2 - Global Params in FOSUserBundle -



symfony2 - Global Params in FOSUserBundle -

i seek retrieve global param define in parameters.yml , config.yml

in fosuserbundle.en.yml under registration, in message seek pass %myparam% , in email.txt seek pass %myparam%:param this

{{ 'registration.email.message'|trans({'%username%': user.username, '%confirmationurl%': confirmationurl,'%myparam%':myparam}, 'fosuserbundle') }}

but dosen't works. , can insert html within yml , new line? thanks

in config.yml under fosuserbundle configuration.

confirmation: enabled: true template: mymailbundle:registration:email.html.twig

by doing creating twig template can render variables , format html how want.

if want create newline in yml file think adding \n.

symfony2 fosuserbundle

.htaccess - Far future Expires header ignored -



.htaccess - Far future Expires header ignored -

following advice given yahoo / yslow @ http://developer.yahoo.com/performance/rules.html#expires trying set far future expires header images.

in .htacess have:

<filesmatch "\.(jpg|jpeg|png|gif)$"> header unset pragma fileetag none header unset etag header set cache-control "public" header set expires "thu, 15 apr 2014 20:00:00 gmt" header unset last-modified </filesmatch>

using live http headers in firefox can see there no etag , expires date shows 2014. also, looking @ cache can confirm expires date , there no etag or server lastly modified date.

again next info given @ yslow expecting if alter image without altering filename no changes take effect until expires date reached. yslow points out “if utilize far future expires header have alter component's filename whenever component changes”.

however, testing on localhost xampp alter create image still reflected on web page if refresh it.

is local server thing or have misunderstood how intended work?

thanks.

.htaccess xampp cache-control expires-header

how to add Two TextView in Android's ViewPagerExtension Library -



how to add Two TextView in Android's ViewPagerExtension Library -

i using viewpagerextension in android project.i able add together 1 textview each tab. want add together 2 textviews in each tabs.how can achieae that?

make wrapper view, i.e. linearlayout, , set 2 textview elements within wrapper view. then, instead of adding textview elements viewpager, add together wrapper layouts viewpager.

android

visual studio - Trying to compile Android non native project with NSight -



visual studio - Trying to compile Android non native project with NSight -

i trying compile plain , simple android application without native code using new nsight plugin visual studio. problem visual studio wont seek compile doesn't see compile. running ant debug manually compiles fine. android application native code works fine, visual studio recognizes c file compile. know how prepare this, because is, android application without native code alternative rather useless.

the output is

1>------ build started: project: android3, configuration: debug android ------ ========== build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

i should note if go command line, , run ant build, builds fine.

maybe can seek helloworld sample template "android application", see if compiles.

if installed nsight tegra tegra android development pack, , installed android sdk/ndk, ant, java that. should preconfigured working. need 32bit java in path, , java_home,ant_home environments. have seen native compiled, java related missed or messed in environments.

as described "no compiling", there other log in output?

android visual-studio nvidia nsight tegra

git - github clone from pull request? -



git - github clone from pull request? -

i clone repo github. problem don't want main branch, want version in this unapproved pull request.

is possible me clone pull request version instead of main repo?

you can clone the branch want using -b alternative in git clone command. in case, branch want clone source branch of pull request(feature/mongoose-support)

git clone https://github.com/berstend/frappe.git -b feature/mongoose-support /my_clone

git github pull-request

Perl - enhance code to recursively count files -



Perl - enhance code to recursively count files -

i new perl , trying larn language having hard time doing think simple.

i have been able script working count number of files in directory. enhance script recursively count files in sub directories also. have searched , found few different options glob , file::find, have not been able them work.

my current code:

#!/usr/bin/perl utilize strict; utilize warnings; utilize path::class; # set variables $count = 0; # set count start @ 0 $dir = dir('p:'); # p/ # iterate on content of p:pepid content db/pepid ed while (my $file = $dir->next) { next if $file->is_dir(); # see if directory , skip print $file->stringify . "\n"; # print out file name , path $count++ # increment count 1 every file counted } print "number of files counted " . $count . "\n";

can help me enhance code recursively search sub directories well?

the file::find module friend recursive kinds of operations. here's simple script counts files:

#!/usr/bin/perl utilize strict; utilize warnings; utilize cwd; utilize file::find; $dir = getcwd; # current working directory $counter = 0; find(\&wanted, $dir); print "found $counter files @ , below $dir\n"; sub wanted { -f && $counter++; # count files }

perl

powershell - how to get a pc list that have a service running on each pc? -



powershell - how to get a pc list that have a service running on each pc? -

i m using psexec auto run cmd on pcs on our network check if process running or not. wannt list pc name has service running on. how can powershell?

this m running now. 2 batch files , 1 text file.

get.bat

tasklist | findstr pmill.exe >> dc-01\c$\0001.txt

run_get.bat

psexec @%1 -u administrator -p password -c "c:\get.bat"

pclist.txt

what got in result pmill.exe , m wondering if there anyway can output pc name has pmill.exe running on?

hint plz!

if computers have powershell installed remoting enabled, can seek script below. outputs computers not reachable can retest them later if want to. if don't need it, remove content within catch-block(or of try/catch):

$out = @() get-content "pclist.txt" | foreach { $pc = $_ seek { if((get-process -name "pmill" -computername $pc) -ne $null) { $out += $_ } } grab { #unknown error $out += "error: $pc not checked. $_.message" } } $out | set-content "out.txt"

pclist.txt:

graimer-pc pcwithoutprocesscalledpmill testcomputer testpc graimer-pc

out.txt (log):

graimer-pc error: testcomputer unreachable error: testpc unreachable graimer-pc

powershell batch-file powershell-v2.0

frameworks - What is the version of Apache Camel used in Akka 2.1? -



frameworks - What is the version of Apache Camel used in Akka 2.1? -

i looking @ using akka camel in mission critical app. version of apache camel used in current akka 2.1? how can used latest apache camel in akka?

from akka dependencies, seems akka-camel uses apache camel 2.10.0:

val camelcore = "org.apache.camel" % "camel-core" % "2.10.0" exclude("org.slf4j", "slf4j-api") // apachev2

apache frameworks version integration akka

php - Is a BLOB converted using the current/default charset in MySQL? -



php - Is a BLOB converted using the current/default charset in MySQL? -

i have table blob field. the charset of table latin1. i connect db , "set character set utf8". then save binary info field. then retrieve data, , it's not saved (corrupt).

the code:

<?php $pdo = new \pdo("mysql:host=127.0.0.1;dbname=***", '***', '***'); $pdo->exec('set character set utf8'); $sql = "insert pdo_blob (the_blob) values(:the_blob)"; $insertstm = $pdo->prepare($sql); $blob = (binary) file_get_contents('/home/***/test.pdf'); $insertstm->bindparam(":the_blob", $blob, \pdo::param_lob); $insertstm->execute(); $selectstm = $pdo->prepare("select the_blob pdo_blob order id desc limit 1"); $selectstm->execute(); $savedblob = null; $selectstm->bindcolumn(1, $savedblob, \pdo::param_lob); $selectstm->fetch(); echo 'equal: ' . ((int) ($blob == $savedblob));

good reply @mvp!

but when web app utf-8 , database encoding latin1, have to set character_set_client , character_set_results.

when utilize set character set utf8, got described problem blobs.

but when utilize set names utf8 instead works!

php mysql perl utf-8 pdo

cocoa - Modify defaults of sandboxed application from non-sandboxed app -



cocoa - Modify defaults of sandboxed application from non-sandboxed app -

i have application i'm sandboxing. automated acceptance testing using accessibility api different process. before sandboxing, test suite used cfpreferencessetvalue , friends set default values application.

after sandboxing, defaults read ~/library/containers/bundleid/data/library/preferences cfpreferencessetvalue functions writes ~/library/preferences far understand.

is there way programmatically write preferences sandboxed preferences without e.g. hardcoding location , modifying plist directly, or using defaults command line utility.

one solution add together "application group" sandboxed app, thereby allowing other apps of grouping share preferences, see: reading nsuserdefaults helper app in sandbox

cocoa nsuserdefaults sandbox

Conflict between relative and absolute path while using two exe file in delphi -



Conflict between relative and absolute path while using two exe file in delphi -

i have 1 exe myapp.exe in c:\myproject folder. writes logs in logfile tracefile.log there in c:\myproject.

now have create schedule task schedule1.exe write in logfile tracefile.log located in c:\myproject.

ok, created schedule1.exe , kept in same folder c:\myproject folder , made schedule taks using exe.

problem: schedule1.exe cannot pick path of logfile when give relative path of logfile ".\tracefile.log". when give total path "c:\myproject", picks logfile path , writes on it.

please suggest problem?

relative paths relative working directory of process. working directory of process determined @ process startup, , may not directory contains executable. what's more, working directory can alter during processes life.

it seems me should giving total path these files. need hold of directory in executable lives. is

extractfilepath(paramstr(0));

so should using code name file:

extractfilepath(paramstr(0)) + 'tracefile.log'

delphi delphi-xe2 delphi-7

ANT error: failed to create task or type antlib:com.salesforce:deploy -



ANT error: failed to create task or type antlib:com.salesforce:deploy -

i've started play force.com migration tool. want utilize ant build file. i've created one:

<project name="subversion org" default="deploy" basedir="." xmlns:sf="antlib:com.salesforce"> <target name="deploy"> <echo message="deploying metadata" /> <echo message="ant_home=${ant.home}"/> <echo message="basedir=${basedir}"/> <echo message="ant_core_lib=${ant.core.lib}"/> <echo message="java_version=${ant.java.version}"/> <echo message="ant_library_dir=${ant.library.dir}"/> <echo message="classpath=${java.class.path}"/> <sf:deploy username="${properties.username}" password="${properties.password}" serverurl="${properties.url}" deployroot="${properties.root}" singlepackage="${properties.singlepackage}" runalltests="${properties.alltest}" /> </target> </project>

i've copied ant-salesforce.jar in ant.lib folder. when execute file throught ant this:

buildfile: build.xml deploy: [echo] deploying metadata [echo] ant_home=/usr/share/ant [echo] basedir=/usr/share/tomcat6/.jenkins/jobs/salesforce deploy test/workspace/deploy script [echo] ant_core_lib=/usr/share/java/ant-1.7.1.jar [echo] java_version=1.6 [echo] ant_library_dir=/usr/share/ant/lib [echo] classpath=/usr/share/java/ant.jar:/usr/share/java/ant-launcher.jar:/usr/share/java/jaxp_parser_impl.jar:/usr/share/java/xml-commons-apis.jar:/usr/lib/jvm/java/lib/tools.jar:/usr/share/ant/lib/ant.jar:/usr/share/ant/lib/ant-launcher.jar:/usr/share/ant/lib/ant-salesforce.jar:/usr/share/ant/lib/ant-bootstrap.jar build failed /usr/share/tomcat6/.jenkins/jobs/salesforce deploy test/workspace/deploy script/build.xml:16: problem: failed create task or type antlib:com.salesforce:deploy cause: name undefined. action: check spelling. action: check custom tasks/types have been declared. action: check <presetdef>/<macrodef> declarations have taken place. no types or tasks have been defined in namespace yet appears antlib declaration. action: check implementing library exists in 1 of: -/usr/share/ant/lib -/root/.ant/lib -a directory added on command line -lib argument total time: 0 seconds

it seems ant-salesforce.jar file isn't found, appears listed in output. ideas?

more info:

permissions check

ls -al /usr/share/ant/lib total 3412 drwxr-xr-x. 2 root root 4096 feb 12 15:36 . drwxr-xr-x. 4 root root 4096 feb 12 09:49 .. lrwxrwxrwx. 1 root root 28 feb 12 09:49 ant-bootstrap.jar -> ../../java/ant-bootstrap.jar lrwxrwxrwx. 1 root root 18 feb 12 09:49 ant.jar -> ../../java/ant.jar lrwxrwxrwx. 1 root root 27 feb 12 09:49 ant-launcher.jar -> ../../java/ant-launcher.jar -rwxrwxrwx. 1 root root 3483648 feb 12 12:58 ant-salesforce.jar

jar contents check:

... com/salesforce/ant/bulkretrievetask.class com/salesforce/ant/compileandtest$codenameelement.class com/salesforce/ant/compileandtest$runtestselement.class com/salesforce/ant/compileandtest.class com/salesforce/ant/configuration.class com/salesforce/ant/connectionfactory.class com/salesforce/ant/deploytask$codenameelement.class com/salesforce/ant/deploytask.class com/salesforce/ant/describemetadatatask.class com/salesforce/ant/listmetadatatask.class com/salesforce/ant/retrievetask$packagemanifestparser.class com/salesforce/ant/retrievetask.class com/salesforce/ant/sfdcanttask.class com/salesforce/ant/sfdcmdapianttask.class com/salesforce/ant/sfdcmdapianttaskrunner.class com/salesforce/ant/ziputil.class com/salesforce/antlib.xml ...

antlib file contents (as expected):

<antlib> <typedef name="compileandtest" classname="com.salesforce.ant.compileandtest"/> <typedef name="deploy" classname="com.salesforce.ant.deploytask"/> <typedef name="retrieve" classname="com.salesforce.ant.retrievetask"/> <typedef name="bulkretrieve" classname="com.salesforce.ant.bulkretrievetask"/> <typedef name="listmetadata" classname="com.salesforce.ant.listmetadatatask"/> <typedef name="describemetadata" classname="com.salesforce.ant.describemetadatatask"/> </antlib>

thanks in advance.

your syntax sf:deploy good. matches mine.

check project definition. setting namespace of xmlns:sf right value?

should be:

<project name="salesforce" default="deploy" basedir="." xmlns:sf="antlib:com.salesforce">

you check permissions of ant-salesforce.jar.

and check jar not corrupted

jar -tf ant-salesforce.jar

ant salesforce force.com

c++ - Acquire/Release versus Sequentially Consistent memory order -



c++ - Acquire/Release versus Sequentially Consistent memory order -

for std::atomic<t> t primitive type:

if utilize std::memory_order_acq_rel fetch_xxx operations, , std::memory_order_acquire load operation , std::memory_order_release store operation blindly (i mean resetting default memory ordering of functions)

will results same if used std::memory_order_seq_cst (which beingness used default) of declared operations? if results same, usage anyhow different using std::memory_order_seq_cst in terms of efficiency?

the c++11 memory ordering parameters atomic operations specify constraints on ordering. if store std::memory_order_release, , load thread reads value std::memory_order_acquire subsequent read operations sec thread see values stored memory location first thread prior store-release, or later store of memory locations.

if both store , subsequent load std::memory_order_seq_cst relationship between these 2 threads same. need more threads see difference.

e.g. std::atomic<int> variables x , y, both 0.

thread 1:

x.store(1,std::memory_order_release);

thread 2:

y.store(1,std::memory_order_release);

thread 3:

int a=x.load(std::memory_order_acquire); // x before y int b=y.load(std::memory_order_acquire);

thread 4:

int c=y.load(std::memory_order_acquire); // y before x int d=x.load(std::memory_order_acquire);

as written, there no relationship between stores x , y, quite possible see a==1, b==0 in thread 3, , c==1 , d==0 in thread 4.

if memory orderings changed std::memory_order_seq_cst enforces ordering between stores x , y. consequently, if thread 3 sees a==1 , b==0 means store x must before store y, if thread 4 sees c==1, meaning store y has completed, store x must have completed, must have d==1.

in practice, using std::memory_order_seq_cst everywhere add together additional overhead either loads or stores or both, depending on compiler , processor architecture. e.g. mutual technique x86 processors utilize xchg instructions rather mov instructions std::memory_order_seq_cst stores, in order provide necessary ordering guarantees, whereas std::memory_order_release plain mov suffice. on systems more relaxed memory architectures overhead may greater, since plain loads , stores have fewer guarantees.

memory ordering hard. devoted entire chapter in my book.

c++ concurrency c++11 atomic

c# - NullReferenceException in finalizer during MSTest -



c# - NullReferenceException in finalizer during MSTest -

(i know, ridiculously long question. tried separate question investigation far, it's easier read.)

i'm running unit tests using mstest.exe. occasionally, see test error:

on individual unit test method: "the agent process stopped while test running."

on entire test run:

1 of background threads threw exception: system.nullreferenceexception: object reference not set instance of object. @ system.runtime.interopservices.marshal.releasecomobject(object o) @ system.management.instrumentation.metadatainfo.dispose() @ system.management.instrumentation.metadatainfo.finalize()

so, here's think need do: need track downwards causing error in metadatainfo, i'm drawing blank. unit test suite takes on half hr run, , error doesn't happen every time, it's hard reproduce.

has else seen type of failure in running unit tests? able track downwards specific component?

edit:

the code under test mix of c#, c++/cli, , little bit of unmanaged c++ code. unmanaged c++ used c++/cli, never straight unit tests. unit tests c#.

the code under test running in standalone windows service, there's no complication asp.net or that. in code under test, there's threads starting & stopping, network communication, , file i/o local hard drive.

my investigation far:

i spent time digging around multiple versions of system.management assembly on windows 7 machine, , found metadatainfo class in system.management that's in windows directory. (the version that's under programme files\reference assemblies much smaller, , doesn't have metadatainfo class.)

using reflector inspect assembly, found seems obvious bug in metadatainfo.dispose():

// class system.management.instrumentation.metadatainfo: public void dispose() { if (this.importinterface == null) // <---- should "!=" { marshal.releasecomobject(this.importinterface); } this.importinterface = null; gc.suppressfinalize(this); }

with 'if' statement backwards, metadatainfo leak com object if present, or throw nullreferenceexception if not. i've reported on microsoft connect: https://connect.microsoft.com/visualstudio/feedback/details/779328/

using reflector, able find uses of metadatainfo class. (it's internal class, searching assembly should finish list.) there 1 place used:

public static guid getmvid(assembly assembly) { using (metadatainfo info = new metadatainfo(assembly)) { homecoming info.mvid; } }

since uses of metadatainfo beingness disposed, here's what's happening:

if metadatainfo.importinterface not null: static method getmvid returns metadatainfo.mvid the using calls metadatainfo.dispose dispose leaks com object dispose sets importinterface null dispose calls gc.suppressfinalize later, when gc collects metadatainfo, finalizer skipped. . if metadatainfo.importinterface null: static method getmvid gets nullreferenceexception calling metadatainfo.mvid. before exception propagates up, using calls metadatainfo.dispose dispose calls marshal.releasecomobject marshal.releasecomobject throws nullreferenceexception. because exception thrown, dispose doesn't phone call gc.suppressfinalize the exception propagates getmvid's caller. later, when gc collects metadatainfo, runs finalizer finalize calls dispose dispose calls marshal.releasecomobject marshal.releasecomobject throws nullreferenceexception, propagates way gc, , application terminated.

for it's worth, here's rest of relevant code metadatainfo:

public metadatainfo(string assemblyname) { guid riid = new guid(((guidattribute) attribute.getcustomattribute(typeof(imetadataimportinternalonly), typeof(guidattribute), false)).value); // above line retrieves guid: "7dac8207-d3ae-4c75-9b67-92801a497d44" imetadatadispenser o = (imetadatadispenser) new cormetadatadispenser(); this.importinterface = (imetadataimportinternalonly) o.openscope(assemblyname, 0, ref riid); marshal.releasecomobject(o); } private void initnameandmvid() { if (this.name == null) { uint num; stringbuilder szname = new stringbuilder { capacity = 0 }; this.importinterface.getscopeprops(szname, (uint) szname.capacity, out num, out this.mvid); szname.capacity = (int) num; this.importinterface.getscopeprops(szname, (uint) szname.capacity, out num, out this.mvid); this.name = szname.tostring(); } } public guid mvid { { this.initnameandmvid(); homecoming this.mvid; } } edit 2:

i able reproduce bug in metadatainfo class microsoft. however, reproduction different issue i'm seeing here.

reproduction: seek create metadatainfo object on file isn't managed assembly. throws exception constructor before importinterface initialized. my issue mstest: metadatainfo constructed on managed assembly, , something happens create importinterface null, or exit constructor before importinterface initialized. i know metadatainfo created on managed assembly, because metadatainfo internal class, , api calls passing result of assembly.location.

however, re-creating issue in visual studio meant downloaded source metadatainfo me. here's actual code, original developer's comments.

public void dispose() { // implement idisposable on class because imetadataimport // can expensive object maintain in memory. if(importinterface == null) marshal.releasecomobject(importinterface); importinterface = null; gc.suppressfinalize(this); } ~metadatainfo() { dispose(); }

the original code confirms seen in reflector: if statement backwards, , shouldn't accessing managed object finalizer.

i said before because never calling releasecomobject, leaking com object. read more on utilize of com objects in .net, , if understand properly, incorrect: com object isn't released when dispose() called, released when garbage collector gets around collecting runtime callable wrapper, managed object. though it's wrapper unmanaged com object, rcw still managed object, , rule "don't access managed objects finalizer" should still apply.

try add together next code class definition:

bool _disposing = false // class property public void dispose() { if( !disposing ) marshal.releasecomobject(importinterface); importinterface = null; gc.suppressfinalize(this); disposing = true; }

c# .net mstest system.management

css - Twitter Bootstrap with 1024px fixed width -



css - Twitter Bootstrap with 1024px fixed width -

my project needs me create website 1024px fixed width. how can utilize twitter bootstrap uses 960px fixed width method adjust 1024px width.

is there downsides of having 1024px width websites?

you can create .container class , assign width of 1024px .

.container{ width:1024px; }

and have rewrite classes according .

downsize can little monitors there can scrollbar in browsers.suppose create pages @ 1024×768, not fit screen of visitor has set his/her resolution 800×600.

but these days people have bigger screen resolution , go 1024px size .

css twitter-bootstrap

c - How to count number of lines in a function -



c - How to count number of lines in a function -

i need count number of lines in function in file. have next inputs.

inputs:

name of file, name of function

required output:

number of lines in function

example:

int main() { line1; line2; line3; } int func() { line1 line2 line3 line4 line5 if(---) //line 6 { //line 7 line 8 line 9 } //line10 }

so above illustration should homecoming 10 if pass file name , function name "func"

kindly suggest way it...

code has strict format, indent source files

indent -kr -bap -nce -i8 -ts8 -sob -l80 -ss -bs -npsl -bl -bli0 file.c

awk + substr($0,1,1) match '{' , '}'

awk -f"," '{ if( index(v_func,$0)<10 ) { findfunc=1; } if( findfunc == 1) { if( substr($0,1,1) == "{" ) { linecnt=0; } else if(substr($0,1,1) == "}" ) { print linecnt; } else { linecnt = linecnt+1; } } }' v_func=$2 $1

c perl

javascript - File Errors in Android Cordova -



javascript - File Errors in Android Cordova -

i thought i'd post may useful others, i've struggled error feedback while lodging files in android/cordova hybrid application. next blocks of code should create easier - pointers improvement welcome.

fail: function(error) { var logger = cordova.require("salesforce/util/logger"); switch(error.code) { case fileerror.not_found_err: logger.logtoconsole("file not found"); break; case fileerror.security_err: logger.logtoconsole("security error"); break; case fileerror.abort_err: logger.logtoconsole("abort error"); break; case fileerror.not_readable_err: logger.logtoconsole("not readable"); break; case fileerror.encoding_err: logger.logtoconsole("encoding error"); break; case fileerror.no_modification_allowed_err: logger.logtoconsole("no modification allowed"); break; case fileerror.invalid_state_err: logger.logtoconsole("invalid state"); break; case fileerror.syntax_err: logger.logtoconsole("syntax error"); break; case fileerror.invalid_modification_err: logger.logtoconsole("invalid modification error"); break; case fileerror.quota_exceeded_err: logger.logtoconsole("quota exceeded"); break; case fileerror.type_mismatch_err: logger.logtoconsole("type mismatch error"); break; case fileerror.path_exists_err: logger.logtoconsole("path exists error"); break; } logger.logtoconsole("error code:: " + error.code); }

here file save routine causing issues (turned out needed create: true flag). hope it's helpful.

savelocal: function (file, data, sync) { //accept json of inspection object cordova.require("salesforce/util/logger").logtoconsole("writing " + file); //write info requested file window.requestfilesystem(localfilesystem.persistent, 0, function(filesystem) { cordova.require("salesforce/util/logger").logtoconsole("writing " + file); filesystem.root.getfile(file, {create: true}, function(fileentry) { cordova.require("salesforce/util/logger").logtoconsole("create writer"); fileentry.createwriter(function (writer) { writer.write(json.stringify(data)); //trigger send info salesforce if (sync) {sync();} //send event if registered if (onsaveend) {onsaveend(data);} }, anytime.fail); }, anytime.fail); }, anytime.fail); }

javascript android cordova