Search Results

Search found 637 results on 26 pages for 'p1'.

Page 10/26 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • How to attach a line to a moving object?

    - by snow-spur
    Hello i have designed a maze and i want to draw a path between the cells as the 'person' moves from one cell to the next. So each time i move the cell a line is drawn I have done this so far but do not want to show my full code However i get an error saying Circle has no attribute center my circle which is my cell center = Point(15, 15) c = Circle(center, 12) c.setFill('blue') c.setOutline('yellow') c.draw(win) p1 = Point(c.center().getx(), c.center().gety()) this bit is in my loop p2 = Point(getx(), gety()) line = graphics.Line(p1, p2)

    Read the article

  • p=malloc()!=null.......

    - by gcc
    char *p,*p1,*p2,*p3,*p4; for(;;) { if((p=malloc(10))!=NULL && (p1=malloc(20))!=NULL ......) break; } Writing if(........) is too boring and long, are there any ways to make it simpler?

    Read the article

  • problem in run oracle server please help

    - by rima
    I used Oracle 11g, from few days ago I face below error: SQL*Plus: Release 11.2.0.1.0 Production on Thu Apr 7 07:33:19 2011 Copyright (c) 1982, 2010, Oracle. All rights reserved. Enter user-name: pentacms Enter password: ERROR: ORA-01033: ORACLE initialization or shutdown in progress Process ID: 0 Session ID: 0 Serial number: 0 Enter user-name: I try to solve the error, but it raised an other error, I try to open log file but I receive below error(last line) "ERROR at line 1: ORA-00600: internal error code, arguments: [kcratr_nab_less_than_odr], [1], [46], [32689], [32690], [], [], [], [], [], [], [] " please advice me, It's an emergency case. FIXED_TABLE_SEQUENCE ROW_WAIT_OBJ# ROW_WAIT_FILE# ROW_WAIT_BLOCK# ROW_WAIT_ROW# -------------------- ------------- -------------- --------------- ------------- TOP_LEVEL_CALL# LOGON_TIM LAST_CALL_ET PDM FAILOVER_TYPE FAILOVER_M FAI --------------- --------- ------------ --- ------------- ---------- --- RESOURCE_CONSUMER_GROUP PDML_STA PDDL_STA PQ_STATU -------------------------------- -------- -------- -------- CURRENT_QUEUE_DURATION ---------------------- CLIENT_IDENTIFIER BLOCKING_SE ---------------------------------------------------------------- ----------- BLOCKING_INSTANCE BLOCKING_SESSION FINAL_BLOCK FINAL_BLOCKING_INSTANCE ----------------- ---------------- ----------- ----------------------- FINAL_BLOCKING_SESSION SEQ# EVENT# ---------------------- ---------- ---------- EVENT ---------------------------------------------------------------- P1TEXT P1 ---------------------------------------------------------------- ---------- P1RAW ---------------- P2TEXT P2 ---------------------------------------------------------------- ---------- P2RAW ---------------- P3TEXT P3 ---------------------------------------------------------------- ---------- P3RAW WAIT_CLASS_ID WAIT_CLASS# ---------------- ------------- ----------- WAIT_CLASS WAIT_TIME ---------------------------------------------------------------- ---------- SECONDS_IN_WAIT STATE WAIT_TIME_MICRO TIME_REMAINING_MICRO --------------- ------------------- --------------- -------------------- TIME_SINCE_LAST_WAIT_MICRO -------------------------- SERVICE_NAME SQL_TRAC SQL_T ---------------------------------------------------------------- -------- ----- SQL_T SQL_TRACE_ SESSION_EDITION_ID CREATOR_ADDR CREATOR_SERIAL# ----- ---------- ------------------ ---------------- --------------- ECID ---------------------------------------------------------------- SYS$USERS DISABLED FALSE SADDR SID SERIAL# AUDSID PADDR USER# ---------------- ---------- ---------- ---------- ---------------- ---------- USERNAME COMMAND OWNERID TADDR ------------------------------ ---------- ---------- ---------------- LOCKWAIT STATUS SERVER SCHEMA# SCHEMANAME ---------------- -------- --------- ---------- ------------------------------ OSUSER PROCESS ------------------------------ ------------------------ MACHINE PORT ---------------------------------------------------------------- ---------- TERMINAL ---------------- PROGRAM TYPE ---------------------------------------------------------------- ---------- SQL_ADDRESS SQL_HASH_VALUE SQL_ID SQL_CHILD_NUMBER SQL_EXEC_ ---------------- -------------- ------------- ---------------- --------- SQL_EXEC_ID PREV_SQL_ADDR PREV_HASH_VALUE PREV_SQL_ID PREV_CHILD_NUMBER ----------- ---------------- --------------- ------------- ----------------- PREV_EXEC PREV_EXEC_ID PLSQL_ENTRY_OBJECT_ID PLSQL_ENTRY_SUBPROGRAM_ID --------- ------------ --------------------- ------------------------- PLSQL_OBJECT_ID PLSQL_SUBPROGRAM_ID --------------- ------------------- MODULE MODULE_HASH ------------------------------------------------ ----------- ACTION ACTION_HASH -------------------------------- ----------- CLIENT_INFO ---------------------------------------------------------------- FIXED_TABLE_SEQUENCE ROW_WAIT_OBJ# ROW_WAIT_FILE# ROW_WAIT_BLOCK# ROW_WAIT_ROW# -------------------- ------------- -------------- --------------- ------------- TOP_LEVEL_CALL# LOGON_TIM LAST_CALL_ET PDM FAILOVER_TYPE FAILOVER_M FAI --------------- --------- ------------ --- ------------- ---------- --- RESOURCE_CONSUMER_GROUP PDML_STA PDDL_STA PQ_STATU -------------------------------- -------- -------- -------- CURRENT_QUEUE_DURATION ---------------------- CLIENT_IDENTIFIER BLOCKING_SE ---------------------------------------------------------------- ----------- BLOCKING_INSTANCE BLOCKING_SESSION FINAL_BLOCK FINAL_BLOCKING_INSTANCE ----------------- ---------------- ----------- ----------------------- FINAL_BLOCKING_SESSION SEQ# EVENT# ---------------------- ---------- ---------- EVENT ---------------------------------------------------------------- P1TEXT P1 ---------------------------------------------------------------- ---------- P1RAW ---------------- P2TEXT P2 ---------------------------------------------------------------- ---------- P2RAW ---------------- P3TEXT P3 ---------------------------------------------------------------- ---------- P3RAW WAIT_CLASS_ID WAIT_CLASS# ---------------- ------------- ----------- WAIT_CLASS WAIT_TIME ---------------------------------------------------------------- ---------- SECONDS_IN_WAIT STATE WAIT_TIME_MICRO TIME_REMAINING_MICRO --------------- ------------------- --------------- -------------------- TIME_SINCE_LAST_WAIT_MICRO -------------------------- SERVICE_NAME SQL_TRAC SQL_T ---------------------------------------------------------------- -------- ----- SQL_T SQL_TRACE_ SESSION_EDITION_ID CREATOR_ADDR CREATOR_SERIAL# ----- ---------- ------------------ ---------------- --------------- ECID ---------------------------------------------------------------- FALSE FIRST EXEC 0 000007FF5D4D8D70 2 SADDR SID SERIAL# AUDSID PADDR USER# ---------------- ---------- ---------- ---------- ---------------- ---------- USERNAME COMMAND OWNERID TADDR ------------------------------ ---------- ---------- ---------------- LOCKWAIT STATUS SERVER SCHEMA# SCHEMANAME ---------------- -------- --------- ---------- ------------------------------ OSUSER PROCESS ------------------------------ ------------------------ MACHINE PORT ---------------------------------------------------------------- ---------- TERMINAL ---------------- PROGRAM TYPE ---------------------------------------------------------------- ---------- SQL_ADDRESS SQL_HASH_VALUE SQL_ID SQL_CHILD_NUMBER SQL_EXEC_ ---------------- -------------- ------------- ---------------- --------- SQL_EXEC_ID PREV_SQL_ADDR PREV_HASH_VALUE PREV_SQL_ID PREV_CHILD_NUMBER ----------- ---------------- --------------- ------------- ----------------- PREV_EXEC PREV_EXEC_ID PLSQL_ENTRY_OBJECT_ID PLSQL_ENTRY_SUBPROGRAM_ID --------- ------------ --------------------- ------------------------- PLSQL_OBJECT_ID PLSQL_SUBPROGRAM_ID --------------- ------------------- MODULE MODULE_HASH ------------------------------------------------ ----------- ACTION ACTION_HASH -------------------------------- ----------- CLIENT_INFO ---------------------------------------------------------------- FIXED_TABLE_SEQUENCE ROW_WAIT_OBJ# ROW_WAIT_FILE# ROW_WAIT_BLOCK# ROW_WAIT_ROW# -------------------- ------------- -------------- --------------- ------------- TOP_LEVEL_CALL# LOGON_TIM LAST_CALL_ET PDM FAILOVER_TYPE FAILOVER_M FAI --------------- --------- ------------ --- ------------- ---------- --- RESOURCE_CONSUMER_GROUP PDML_STA PDDL_STA PQ_STATU -------------------------------- -------- -------- -------- CURRENT_QUEUE_DURATION ---------------------- CLIENT_IDENTIFIER BLOCKING_SE ---------------------------------------------------------------- ----------- BLOCKING_INSTANCE BLOCKING_SESSION FINAL_BLOCK FINAL_BLOCKING_INSTANCE ----------------- ---------------- ----------- ----------------------- FINAL_BLOCKING_SESSION SEQ# EVENT# ---------------------- ---------- ---------- EVENT ---------------------------------------------------------------- P1TEXT P1 ---------------------------------------------------------------- ---------- P1RAW ---------------- P2TEXT P2 ---------------------------------------------------------------- ---------- P2RAW ---------------- P3TEXT P3 ---------------------------------------------------------------- ---------- P3RAW WAIT_CLASS_ID WAIT_CLASS# ---------------- ------------- ----------- WAIT_CLASS WAIT_TIME ---------------------------------------------------------------- ---------- SECONDS_IN_WAIT STATE WAIT_TIME_MICRO TIME_REMAINING_MICRO --------------- ------------------- --------------- -------------------- TIME_SINCE_LAST_WAIT_MICRO -------------------------- SERVICE_NAME SQL_TRAC SQL_T ---------------------------------------------------------------- -------- ----- SQL_T SQL_TRACE_ SESSION_EDITION_ID CREATOR_ADDR CREATOR_SERIAL# ----- ---------- ------------------ ---------------- --------------- ECID ---------------------------------------------------------------- SADDR SID SERIAL# AUDSID PADDR USER# ---------------- ---------- ---------- ---------- ---------------- ---------- USERNAME COMMAND OWNERID TADDR ------------------------------ ---------- ---------- ---------------- LOCKWAIT STATUS SERVER SCHEMA# SCHEMANAME ---------------- -------- --------- ---------- ------------------------------ OSUSER PROCESS ------------------------------ ------------------------ MACHINE PORT ---------------------------------------------------------------- ---------- TERMINAL ---------------- PROGRAM TYPE ---------------------------------------------------------------- ---------- SQL_ADDRESS SQL_HASH_VALUE SQL_ID SQL_CHILD_NUMBER SQL_EXEC_ ---------------- -------------- ------------- ---------------- --------- SQL_EXEC_ID PREV_SQL_ADDR PREV_HASH_VALUE PREV_SQL_ID PREV_CHILD_NUMBER ----------- ---------------- --------------- ------------- ----------------- PREV_EXEC PREV_EXEC_ID PLSQL_ENTRY_OBJECT_ID PLSQL_ENTRY_SUBPROGRAM_ID --------- ------------ --------------------- ------------------------- PLSQL_OBJECT_ID PLSQL_SUBPROGRAM_ID --------------- ------------------- MODULE MODULE_HASH ------------------------------------------------ ----------- ACTION ACTION_HASH -------------------------------- ----------- CLIENT_INFO ---------------------------------------------------------------- FIXED_TABLE_SEQUENCE ROW_WAIT_OBJ# ROW_WAIT_FILE# ROW_WAIT_BLOCK# ROW_WAIT_ROW# -------------------- ------------- -------------- --------------- ------------- TOP_LEVEL_CALL# LOGON_TIM LAST_CALL_ET PDM FAILOVER_TYPE FAILOVER_M FAI --------------- --------- ------------ --- ------------- ---------- --- RESOURCE_CONSUMER_GROUP PDML_STA PDDL_STA PQ_STATU -------------------------------- -------- -------- -------- CURRENT_QUEUE_DURATION ---------------------- CLIENT_IDENTIFIER BLOCKING_SE ---------------------------------------------------------------- ----------- BLOCKING_INSTANCE BLOCKING_SESSION FINAL_BLOCK FINAL_BLOCKING_INSTANCE ----------------- ---------------- ----------- ----------------------- FINAL_BLOCKING_SESSION SEQ# EVENT# ---------------------- ---------- ---------- EVENT ---------------------------------------------------------------- P1TEXT P1 ---------------------------------------------------------------- ---------- P1RAW ---------------- P2TEXT P2 ---------------------------------------------------------------- ---------- P2RAW ---------------- P3TEXT P3 ---------------------------------------------------------------- ---------- P3RAW WAIT_CLASS_ID WAIT_CLASS# ---------------- ------------- ----------- WAIT_CLASS WAIT_TIME ---------------------------------------------------------------- ---------- SECONDS_IN_WAIT STATE WAIT_TIME_MICRO TIME_REMAINING_MICRO --------------- ------------------- --------------- -------------------- TIME_SINCE_LAST_WAIT_MICRO -------------------------- SERVICE_NAME SQL_TRAC SQL_T ---------------------------------------------------------------- -------- ----- SQL_T SQL_TRACE_ SESSION_EDITION_ID CREATOR_ADDR CREATOR_SERIAL# ----- ---------- ------------------ ---------------- --------------- ECID ---------------------------------------------------------------- 16 rows selected. SQL> desc dba_user; ERROR: ORA-04043: object dba_user does not exist SQL> desc dba_users; ERROR: ORA-04043: object dba_users does not exist SQL> desc v$user; ERROR: ORA-04043: object v$user does not exist SQL> desc v$users ERROR: ORA-04043: object v$users does not exist SQL> seleect * from dba_users; SP2-0734: unknown command beginning "seleect * ..." - rest of line ignored. SQL> select * from dba_users; select * from dba_users * ERROR at line 1: ORA-01219: database not open: queries allowed on fixed tables/views only SQL> alter database open; alter database open * ERROR at line 1: ORA-00600: internal error code, arguments: [kcratr_nab_less_than_odr], [1], [46], [32689], [32690], [], [], [], [], [], [], [] SQL> alter database mount; alter database mount * ERROR at line 1: ORA-01100: database already mounted SQL> alter database mount;

    Read the article

  • Box2d Cocos2d circle crash on contact with ground

    - by Oliver Cooper
    this is my first question here so sorry if I do something wrong or this is too long. I have been reading this tutorial by Ray Wenderlich, I have modified it so it is flatter and gradually goes down hill. Basically I have a ball roll down a bumpy hill, but at the moment the ball only drops from about 100 pixels above. When ever the touch the app crashes (the app is a Mac Cocos2d Box2d app). The ball code is this: CGSize winSize = [CCDirector sharedDirector].winSize; self.oeva = [CCSprite spriteWithTexture:[[CCTextureCache sharedTextureCache] addImage:@"Ball.png"]rect:CGRectMake(0, 0, 64, 64)]; _oeva.position = CGPointMake(68, winSize.height/2); [self addChild:_oeva z:1]; b2BodyDef oevaBodyDef; oevaBodyDef.type = b2_dynamicBody; oevaBodyDef.position.Set(68/PTM_RATIO, (winSize.height/2)/PTM_RATIO); // oevaBodyDef.userData = _oeva; _oevaBody = world->CreateBody(&oevaBodyDef); b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; bodyDef.position.Set(60/PTM_RATIO, 400/PTM_RATIO); bodyDef.userData = _oeva; b2Body *body = world->CreateBody(&bodyDef); // Define another box shape for our dynamic body. b2CircleShape dynamicBox; dynamicBox.m_radius = 70/PTM_RATIO;//These are mid points for our 1m box // Define the dynamic body fixture. b2FixtureDef fixtureDef; fixtureDef.shape = &dynamicBox; fixtureDef.density = 1.0f; fixtureDef.friction = 0.3f; body->CreateFixture(&fixtureDef); That works fine. This is the terrain code, this also works fine: -(void)generateTerrainWithWorld: (b2World *) inputWorld: (int) hillSize;{ b2BodyDef bd; bd.position.Set(0, 0); body = inputWorld->CreateBody(&bd); b2PolygonShape shape; b2FixtureDef fixtureDef; currentSlope = 0; CGSize winSize = [CCDirector sharedDirector].winSize; float xf = 0; float yf = (arc4random() % 10)+winSize.height/3; int x = 200; for(int i = 0; i < maxHillPoints; ++i) { hillPoints[i] = CGPointMake(xf, yf); xf = xf+ (arc4random() % x/2)+x/2; yf = ((arc4random() % 30)+winSize.height/3)-currentSlope; currentSlope +=10; } int hSegments; for (int i=0; i<maxHillPoints-1; i++) { CGPoint p0 = hillPoints[i-1]; CGPoint p1 = hillPoints[i]; hSegments = floorf((p1.x-p0.x)/cosineSegmentWidth); float dx = (p1.x - p0.x) / hSegments; float da = M_PI / hSegments; float ymid = (p0.y + p1.y) / 2; float ampl = (p0.y - p1.y) / 2; CGPoint pt0, pt1; pt0 = p0; for (int j = 0; j < hSegments+1; ++j) { pt1.x = p0.x + j*dx; pt1.y = ymid + ampl * cosf(da*j); fullHillPoints[fullHillPointsCount++] = pt1; pt0 = pt1; } } b2Vec2 p1v, p2v; for (int i=0; i<fullHillPointsCount-1; i++) { p1v = b2Vec2(fullHillPoints[i].x/PTM_RATIO,fullHillPoints[i].y/PTM_RATIO); p2v = b2Vec2(fullHillPoints[i+1].x/PTM_RATIO,fullHillPoints[i+1].y/PTM_RATIO); shape.SetAsEdge(p1v, p2v); body->CreateFixture(&shape, 0); } } However when ever the two collide the app crashes. The crash error is: Thread 6 CVDisplayLink: Program received signal: "SIGABRT" The error occurs on line 96 of b2ContactSolver.cpp: b2Assert(kNormal > b2_epsilon); The error log is: Assertion failed: (kNormal 1.19209290e-7F), function b2ContactSolver, file /Users/coooli01/Documents/Xcode Projects/Cocos2d/Hill Slide/Hill Slide/libs/Box2D/Dynamics/Contacts/b2ContactSolver.cpp, line 96. Sorry if I rambled on for too long, i've been stuck on this for ages.

    Read the article

  • CoreData: Same predicate (IN) returns different fetched results after a Save operation

    - by Jason Lee
    I have code below: NSArray *existedTasks = [[TaskBizDB sharedInstance] fetchTasksWatchedByMeOfProject:projectId]; [context save:&error]; existedTasks = [[TaskBizDB sharedInstance] fetchTasksWatchedByMeOfProject:projectId]; NSArray *allTasks = [[TaskBizDB sharedInstance] fetchTasksOfProject:projectId]; First line returns two objects; Second line save the context; Third line returns just one object, which is contained in the 'two objects' above; And the last line returns 6 objects, containing the 'two objects' returned at the first line. The fetch interface works like below: WXModel *model = [WXModel modelWithEntity:NSStringFromClass([WQPKTeamTask class])]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%@ IN personWatchers) AND (projectId == %d)", currentLoginUser, projectId]; [model setPredicate:predicate]; NSArray *fetchedTasks = [model fetch]; if (fetchedTasks.count == 0) return nil; return fetchedTasks; What confused me is that, with the same fetch request, why return different results just after a save? Here comes more detail: The 'two objects' returned at the first line are: <WQPKTeamTask: 0x1b92fcc0> (entity: WQPKTeamTask; id: 0x1b9300f0 <x-coredata://CFFD3F8B-E613-4DE8-85AA-4D6DD08E88C5/WQPKTeamTask/p9> ; data: { projectId = 372004; taskId = 338001; personWatchers = ( "0xf0bf440 <x-coredata://CFFD3F8B-E613-4DE8-85AA-4D6DD08E88C5/WWPerson/p1>" ); } <WQPKTeamTask: 0xf3f6130> (entity: WQPKTeamTask; id: 0xf3cb8d0 <x-coredata://CFFD3F8B-E613-4DE8-85AA-4D6DD08E88C5/WQPKTeamTask/p11> ; data: { projectId = 372004; taskId = 340006; personWatchers = ( "0xf0bf440 <x-coredata://CFFD3F8B-E613-4DE8-85AA-4D6DD08E88C5/WWPerson/p1>" ); } And the only one object returned at third line is: <WQPKTeamTask: 0x1b92fcc0> (entity: WQPKTeamTask; id: 0x1b9300f0 <x-coredata://CFFD3F8B-E613-4DE8-85AA-4D6DD08E88C5/WQPKTeamTask/p9> ; data: { projectId = 372004; taskId = 338001; personWatchers = ( "0xf0bf440 <x-coredata://CFFD3F8B-E613-4DE8-85AA-4D6DD08E88C5/WWPerson/p1>" ); } Printing description of allTasks: <_PFArray 0xf30b9a0>( <WQPKTeamTask: 0xf3ab9d0> (entity: WQPKTeamTask; id: 0xf3cda40 <x-coredata://CFFD3F8B-E613-4DE8-85AA-4D6DD08E88C5/WQPKTeamTask/p6> ; data: <fault>), <WQPKTeamTask: 0xf315720> (entity: WQPKTeamTask; id: 0xf3c23a0 <x-coredata://CFFD3F8B-E613-4DE8-85AA-4D6DD08E88C5/WQPKTeamTask/p7> ; data: <fault>), <WQPKTeamTask: 0xf3a1ed0> (entity: WQPKTeamTask; id: 0xf3cda30 <x-coredata://CFFD3F8B-E613-4DE8-85AA-4D6DD08E88C5/WQPKTeamTask/p8> ; data: <fault>), <WQPKTeamTask: 0x1b92fcc0> (entity: WQPKTeamTask; id: 0x1b9300f0 <x-coredata://CFFD3F8B-E613-4DE8-85AA-4D6DD08E88C5/WQPKTeamTask/p9> ; data: { projectId = 372004; taskId = 338001; personWatchers = ( "0xf0bf440 <x-coredata://CFFD3F8B-E613-4DE8-85AA-4D6DD08E88C5/WWPerson/p1>" ); }), <WQPKTeamTask: 0xf325e50> (entity: WQPKTeamTask; id: 0xf343820 <x-coredata://CFFD3F8B-E613-4DE8-85AA-4D6DD08E88C5/WQPKTeamTask/p10> ; data: <fault>), <WQPKTeamTask: 0xf3f6130> (entity: WQPKTeamTask; id: 0xf3cb8d0 <x-coredata://CFFD3F8B-E613-4DE8-85AA-4D6DD08E88C5/WQPKTeamTask/p11> ; data: { projectId = 372004; taskId = 340006; personWatchers = ( "0xf0bf440 <x-coredata://CFFD3F8B-E613-4DE8-85AA-4D6DD08E88C5/WWPerson/p1>" ); }) ) UPDATE 1 If I call the same interface fetchTasksWatchedByMeOfProject: in: #pragma mark - NSFetchedResultsController Delegate - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller { I will get 'two objects' as well. UPDATE 2 I've tried: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(ANY personWatchers == %@) AND (projectId == %d)", currentLoginUser, projectId]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(ANY personWatchers.personId == %@) AND (projectId == %d)", currentLoginUserId, projectId]; Still the same result. UPDATE 3 I've checked the save:&error, error is nil.

    Read the article

  • how can we generate the bit greater than 60000?

    - by thinthinyu
    we can now generate about 50000bits. my code cannot generate more than 60000 bit..please help me............m_B is member variable and type is CString. // LFSR_ECDlg.cpp : implementation file // #include "stdafx.h" #include "myecc.h" #include "LFSR_ECDlg.h" #include "MyClass.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern MyClass mycrv; ///////////////////////////////////////////////////////////////////////////// // LFSR_ECDlg dialog LFSR_ECDlg::LFSR_ECDlg(CWnd* pParent /*=NULL*/) : CDialog(LFSR_ECDlg::IDD, pParent) { //{{AFX_DATA_INIT(LFSR_ECDlg) m_C1 = 0; m_C2 = 0; m_B = _T(""); m_p = _T(""); m_Qty = 0; m_time = _T(""); //}}AFX_DATA_INIT } void LFSR_ECDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(LFSR_ECDlg) DDX_Text(pDX, IDC_C1, m_C1); DDX_Text(pDX, IDC_C2, m_C2); DDX_Text(pDX, IDC_Sequence, m_B); DDX_Text(pDX, IDC_Sequence2, m_p); DDX_Text(pDX, IDC_QTY, m_Qty); DDV_MinMaxLong(pDX, m_Qty, 0, 2147483647); DDX_Text(pDX, IDC_time, m_time); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(LFSR_ECDlg, CDialog) //{{AFX_MSG_MAP(LFSR_ECDlg) ON_WM_SETCURSOR() ON_EN_CHANGE(IDC_Sequence, OnGeneratorLFSR) ON_MESSAGE(WM_MYPAINTMESSAGE,PaintMyCaption)//by ttyu ON_BN_CLICKED(IDC_save, Onsave) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // LFSR_ECDlg message handlers bool LFSR_ECDlg::CheckDataEntry() { //if((m_Px>=mycrv.p)|(m_Py>=mycrv.p)) {AfxMessageBox("Seed [P] is invalid!");return false;}//by ttyu if((m_C1<=0) | (m_C1>mycrv.n)) {AfxMessageBox("Constant c1 is not valid!");return false;} if((m_C2<=0 )| (m_C2>mycrv.n)) {AfxMessageBox("Constant c2 is not valid!");return false;} return true; } void LFSR_ECDlg::OnOK() { UpdateData(true); static int stime,etime,dtime; CString txt; m_time=""; CTime t(CTime::GetCurrentTime()); CString txt1; txt1=""; //ms = t.GetDay(); // TODO: Add extra validation here stime=t.GetTime(); txt1.Format("%d",stime); AfxMessageBox (txt1); txt=""; if (CheckDataEntry()) OnGeneratorLFSR(); etime=t.GetTime(); CString txt2; txt2=""; txt2.Format("%d",etime); AfxMessageBox (txt2); dtime=etime-stime; txt.Format("%f",dtime); m_time+=txt; // UpdateData(false); //rtime.Format("%s, %s %d, %d.",day,month,dd,yy); //CDialog::OnOK(); } void LFSR_ECDlg::OnCancel() { // TODO: Add extra cleanup here CDialog::OnCancel(); } void LFSR_ECDlg::OnGeneratorLFSR() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here point P0,P1,P2; P0 = mycrv.G; P1 = mycrv.MulPoint(P0,2); int C1=m_C1, C2=m_C2, n=m_Qty, k=0; int q= (mycrv.p-1) / 2; m_p = ""; m_B = ""; CString txt; for(int i=0;i<n;i++) { txt=""; if(P0==mycrv.O) txt.Format("O"); else txt.Format("(%d, %d)",P0.x,P0.y); m_p +=txt; m_p += 13; m_p += 10; if((P0.y >= 0)&&(P0.y <= q)) m_B += "0"; else if(P0 == mycrv.O) m_B += "0"; else m_B += "1"; //m_B += 13;//by ttyu // m_B += 10;//by ttyu P2 = mycrv.AddPoints(mycrv.MulPoint(P1,C2), mycrv.MulPoint(P0,C1)); P0 = P1; P1 = P2; } } BOOL LFSR_ECDlg::OnInitDialog() { CDialog::OnInitDialog(); // TODO: Add extra initialization here //code for dlg bar CString str="LFSR_EC"; m_cap.SetCaption (str); m_cap.Install (this,WM_MYPAINTMESSAGE); ////////////////////////////// return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } LRESULT LFSR_ECDlg::PaintMyCaption(WPARAM wp, LPARAM lp) { m_cap.PaintCaption(wp,lp); return 0; } BOOL LFSR_ECDlg::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { // TODO: Add your message handler code here and/or call default return CDialog::OnSetCursor(pWnd, nHitTest, message); } void LFSR_ECDlg::Onsave() { this->UpdateData(); CFile bitstream; char strFilter[] = { "Stream Records (*.mpl)|*.mpl| (*.pis)|*.pis|All Files (*.*)|*.*||" }; CFileDialog FileDlg(FALSE, ".mpl", NULL, 0, strFilter); //insertion//by TTT CFile cf_object; if( FileDlg.DoModal() == IDOK ){ cf_object.Open( FileDlg.GetFileName(), CFile::modeCreate|CFile::modeWrite); //char szText[100]; //strcpy(szText, "File Write Test"); CString txt; txt=""; txt.Format("%s",m_B);//by ANO AfxMessageBox (txt);//by ANO int mB_size=m_B.GetLength(); cf_object.Write (m_B,mB_size); //insertion end /* if( FileDlg.DoModal() == IDOK ) { if( bitstream.Open(FileDlg.GetFileName(), CFile::modeCreate | CFile::modeWrite) == FALSE ) return; CArchive ar(&bitstream, CArchive::store); CString txt; txt=""; txt.Format("%s",m_B);//by ANO AfxMessageBox (txt);//by ANO //txt=m_B;//by ANO ar <<txt;//by ANO ar.Close(); } else return; bitstream.Close(); */ // TODO: Add your control notification handler code here } }

    Read the article

  • Using the latest (stable release) of Oracle Developer Tools for Visual Studio 11.1.0.7.20.

    - by mbcrump
    +  = Simple and safe Data connections.   This guide is for someone wanting to use the latest ODP.NET quickly without reading the official documentation. This guide will get you up and running in about 15 minutes. I have reviewed my referral link to my simple Setting up ODP.net with Win7 x64 and noticed most people were searching for one of the following terms: “how to use odp.net with vs” “setup connection odp.net” “query db using odp and vs” While my article provided links and a sample tnsnames.ora file, it really didn’t tell you how to use it. I’m hoping that this brief tutorial will help. So before we get started, you will need the following: Download the following: www.oracle.com/technology/software/tech/dotnet/utilsoft.html from oracle and install it. It is the first one on the page. Visual Studio 2008 or 2010. It should be noted that The System.Data.OracleClient namespace is the OLD .NET Framework Data Provider for Oracle. It should not be used anymore as it has been depreciated. The latest version which is what we are using is Oracle.DataAccess.Client. First things first, Add a reference to the Oracle.DataAccess.Client after you install ODP.NET   Copy and paste the following C# code into your project and replace the relevant info including the query string and you should be able to return data. I have commented several lines of code to assist in understanding what it is doing.   Lambda Expression. using System; using System.Data; using Oracle.DataAccess.Client;   namespace ConsoleApplication1 {     class Program     {         static void Main(string[] args)         {           try         {             //Setup DataSource             string oradb = "Data Source=(DESCRIPTION ="                                    + "(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = hostname)(PORT = 1521)))"                                    + "(CONNECT_DATA = (SERVICE_NAME = SERVICENAME))) ;"                                    + "Persist Security Info=True;User ID=USER;Password=PASSWORD;";                        //Open Connection to Oracle - this could be moved outside the try.             OracleConnection conn = new OracleConnection(oradb);             conn.Open();               //Create cmd and use parameters to prevent SQL injection attacks.             OracleCommand cmd = new OracleCommand();             cmd.Connection = conn;               cmd.CommandText = "select username from table where username = :username";               OracleParameter p1 = new OracleParameter("username", OracleDbType.Varchar2);             p1.Value = username;             cmd.Parameters.Add(p1);               cmd.CommandType = CommandType.Text;               OracleDataReader dr = cmd.ExecuteReader();             dr.Read();               //Contains the value of the datarow             Console.WriteLine(dr["username"].ToString());               //Disposes of objects.             dr.Dispose();             cmd.Dispose();             conn.Dispose();         }           catch (OracleException ex) // Catches only Oracle errors         {             switch (ex.Number)             {                 case 1:                     Console.WriteLine("Error attempting to insert duplicate data.");                     break;                 case 12545:                     Console.WriteLine("The database is unavailable.");                     break;                 default:                     Console.WriteLine(ex.Message.ToString());                     break;             }         }           catch (Exception ex) // Catches any error not previously caught         {                   Console.WriteLine("Unidentified Error: " + ex.Message.ToString());              }         }       }           } At this point, you should have a working Program that returns data from an oracle database. If you are still having trouble then drop me a line and I will be happy to assist. As of this writing, oracle has announced the latest beta release of ODP.NET 11.2.0.1.1 Beta.  This release includes .NET Framework 4 and .NET Framework 4 Client Profile support. You may want to hold off on this version for a while as its BETA, and I wouldn’t want any production code using any BETA software.

    Read the article

  • Numerically stable(ish) method of getting Y-intercept of mouse position?

    - by Fraser
    I'm trying to unproject the mouse position to get the position on the X-Z plane of a ray cast from the mouse. The camera is fully controllable by the user. Right now, the algorithm I'm using is... Unproject the mouse into the camera to get the ray: Vector3 p1 = Vector3.Unproject(new Vector3(x, y, 0), 0, 0, width, height, nearPlane, farPlane, viewProj; Vector3 p2 = Vector3.Unproject(new Vector3(x, y, 1), 0, 0, width, height, nearPlane, farPlane, viewProj); Vector3 dir = p2 - p1; dir.Normalize(); Ray ray = Ray(p1, dir); Then get the Y-intercept by using algebra: float t = -ray.Position.Y / ray.Direction.Y; Vector3 p = ray.Position + t * ray.Direction; The problem is that the projected position is "jumpy". As I make small adjustments to the mouse position, the projected point moves in strange ways. For example, if I move the mouse one pixel up, it will sometimes move the projected position down, but when I move it a second pixel, the project position will jump back to the mouse's location. The projected location is always close to where it should be, but it does not smoothly follow a moving mouse. The problem intensifies as I zoom the camera out. I believe the problem is caused by numeric instability. I can make minor improvements to this by doing some computations at double precision, and possibly abusing the fact that floating point calculations are done at 80-bit precision on x86, however before I start micro-optimizing this and getting deep into how the CLR handles floating point, I was wondering if there's an algorithmic change I can do to improve this? EDIT: A little snooping around in .NET Reflector on SlimDX.dll: public static Vector3 Unproject(Vector3 vector, float x, float y, float width, float height, float minZ, float maxZ, Matrix worldViewProjection) { Vector3 coordinate = new Vector3(); Matrix result = new Matrix(); Matrix.Invert(ref worldViewProjection, out result); coordinate.X = (float) ((((vector.X - x) / ((double) width)) * 2.0) - 1.0); coordinate.Y = (float) -((((vector.Y - y) / ((double) height)) * 2.0) - 1.0); coordinate.Z = (vector.Z - minZ) / (maxZ - minZ); TransformCoordinate(ref coordinate, ref result, out coordinate); return coordinate; } // ... public static void TransformCoordinate(ref Vector3 coordinate, ref Matrix transformation, out Vector3 result) { Vector3 vector; Vector4 vector2 = new Vector4 { X = (((coordinate.Y * transformation.M21) + (coordinate.X * transformation.M11)) + (coordinate.Z * transformation.M31)) + transformation.M41, Y = (((coordinate.Y * transformation.M22) + (coordinate.X * transformation.M12)) + (coordinate.Z * transformation.M32)) + transformation.M42, Z = (((coordinate.Y * transformation.M23) + (coordinate.X * transformation.M13)) + (coordinate.Z * transformation.M33)) + transformation.M43 }; float num = (float) (1.0 / ((((transformation.M24 * coordinate.Y) + (transformation.M14 * coordinate.X)) + (coordinate.Z * transformation.M34)) + transformation.M44)); vector2.W = num; vector.X = vector2.X * num; vector.Y = vector2.Y * num; vector.Z = vector2.Z * num; result = vector; } ...which seems to be a pretty standard method of unprojecting a point from a projection matrix, however this serves to introduce another point of possible instability. Still, I'd like to stick with the SlimDX Unproject routine rather than writing my own unless it's really necessary.

    Read the article

  • How to use Application Verifier to find memory leaks

    - by Patrick
    I want to find memory leaks in my application using standard utilities. Previously I used my own memory allocator, but other people (yes, you Neil) suggested to use Microsoft's Application Verifier, but I can't seem to get it to report my leaks. I have the following simple application: #include <iostream> #include <conio.h> class X { public: X::X() : m_value(123) {} private: int m_value; }; void main() { X *p1 = 0; X *p2 = 0; X *p3 = 0; p1 = new X(); p2 = new X(); p3 = new X(); delete p1; delete p3; } This test clearly contains a memory leak: p2 is new'd but not deleted. I build the executable using the following command lines: cl /c /EHsc /Zi /Od /MDd test.cpp link /debug test.obj I downloaded Application Verifier (4.0.0665) and enabled all checks. If I now run my test application I can see a log of it in Application Verifier, but I don't see the memory leak. Questions: Why doesn't Application Verifier report a leak? Or isn't Application Verifier really intended to find leaks? If it isn't which other tools are available to clearly report leaks at the end of the application (i.e. not by taking regular snapshots and comparing them since this is not possible in an application taking 1GB or more), including the call stack of the place of allocation (so not the simple leak reporting at the end of the CRT) If I don't find a decent utility, I still have to rely on my own memory manager (which does it perfectly).

    Read the article

  • How to use Parcel in Android?

    - by Mike
    I'm trying to use Parcel to write and then read back a Parcelable. For some reason, when I read the object back from the file, it's coming back as null. public void testFoo() { final Foo orig = new Foo("blah blah"); // Wrote orig to a parcel and then byte array final Parcel p1 = Parcel.obtain(); p1.writeValue(orig); final byte[] bytes = p1.marshall(); // Check to make sure that the byte array seems to contain a Parcelable assertEquals(4, bytes[0]); // Parcel.VAL_PARCELABLE // Unmarshall a Foo from that byte array final Parcel p2 = Parcel.obtain(); p2.unmarshall(bytes, 0, bytes.length); final Foo result = (Foo) p2.readValue(Foo.class.getClassLoader()); assertNotNull(result); // FAIL assertEquals( orig.str, result.str ); } protected static class Foo implements Parcelable { protected static final Parcelable.Creator<Foo> CREATOR = new Parcelable.Creator<Foo>() { public Foo createFromParcel(Parcel source) { final Foo f = new Foo(); f.str = (String) source.readValue(Foo.class.getClassLoader()); return f; } public Foo[] newArray(int size) { throw new UnsupportedOperationException(); } }; public String str; public Foo() { } public Foo( String s ) { str = s; } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int ignored) { dest.writeValue(str); } } What am I missing? UPDATE: To simplify the test I've removed the reading and writing of files in my original example.

    Read the article

  • jQuery plugin for Event Driven Architecture?

    - by leeand00
    Are there any Event Driven Architecture jQuery plugins? Step 1: Subscribing The subscribers subscribe to the event handler in the middle, and pass in a callback method, as well as the name of the event they are listening for... i.e. The two green subscribers will be listening for p0 events. And the blue subscriber will be listening for p1 events. Step 2: The p0 event is fired by another component to the Event Handler A p0 event is fired to the Event Handler The event handler notifies it's subscribers of the event, calling the callback methods they specified when they subscribed in Step 1: Subscribing. Note that the blue subscriber is not notified because it was not listening for p0 events. Step 3: The p1 event is fired a component to the Event Handler The p1 event is fired by another component Just as before except that now the blue subscriber receives the event through its callback and the other two green subscribers do not receive the event. Images by leeand00, on Flickr I can't seem to find one, but my guess is that they just call it something else in Javascript/jquery Also is there a name for this pattern? Because it isn't just a basic publisher/subscriber, it has to be called something else I would think.

    Read the article

  • Concatenate row values T-SQL

    - by Robert
    I am trying to pull together some data for a report and need to concatenate the row values of one of the tables. Here is the basic table structure: Reviews ReviewID ReviewDate Reviewers ReviewerID ReviewID UserID Users UserID FName LName This is a M:M relationship. Each Review can have many Reviewers; each User can be associated with many Reviews. Basically, all I want to see is Reviews.ReviewID, Reviews.ReviewDate, and a concatenated string of the FName's of all the associated Users for that Review (comma delimited). Instead of: ReviewID---ReviewDate---User 1----------12/1/2009----Bob 1----------12/1/2009----Joe 1----------12/1/2009----Frank 2----------12/9/2009----Sue 2----------12/9/2009----Alice Display this: ReviewID---ReviewDate----Users 1----------12/1/2009-----Bob, Joe, Frank 2----------12/9/2009-----Sue, Alice I have found this article describing some ways to do this, but most of these seem to only deal with one table, not multiple; unfortunately, my SQL-fu is not strong enough to adapt these to my circumstances. I am particularly interested in the example on that site which utilizes FOR XML PATH() as that looks the cleanest and most straight forward. SELECT p1.CategoryId, ( SELECT ProductName + ', ' FROM Northwind.dbo.Products p2 WHERE p2.CategoryId = p1.CategoryId ORDER BY ProductName FOR XML PATH('') ) AS Products FROM Northwind.dbo.Products p1 GROUP BY CategoryId; Can anyone give me a hand with this? Any help would be greatly appreciated!

    Read the article

  • This is more a matlab/math brain teaser than a question

    - by gd047
    Here is the setup. No assumptions for the values I am using. n=2; % dimension of vectors x and (square) matrix P r=2; % number of x vectors and P matrices x1 = [3;5] x2 = [9;6] x = cat(2,x1,x2) P1 = [6,11;15,-1] P2 = [2,21;-2,3] P(:,1)=P1(:) P(:,2)=P2(:) modePr = [-.4;16] TransPr=[5.9,0.1;20.2,-4.8] pred_modePr = TransPr'*modePr MixPr = TransPr.*(modePr*(pred_modePr.^(-1))') x0 = x*MixPr Then it was time to apply the following formula to get myP , where µij is MixPr. I used this code to get it: myP=zeros(n*n,r); Ptables(:,:,1)=P1; Ptables(:,:,2)=P2; for j=1:r for i = 1:r; temp = MixPr(i,j)*(Ptables(:,:,i) + ... (x(:,i)-x0(:,j))*(x(:,i)-x0(:,j))'); myP(:,j)= myP(:,j) + temp(:); end end Some brilliant guy proposed this formula as another way to produce myP for j=1:r xk1=x(:,j); PP=xk1*xk1'; PP0(:,j)=PP(:); xk1=x0(:,j); PP=xk1*xk1'; PP1(:,j)=PP(:); end myP = (P+PP0)*MixPr-PP1 I tried to formulate the equality between the two methods and seems to be this one. To make things easier, I ignored from both methods the summation of matrix P. where the first part denotes the formula that I used, while the second comes from his code snippet. Do you think this is an obvious equality? If yes, ignore all the above and just try to explain why. I could only start from the LHS, and after some algebra I think I proved it equals to the RHS. However I can't see how did he (or she) think of it in the first place.

    Read the article

  • Can't write the SysWow64 value to registry with vbscript for Screensaver

    - by Valentein
    Scripts, registries, screen-savers, oh my! I'm trying to use a screen-saver on a Windows XP 64 bit machine which uses a .NET app which makes an interop call which relies on some x86 Shockwave Dlls (some Shockwave animation). Everything should be in the %systemroot%\WINNT\SysWOW64 directory. When the timeout for the screensaver occurs, the process should looks like this: Screensaver.scr - .NET app - shockwave animation. During installation I want a vbscript to my screen-saver file to copy the Screensaver.scr to the SysWow64 directory and then set the proper registry key to this file for Windows to launch the screen-saver. The code is something like this: Dim sScreenSaver, tScreenSaver sScreenSaver = "C:\SourceFiles\bin\ScreenSaver.scr" 'screensaver tScreenSaver = "C:\winnt\SysWOW64\" Set WshShell = WScript.CreateObject("WScript.Shell") 'script shell to run objects Set FSO = createobject("scripting.filesystemobject") 'file system object 'copy screensaver FSO.CopyFile sScreenSaver, tScreenSaver, True 'set screen saver Dim p1 p1 = "HKEY_CURRENT_USER\Control Panel\Desktop\" WshShell.RegWrite p1 & "SCRNSAVE.EXE", (tScreenSaver & "ScreenSaver.scr") After installation, I can verify the the Screensaver exists in the correct directory. (It actually seems to be in both the system32 and the sysWOW64 directories---whether that's the install script or something I did post-install I'm in the process of verifying.) However, the registry entry is not correct. In both the 32 and 64 bit regedit I see the HKCU\ControlPanel\Desktop\SCRNSAVE.EX is set to: C:\WINNT\system32\Screensaver.scr This isn't right. The screen-saver won't run from this directory. It only runs from SysWOW64. If I manually edit the registry with regedit to the correct SysWOW64 path everything works fine. Is this a problem with using the script or is this a Windows registry redirection, or filesystem redirection problem? You'd think this would be simple...

    Read the article

  • Does anyone know how to detect whether a Windows Service is running through Java

    - by GKelly
    There's plenty of information on running Java apps as services, but I need to know how to detect whether a windows service is running or not. Does anyone know how??? At the DOS prompt, I can run: tasklist /svc|findstr "NonRunningService" echo Return code for N onRunningService is %ERRORLEVEL% tasklist /svc|findstr "RunningService" echo Return code for RunningService is %ERRORLEVEL% I get the following: Return code for NonRunningService is 1 Return code for RunningService is 0 In code, I have: int retCode = Runtime.getRuntime.exec("tasklist /svc|findstr \"NonRunningService\"").waitFor(); System.out.println("Return code for NonRunningService is " + retCode); retCode = Runtime.getRuntime.exec("tasklist /svc|findstr \"RunningService\"").waitFor(); System.out.println("Return code for RunningService is " + retCode); I get the following output Return code for NonRunningService is 1 Return code for RunningService is 1 According to the JavaDocs, the waitFor() should block until the process finishes, and give me the exit value of the process. I've also tried using the Process/ProcessBuilder command line calls: //'tasklist /nh /fi "SERVICES eq RunningService"' will return a line for // each running service of the requested type. Process p1 = new ProcessBuilder("tasklist", "/nh", "/fi" "SERVICES eq RunningService").start(); p1.waitFor(); BufferedReader is = new BufferedReader(new InputStreamReader(p1.getInputStream())); String line = is.readLine(); System.out.println("Service - " + line); System.out.println("Running? ", (line==null?"No":"Yes"); gives: Service - Running? No even when I get lines in the output at the command line!

    Read the article

  • Procedure or function AppendDataCT has too many arguments specified

    - by salvationishere
    I am developing a C# VS 2008 / SQL Server website application. I am a newbie to ASP.NET. I am getting the above compiler error. Can you give me advice on how to fix this? Code snippet: public static string AppendDataCT(DataTable dt, Dictionary<int, string> dic) { string connString = ConfigurationManager.ConnectionStrings["AW3_string"].ConnectionString; string errorMsg; try { SqlConnection conn2 = new SqlConnection(connString); SqlCommand cmd = conn2.CreateCommand(); cmd.CommandText = "dbo.AppendDataCT"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = conn2; SqlParameter p1, p2, p3; foreach (string s in dt.Rows[1].ItemArray) { DataRow dr = dt.Rows[1]; // second row p1 = cmd.Parameters.AddWithValue((string)dic[0], (string)dr[0]); p1.SqlDbType = SqlDbType.VarChar; p2 = cmd.Parameters.AddWithValue((string)dic[1], (string)dr[1]); p2.SqlDbType = SqlDbType.VarChar; p3 = cmd.Parameters.AddWithValue((string)dic[2], (string)dr[2]); p3.SqlDbType = SqlDbType.VarChar; } conn2.Open(); cmd.ExecuteNonQuery(); It errors on this last line here. And here is that SP: ALTER PROCEDURE [dbo].[AppendDataCT] @col1 VARCHAR(50), @col2 VARCHAR(50), @col3 VARCHAR(50) AS BEGIN SET NOCOUNT ON; DECLARE @TEMP DATETIME SET @TEMP = (SELECT CONVERT (DATETIME, @col3)) INSERT INTO Person.ContactType (Name, ModifiedDate) VALUES( @col2, @TEMP) END

    Read the article

  • Cache consistency & spawning a thread

    - by Dave Keck
    Background I've been reading through various books and articles to learn about processor caches, cache consistency, and memory barriers in the context of concurrent execution. So far though, I have been unable to determine whether a common coding practice of mine is safe in the strictest sense. Assumptions The following pseudo-code is executed on a two-processor machine: int sharedVar = 0; myThread() { print(sharedVar); } main() { sharedVar = 1; spawnThread(myThread); sleep(-1); } main() executes on processor 1 (P1), while myThread() executes on P2. Initially, sharedVar exists in the caches of both P1 and P2 with the initial value of 0 (due to some "warm-up code" that isn't shown above.) Question Strictly speaking – preferably without assuming any particular CPU – is myThread() guaranteed to print 1? With my newfound knowledge of processor caches, it seems entirely possible that at the time of the print() statement, P2 may not have received the invalidation request for sharedVar caused by P1's assignment in main(). Therefore, it seems possible that myThread() could print 0. References These are the related articles and books I've been reading. (It wouldn't allow me to format these as links because I'm a new user - sorry.) Shared Memory Consistency Models: A Tutorial hpl.hp.com/techreports/Compaq-DEC/WRL-95-7.pdf Memory Barriers: a Hardware View for Software Hackers rdrop.com/users/paulmck/scalability/paper/whymb.2009.04.05a.pdf Linux Kernel Memory Barriers kernel.org/doc/Documentation/memory-barriers.txt Computer Architecture: A Quantitative Approach amazon.com/Computer-Architecture-Quantitative-Approach-4th/dp/0123704901/ref=dp_ob_title_bk

    Read the article

  • Can this code be further optimized??

    - by kaki
    i understand that the code given below will not be compltely understood unless i explain my whole of previous and next lines of code. But this is part of the code which is causing so much of delay in my project and want to optimize this. i want to know which code part is faulty and how could this be replaced. i guess,few can say that use of this function is heavy compared and other ligher method are available to do this work please help, thanks in advance for i in range(len(lists)): save=database_index[lists[i]] #print save #if save[1]!='text0194'and save[1]!='text0526': using_data[save[0]]=save p=os.path.join("c:/begpython/wavnk/",str(str(str(save[1]).replace('phone','text'))+'.pm')) x1=open(p , 'r') x2=open(p ,'r') for i in range(6): x1.readline() x2.readline() gen = (float(line.partition(' ')[0]) for line in x1) r= min(enumerate(gen), key=lambda x: abs(x[1] - float(save[4]))) #print r[0] a1=linecache.getline(str(str(p).replace('.pm','.mcep')), (r[0]+1)) #print a1 p1=str(str(a1).rstrip('\n')).split(' ') #print p1 join_cost_index_end[save[0]]=p1 #print join_cost_index_end gen = (float(line.partition(' ')[0]) for line in x2) r= min(enumerate(gen), key=lambda x: abs(x[1] - float(save[3]))) #print r[0] a2=linecache.getline(str(str(p).replace('.pm','.mcep')), (r[0]+1)) #print a2 p2=str(str(a2).rstrip('\n')).split(' ') #print p2 join_cost_index_strt[save[0]]=p2 #print join_cost_index_strt j=j+1 #print j #print join_cost_index_end #print join_cost_index_strt enter code here here my database_index has about 2,50,000 entries`

    Read the article

  • C#- move a shape to a point which is half way from the top of the form

    - by hello-all
    Hello all, Here I have to create a diamond using drawlines method and make it move horizontally along a path that is half way from the top of the form. I created a diamond and it is moving horizontally, but i want it to start moving from a position which is half way from the top of the form. This is the code to create a diamond, private void Form1_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; Point p1 = new Point(5+x, 0); Point p2 = new Point(10+x, 5); Point p3 = new Point(5+x, 10); Point p4 = new Point(0+x, 5); Point[] ps = { p1, p2, p3, p4, p1 }; Pen p_yellow = new Pen(Color.Yellow, 5); g.DrawLines(p_yellow, ps); this.BackColor = System.Drawing.Color.DarkBlue; } I can make it move using the timer and following is the code, private void timer1_Tick(object sender, EventArgs e) { if (x < 500) x += 2; else timer1.Enabled = false; this.Invalidate(); } please tell me how to bring the diamond to a point which is half way from the top of the form?

    Read the article

  • Events and references pattern

    - by serhio
    In a project I have the following relation between BO and GUI By e.g. G could represent a graphic with time lines, C a TimeLine curve, P - points of that curve and T the time that represents each point. Each GUI object is associated with the BO corresponding object. When T changes GUI P captures the Changed event and changes its location. So, when G should be modified, it modifies internally its objects and as result T changes, P moves and the GuiG visually changes, everything is OK. But there is an inconvenient of this architecture... BO should not be recreated, because this will breack the link between BO and GUIO. In particular, GUI P should always have the same reference of T. If in a business logic I do by e.g. P1.T = new T(this.T + 10) GUI_P1 will not move anymore, because it wait an event from the reference of former P1.T object, that does not belongs to P1 anymore. So the solution was to always modify the existing objects, not to recreate it. But here is an other inconvenient: performance. Say I have a ready newC object that should replace the older one. Instead of doing G1.C = newC I should do foreach T in foreach P in C replace with T from P from newC. Is there an other more optimal way to do it?

    Read the article

  • Inject runtime exception to pthread sometime fails. How to fix that?

    - by lionbest
    I try to inject the exception to thread using signals, but some times the exception is not get caught. For example the following code: void _sigthrow(int sig) { throw runtime_error(strsignal(sig)); } struct sigaction sigthrow = {{&_sigthrow}}; void* thread1(void*) { sigaction(SIGINT,&sigthrow,NULL); try { while(1) usleep(1); } catch(exception &e) { cerr << "Thread1 catched " << e.what() << endl; } }; void* thread2(void*) { sigaction(SIGINT,&sigthrow,NULL); try { while(1); } catch(exception &e) { cerr << "Thread2 catched " << e.what() << endl; //never goes here } }; If I try to execute like: int main() { pthread_t p1,p2; pthread_create( &p1, NULL, &thread1, NULL ); pthread_create( &p2, NULL, &thread2, NULL ); sleep(1); pthread_kill( p1, SIGINT); pthread_kill( p2, SIGINT); sleep(1); return EXIT_SUCCESS; } I get the following output: Thread1 catched Interrupt terminate called after throwing an instance of 'std::runtime_error' what(): Interrupt Aborted How can I make second threat catch exception? Is there better idea about injecting exceptions?

    Read the article

  • How to do buffered intersection checks on an IPoint?

    - by Quigrim
    How would I buffer an IPoint to do an intersection check using IRelationalOperator? I have, for arguments sake: IPoint p1 = xxx; IPoint p2 = yyy; IRelationalOperator rel1 = (IRelationalOperator)p1; if (rel.Intersects (p2)) // Do something But now I want to add a tolerance to my check, so I assume the right way to do that is by either buffering p1 or p2. Right? How do I add such a buffer? Note: the Intersects method I am using is an extension method I wrote to simplify my code. Here it is: /// <summary> /// Returns true if the IGeometry is intersected. /// This method negates the Disjoint method. /// </summary> /// <param name="relOp">The rel op.</param> /// <param name="other">The other.</param> /// <returns></returns> public static bool Intersects ( this IRelationalOperator relOp, IGeometry other) { return (!relOp.Disjoint (other)); }

    Read the article

  • LINQ thinks I need an extra INNER JOIN, but why?

    - by Saurabh Kumar
    I have a LINQ query, which for some reason is generating an extra/duplicatre INNER JOIN. This is causing the query to not return the expected output. If I manually comment that extra JOIN from the generated SQL, then I get seemingly correct output. Can you detect what I might have done i nthis LINQ to have cuased this extra JOIN? Thanks. Here is my approx LINQ var ids = context.Code.Where(predicate); var rs = from r in ids group r by new { r.phonenumbers.person.PersonID} into g let matchcount=g.Select(p => p.phonenumbers.PhoneNum).Distinct().Count() where matchcount ==2 select new { personid = g.Key }; and here is the generated SQL (the duplicate join is [t7]) Declare @p1 VarChar(10)='Home' Declare @p2 VarChar(10)='111' Declare @p3 VarChar(10)='Office' Declare @p4 VarChar(10)='222' Declare @p5 int=2 SELECT [t9].[PersonID] AS [pid] FROM ( SELECT [t3].[PersonID], ( SELECT COUNT(*) FROM ( SELECT DISTINCT [t7].[PhoneValue] FROM [dbo].[Person] AS [t4] INNER JOIN [dbo].[PersonPhoneNumber] AS [t5] ON [t5].[PersonID] = [t4].[PersonID] INNER JOIN [dbo].[CodeMaster] AS [t6] ON [t6].[Code] = [t5].[PhoneType] INNER JOIN [dbo].[PersonPhoneNumber] AS [t7] ON [t7].[PersonID] = [t4].[PersonID] WHERE ([t3].[PersonID] = [t4].[PersonID]) AND ([t6].[Enumeration] = @p0) AND ((([t6].[CodeDescription] = @p1) AND ([t5].[PhoneValue] = @p2)) OR (([t6].[CodeDescription] = @p3) AND ([t5].[PhoneValue] = @p4))) ) AS [t8] ) AS [value] FROM ( SELECT [t0].[PersonID] FROM [dbo].[Person] AS [t0] INNER JOIN [dbo].[PersonPhoneNumber] AS [t1] ON [t1].[PersonID] = [t0].[PersonID] INNER JOIN [dbo].[CodeMaster] AS [t2] ON [t2].[Code] = [t1].[PhoneType] WHERE ([t2].[Enumeration] = @p0) AND ((([t2].[CodeDescription] = @p1) AND ([t1].[PhoneValue] = @p2)) OR (([t2].[CodeDescription] = @p3) AND ([t1].[PhoneValue] = @p4))) GROUP BY [t0].[PersonID] ) AS [t3] ) AS [t9] WHERE [t9].[value] = @p5

    Read the article

  • 'LINQ query plan' horribly inefficient but 'Query Analyser query plan' is perfect for same SQL!

    - by Simon_Weaver
    I have a LINQ to SQL query that generates the following SQL : exec sp_executesql N'SELECT COUNT(*) AS [value] FROM [dbo].[SessionVisit] AS [t0] WHERE ([t0].[VisitedStore] = @p0) AND (NOT ([t0].[Bot] = 1)) AND ([t0].[SessionDate] > @p1)',N'@p0 int,@p1 datetime', @p0=1,@p1='2010-02-15 01:24:00' (This is the actual SQL taken from SQL Profiler on SQL Server 2008.) The query plan generated when I run this SQL from within Query Analyser is perfect. It uses an index containing VisitedStore, Bot, SessionDate. The query returns instantly. However when I run this from C# (with LINQ) a different query plan is used that is so inefficient it doesn't even return in 60 seconds. This query plan is trying to do a key lookup on the clustered primary key which contains a couple million rows. It has no chance of returning. What I just can't understand though is that the EXACT same SQL is being run - either from within LINQ or from within Query Analyser yet the query plan is different. I've ran the two queries many many times and they're now running in isolation from any other queries. The date is DateTime.Now.AddDays(-7), but I've even hardcoded that date to eliminate caching problems. Is there anything i can change in LINQ to SQL to affect the query plan or try to debug this further? I'm very very confused!

    Read the article

  • Creating an appropriate index for a frequently used query in SQL Server

    - by Slauma
    In my application I have two queries which will be quite frequently used. The Where clauses of these queries are the following: WHERE FieldA = @P1 AND (FieldB = @P2 OR FieldC = @P2) and WHERE FieldA = @P1 AND FieldB = @P2 P1 and P2 are parameters entered in the UI or coming from external datasources. FieldA is an int and highly on-unique, means: only two, three, four different values in a table with say 20000 rows FieldB is a varchar(20) and is "almost" unique, there will be only very few rows where FieldB might have the same value FieldC is a varchar(15) and also highly distinct, but not as much as FieldB FieldA and FieldB together are unique (but do not form my primary key, which is a simple auto-incrementing identity column with a clustered index) I'm wondering now what's the best way to define an index to speed up specifically these two queries. Shall I define one index with... FieldB (or better FieldC here?) FieldC (or better FieldB here?) FieldA ... or better two indices: FieldB FieldA and FieldC FieldA Or are there even other and better options? What's the best way and why? Thank you for suggestions in advance!

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >