text:
Q: How can a pivot table filter destroy dynamic named ranges? Problem is sloved, answer is below
I have a code that has been working great the past months.
During the night between yesterday and today while nobody as using the computer ( only a automatic VBA code running) it stopped working.
In short the automatic VBA code updates a table on sheet 1, a pivot table on sheet 2 uses the first four charaters of the time and the value at that time.
Example (time is 10:15) time = 10:1, value = 5555. The reason for the truncing of the last minute is to get a "rounded number", when this scales to months of data it's better to have 10:1 than 10:15, 10:16 and 10:17 and so on.
After the data is on sheet 2, a named range is used to get the interesting part of the table (two rows above first value > 0 to end of table) usually that means row 35~40 and end at row 148-ish.
 =OFFSET(Blad2!$B$5,MATCH(TRUE,Blad2!$B$5:$B$148<>0,0)-3,0,MATCH(TRUE,Blad2!$B$5:$B$148="",0)-MATCH(TRUE,Blad2!$B$5:$B$148<>0,0)+2,1)

This named range is used in a chart.
The VBA that by some reason starting yesterday destroys this is:
ThisWorkbook.RefreshAll
ThisWorkbook.Sheets("Blad2").Calculate
ThisWorkbook.Sheets("Blad2").PivotTables("Pivottabell1").PivotFields("Datum").ClearAllFilters
ThisWorkbook.Sheets("Blad2").PivotTables("Pivottabell1").PivotFields("Veckodag").ClearAllFilters

The Pivot table looks like this:

What I'm doing is changing the filter of the table from as the picture shows Thursdays to Fridays.
And to do that I need to reset the filters first then loop and unset all but Friday.
But as soon as the filter is reset the dynamic ranges stops working.
What can cause this?

A: As I was typing this question I found the problem.
I was literally typing the second last line But as soon as the, and that is when I figured it out.
I believe this can be a problem for others too so that is why I keep the question.
The problem is the pivot table grew downwards.
I thought I had all the "rounded times" in my table but it seems one was missing and that caused it to expand past where the dynamic range was trying to find the end of the table.
By just adding two rows to the range (148 => 150) it all worked fine again.
=OFFSET(Blad2!$B$5,MATCH(TRUE,Blad2!$B$5:$B$150<>0,0)-3,0,MATCH(TRUE,Blad2!$B$5:$B$150="",0)-MATCH(TRUE,Blad2!$B$5:$B$150<>0,0)+2,1)

I have now double checked that all "rounded times" are in the table so it can't grow again.
Yes, I should buy a rubber duck...


text:
Q: Jasmine specs never complete when run by Phantom JS on TeamCity I am using PhantomJS to execute my Jasmine specs (v 2.0) on TeamCity as part of my CI process. The problem I have is that the process never exits when it has finished running the specs. I have also seen it exit early with a timeout.  I am using the Teamcity Jasmine reporter.
More detail: I have tried a basic setTimeout-based mechanism found on a blog post (will add when I find the URL) and the standard wait-for driven script on the PhantomJs.org page.  In both cases, the specs never finish.  When running it through TeamCity, the build never finishes, though the log shows that all the specs have been run; if I run it directly from the command line, I see one of two things: either it finishes and then sits there indefinitely, or I get a wait-for timeout message in the middle of running the specs (i.e. it does not finish).
Final detail: this only happens when I include two particular specs.  One is a long spec containing dozens of tests, the other a spec for a simple custom collection type.  The order in which I include them makes no difference.  If I run either spec alone, Phantom exits correctly.  If I include either of these specs with all the others, Phantom exits correctly.  It only seems to hang when BOTH these two particular specs are included.
I have checked that I have no uninstalled jasmine clocks.
The quantity of js involved is too large to post.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Failure obtaining db row lock: No row exists in table QRTZ_LOCKS for lock named: TRIGGER_ACCESS I'm new to Quartz scheduler and I'm using it with spring ... When I tried to run the XML file that contains Quartz configuration I got an exception stating that:
Failure obtaining db row lock: No row exists in table QRTZ_LOCKS for lock named:
TRIGGER_ACCESS

I found that the table QRTZ_LOCKS contains two fields: SCHED_NAME and LOCK_NAME and that I should run the following statements in my database:
INSERT INTO QRTZ_LOCKS values('my sched_name', 'TRIGGER_ACCESS');
INSERT INTO QRTZ_LOCKS values('my sched_name','JOB_ACCESS');
INSERT INTO QRTZ_LOCKS values('my sched_name','CALENDAR_ACCESS');
INSERT INTO QRTZ_LOCKS values('my sched_name','STATE_ACCESS');
INSERT INTO QRTZ_LOCKS values('my sched_name','MISFIRE_ACCESS');

but I don't have a clue what is my sched_name ??
Any idea ??

A: You just need to run
      INSERT INTO QRTZ_LOCKS values('TRIGGER_ACCESS');
      INSERT INTO QRTZ_LOCKS values('JOB_ACCESS');
      INSERT INTO QRTZ_LOCKS values('CALENDAR_ACCESS');
      INSERT INTO QRTZ_LOCKS values('STATE_ACCESS');
      INSERT INTO QRTZ_LOCKS values('MISFIRE_ACCESS');

That worked for me actually. Stopped the error at least.

A: That is most likely because you got the table scripts from a newer version of Quartz then you are applying on your application.
If you are using Spring, then you must have Quartz 1.8.x.
This is where you can find version 1.8.6
Note: Inside that tar.gz file there is another file without extension. It is a zip file which contains a folder named doc. In there you can find a script for several database engines.
No manual modifications on data should be necessary.

A: *my_sched_name* can be retrieved from the table qrtz_job_details (sched_name).
You must have an issue with your quartz configuration/deployement because usually you do not have to insert/update those tables manually.

A: Usually you get these errors, when you don't have the db tables related to quartz in your db.
Sometimes you may get these errors in migration even though you have the db tables. Please check there are a few changes in db_schema for quartz 1.8 and quart 2.x.
Below is the link for 2.x db scripts, this should perfectly work.
2.x: https://github.com/elventear/quartz-scheduler/blob/master/distribution/src/main/assembly/root/docs/dbTables/tables_mysql.sql
you can check this one too:
https://github.com/quartznet/quartznet/blob/master/database/tables/tables_oracle.sql


text:
Q: How can i know how many numbers that the user wrote the same? I need to write a function that accepts the length of series(0 and 1) and the user writes the series. The function tells the place of the longest same sun-series.
Example:
The function gets length = 12, and the user writes: 1 0 0 1 1 1 1 0 0 0 1 1
The answer for this one is 4 because the longest combination (four consecutive 1's) starts at 4th place.
Another example:
The length is: 12 and the user inputs : 1 0 0 0 1 1 0 1 1 1 0 0
The answer for this one is 2 (three consecutive 0's starting at position 2—if there are multiple sub-series with same length it returns the first one).
This is what I tried to do:
int sameNumbers(int seriaLength)
{
    int i;
    int place=0;
    int num1, num2;
    int sameCount;
    int maxSameCount = 0;

    printf("Please enter the seria: \n");
    scanf("%d",&num1);

    for(i = 1; i < seriaLength; i++)
    {
        scanf("%d",&num2);
        while(num1 == num2)
        {
            sameCount++;
        }
        if(sameCount > maxSameCount)
        {
            maxSameCount = sameCount;
            place = i;
        }
        scanf("%d",&num1);
    }

    return place;
}

Edit:
I need to do this without arrays.
Thanks!!

A: This seems to do what you want.  To understand the logic, see the comments in the code.
#include <stdio.h>
int sameNumbers(int seriaLength)
{

    int i, num, previousNum, length = 0, maxLength = 0, start = 0, startOfLongest = 0;

    printf( "Please enter the series: " );

    for( i = 0; i < seriaLength; i++ )
    {
        scanf( "%d", &num );

        if( i > 0 && num == previousNum ) length++;
        else { length = 1; start = i; }  // if the number is not the same as the previous number, record the start of a new sequence here
        if( length > maxLength ) { maxLength = length; startOfLongest = start; } // if we've broken (not equalled) the previous record for longest sequence, record where it happened
        previousNum = num;
    }
    return startOfLongest + 1; //  add 1 because the OP seems to want the resulting index to be 1-based
}

int main( int argc, const char * argv[] )
{
    printf( "%d\n", sameNumbers( 12 ) );
    return 0;
}


text:
Q: Adding a column list based on another column values in pandas I have a dataframe df:
Date          Product  value    Offer
2022-01-01    x_00_02   0.16    5
2022-01-01    x_00_02   0.16    5
2022-01-01    x_00_02   0.16    5
2022-01-01    x_00_02   0.16    5
2022-01-01    x_00_02   0.18    6
2022-01-01    x_00_02   0.18    6
2022-01-01    x_00_02   0.18    6
2022-01-01    x_00_02   0.18    6
2022-01-01    x_02_04   0.32    10
2022-01-01    x_02_04   0.32    10
2022-01-01    x_02_04   0.32    10
2022-01-01    x_02_04   0.32    10
2022-01-01    x_04_06   0.45    11
2022-01-01    x_04_06   0.45    11
2022-01-01    x_04_06   0.45    11
2022-01-01    x_04_06   0.45    11
2022-01-01    x_04_06   0.47    7
2022-01-01    x_04_06   0.47    7
2022-01-01    x_04_06   0.47    7
2022-01-01    x_04_06   0.47    7
...

Each individual "product" is duplicated 4 times (as this was achieved by previous code) and can be identified based on the value column. df is already sorted by date, product and value.
What I want is to add a new column that counts each "product" based on the Product column so that:

*

*the count begins at: (minimum value * 2) + 1

*the count ends at: maximum value * 2

*count is denoted as: val_0xx, where xx represent the count values

In the case of the product x_00_02 (minimum value = 00 and maximum value = 02):

*

*count starts at: (0*2)+1 = val_001

*count ends at: 2*2 = val_004

Expected output:
Date          Product  value    Offer  Product_2
2022-01-01    x_00_02   0.16    5      val_001
2022-01-01    x_00_02   0.16    5      val_002
2022-01-01    x_00_02   0.16    5      val_003
2022-01-01    x_00_02   0.16    5      val_004
2022-01-01    x_00_02   0.18    6      val_001
2022-01-01    x_00_02   0.18    6      val_002
2022-01-01    x_00_02   0.18    6      val_003
2022-01-01    x_00_02   0.18    6      val_004
2022-01-01    x_02_04   0.32    10     val_005
2022-01-01    x_02_04   0.32    10     val_006
2022-01-01    x_02_04   0.32    10     val_007
2022-01-01    x_02_04   0.32    10     val_008
2022-01-01    x_04_06   0.45    11     val_009
2022-01-01    x_04_06   0.45    11     val_010
2022-01-01    x_04_06   0.45    11     val_011
2022-01-01    x_04_06   0.45    11     val_012
2022-01-01    x_04_06   0.47    7      val_009
2022-01-01    x_04_06   0.47    7      val_010
2022-01-01    x_04_06   0.47    7      val_011
2022-01-01    x_04_06   0.47    7      val_012

A: You can use:
df['Product_2'] = (df.drop_duplicates()['Product'].str.split('_')
                     .map(lambda x: range(int(x[1])*2+1, int(x[2])*2+1))
                     .explode().astype(str).str.zfill(3).radd('val_').tolist())
print(df)

# Output
          Date  Product  value  Offer Product_2
0   2022-01-01  x_00_02   0.16      5   val_001
1   2022-01-01  x_00_02   0.16      5   val_002
2   2022-01-01  x_00_02   0.16      5   val_003
3   2022-01-01  x_00_02   0.16      5   val_004
4   2022-01-01  x_00_02   0.18      6   val_001
5   2022-01-01  x_00_02   0.18      6   val_002
6   2022-01-01  x_00_02   0.18      6   val_003
7   2022-01-01  x_00_02   0.18      6   val_004
8   2022-01-01  x_02_04   0.32     10   val_005
9   2022-01-01  x_02_04   0.32     10   val_006
10  2022-01-01  x_02_04   0.32     10   val_007
11  2022-01-01  x_02_04   0.32     10   val_008
12  2022-01-01  x_04_06   0.45     11   val_009
13  2022-01-01  x_04_06   0.45     11   val_010
14  2022-01-01  x_04_06   0.45     11   val_011
15  2022-01-01  x_04_06   0.45     11   val_012
16  2022-01-01  x_04_06   0.47      7   val_009
17  2022-01-01  x_04_06   0.47      7   val_010
18  2022-01-01  x_04_06   0.47      7   val_011
19  2022-01-01  x_04_06   0.47      7   val_012


text:
Q: R: How to make a switch statement fallthrough In many languages, there is an instruction called break that tells the interpreter to exit the switch after the current statement. If you omit it, the switch fall-through after the current case has been processed:
switch (current_step)
{
  case 1:
    print("Processing the first step...");
    # [...]
  case 2:
    print("Processing the second step...");
    # [...]
  case 3:
    print("Processing the third step...");
    # [...]
    break;
  case 4:
    print("All steps have already been processed!");
    break;
}

Such a design pattern can be useful if you want to go through a serie of transitive conditions.

I understand that this can cause bugs due to unintentional fallthrough if the programmer forgets to insert the break statement, but several languages are breaking by default, and include a fallthrough keyword (e.g. continuein Perl).
And by design, the R switch also breaks by default at the end of each case:
switch(current_step,
  {
    print("Processing the first step...")
  },
  {
    print("Processing the second step...")
  },
  {
    print("Processing the third step...")
  },
  {
    print("All steps have already been processed!")
  }
)

In the above code, if current_step is set to 1, the output will only be "Processing the first step...".

Is there any way in R to force a switch case to fall through the following case?

A: It appears that such a behavior is not possible with switch().
As suggested in the comments, the best option was to implement my own version.

Thus, I pushed an update to my optional package to implement this feature (CRAN).
With this update, you can now use a fallthrough statement in the pattern-matching function match_with.
The design pattern in the question can be reproduced the following way:
library(optional)
a <- 1
match_with(a
    1, fallthrough(function() "Processing the first step..."),
    2, fallthrough(function() "Processing the second step..."),
    3, function() "Processing the third step...",
    4, function() "All steps have already been processed!"
)
## [1] "Processing the first step..." "Processing the second step..." "Processing the third step..."

You can observe that match_with() is quite similar to switch(), but it has extended capabilities. E.g. the patterns can be lists or functional sequences instead of being simple objects to compare:
library("magrittr")
b <- 4
match_with(a,
  . %>% if (. %% 2 == 0).,
  fallthrough( function() "This number is even" ),
  . %>% if ( sqrt(.) == round(sqrt(.)) ).,
  function() "This number is a perfect square"
)
## [1] "This number is even" "This number is a perfect square"


text:
Q: Why were two policies deleted from MSE? Last week two policies were posted to MSE:

*

*What are our policies regarding underage users?

*What are our policies regarding threats of self-harm and suicide?
They have now been deleted, why?

A: We posted these as they were identified as lacking on an audit conducted on our policies for moderators as part of the new agreement.
However, it seems in the interest of expediency we overlooked our own promise that new policies would go through moderator council & moderator teams review before being posted live.
These policies have now been deleted and will undergo the review above to be undeleted later after that is done.
Update: These policies have completed the moderator reviews, and have been undeleted and revised as per feedback.


text:
Q: SQL Server Stored Procedure Returns All Result properly for otherdays except the Starting day I am facing a problem while trying to get the data from my database & displaying it in gridview. in front-end i have a page where i will search the report for a particular day. My code is working properly for all days except the 1st day. for the 1st day it is not displaying any values.1st day means, suppose i entered opening balance entry on 01/06/2014 in opening balance table . & in search page i want to see the report for 22/06/2014 then it is working fine. but if i want to see the report of 01/06/2014 it is not showing any result.
From this stored procedure i am getting the report data which i have written :
ALTER PROCEDURE [dbo].[usp_GetDatailsForDailyReport]
   @vDate VARCHAR(50)
AS
--DECLARE @vPrevDate VARCHAR(50)
BEGIN
--SET @vPrevDate=(SELECT CONVERT(VARCHAR(50),DATEADD(DD, DATEDIFF(DD, 0, CONVERT(datetime,'19/06/2014',103)), -1),103))
    SET NOCOUNT ON;

    -- Insert statements for procedure here
 select PrevOpening.SchoolID,
 SCHOOLDETAILS.SchoolName,
 SCHOOLDETAILS.SchoolCode,
 SCHOOLDETAILS.SansadNo,
 SCHOOLDETAILS.Circle,
 isnull(NOOFSTUDENTS.TotalNoOfStudents,0) AS NoOfStudents,
 isnull(PrevOpening.RecRice,0)-isnull(PrevConsumption.ConRice,0) OpeningRice,
 isnull(RECEIVING.CurRecRice,0) RecvRice,
  isnull(CONSUMPTION.CurConRice,0) ConRice,
 (((isnull(PrevOpening.RecRice,0)-isnull(PrevConsumption.ConRice,0))+ isnull(RECEIVING.CurRecRice,0))- isnull(CONSUMPTION.CurConRice,0)) ClosingRice,
 isnull(PrevOpening.RecAmount,0)-isnull(PrevConsumption.ConAmount,0) OpeningAmount,
 isnull(RECEIVING.CurRecAmount,0) RecvAmount,
  isnull(CONSUMPTION.CurConAmount,0) ConAmount,
 (((isnull(PrevOpening.RecAmount,0)-isnull(PrevConsumption.ConAmount,0))+ isnull(RECEIVING.CurRecAmount,0))- isnull(CONSUMPTION.CurConAmount,0)) ClosingAmount
 FROM
     (
         SELECT
                SchoolID,
                ISNULL (SUM(isnull(Rice,0)),0) AS RecRice,
                ISNULL (SUM(isnull(Amount,0)),0) AS RecAmount
        FROM tblOpeningBalance
        WHERE Date<CONVERT(datetime,@vDate,103) Group BY SchoolID
       ) PrevOpening
        LEFT JOIN
        (
        SELECT SchoolID,
                ISNULL (SUM(isnull(Rice,0)),0) AS ConRice,
                ISNULL (SUM(isnull(Amount,0)),0) AS ConAmount
                --SUM(NoOfStudent) AS PrevTotalNoOfStudents
        FROM tblDailyMidDayDetails
        WHERE Date<CONVERT(datetime,@vDate,103) Group BY SchoolID
        ) PrevConsumption
         ON  PrevOpening.SchoolID=PrevConsumption.SchoolID
        LEFT JOIN
        (
        SELECT
        SchoolID,
        ISNULL (SUM(isnull(Rice,0)),0) AS CurRecRice,
        ISNULL (SUM(isnull(Amount,0)),0)AS CurRecAmount
        FROM tblOpeningBalance
        WHERE
        Date=CONVERT(datetime,@vDate,103) GROUP BY SchoolID
        ) RECEIVING
        ON  PrevOpening.SchoolID=RECEIVING.SchoolID
        LEFT JOIN
        (
        SELECT
        SchoolID,
        ISNULL (SUM(isnull(Rice,0)),0) AS CurConRice,
        ISNULL (SUM(isnull(Amount,0)),0) AS CurConAmount
        --ISNULL (SUM(isnull(NoOfStudent,0)),0) AS TotalNoOfStudents
        FROM tblDailyMidDayDetails
        WHERE
        Date=CONVERT(datetime,@vDate,103) GROUP BY SchoolID
        ) CONSUMPTION
        ON PrevOpening.SchoolID=CONSUMPTION.SchoolID
        LEFT JOIN
        (
        SELECT
        SchoolID,
        SchoolName,
        SchoolCode,
        SansadNo,
        Circle
        FROM
        tblSchoolDetails
        ) SCHOOLDETAILS
        ON PrevOpening.SchoolID=SCHOOLDETAILS.SchoolID
        LEFT JOIN
        (
        SELECT
        SchoolID,
        SUM(NoOfStudent) AS TotalNoOfStudents
        FROM
        tblDailyMidDayDetails
        WHERE
        Date=CONVERT(datetime,@vDate,103) GROUP BY SchoolID
        ) NOOFSTUDENTS
        ON PrevOpening.SchoolID=NOOFSTUDENTS.SchoolID
END

Now the stored procedure for inserting in OpeningBalance table is :
ALTER PROCEDURE [dbo].[usp_InsertOpeningBalance]
(
@vOpeningBalanceID INT
,@vDate NVARCHAR(10)
,@vSchoolID INT
,@vRice NVARCHAR(30)
,@vAmount NVARCHAR(30)
,@ReturnVal INT OUTPUT
)
    AS
    DECLARE @DupCount INT
BEGIN
    SET NOCOUNT ON;
    IF (@vOpeningBalanceID=0)
BEGIN
SET @DupCount=(SELECT COUNT(SchoolID) FROM [dbo].[tblOpeningBalance] WHERE CONVERT(VARCHAR(10),Date,103)=CONVERT (VARCHAR(10),@vDate,103) AND SchoolID=@vSchoolID)
IF (@DupCount>0)
BEGIN
SET @ReturnVal=-70
END
ELSE
BEGIN
            INSERT INTO [dbo].[tblOpeningBalance]
                (
                     Date
                    ,SchoolID
                    ,Rice
                    ,Amount
                )
                VALUES
                (
                     CONVERT(datetime, @vDate, 103)
                     ,@vSchoolID
                     ,CONVERT(float,@vRice)
                     ,CONVERT(float,@vAmount)
                )

            SET @ReturnVal=1
END
        END
ELSE
        BEGIN
            UPDATE [dbo].[tblOpeningBalance]
                SET
                Date= CONVERT(datetime, @vDate, 103)
                ,SchoolID=@vSchoolID
                ,Rice=CONVERT(float,@vRice)
                ,Amount=CONVERT(float,@vAmount)
                WHERE OpeningBalanceID=@vOpeningBalanceID

            SET @ReturnVal=2
        END
END

This is the stored procedure for insertion of daily midday meal details for daily consumption in midday meal table.
ALTER PROCEDURE [dbo].[usp_InsertDailyMidDayDetails]
    -- Add the parameters for the stored procedure here
        (
             @vSchoolID INT
            ,@vDate NVARCHAR(20)
            ,@vNoOfStudent INT
            ,@vRice NVARCHAR(30)
            ,@vAmount NVARCHAR(30)
            ,@vVisitTypeID INT

            ,@ReturnVal INT OUTPUT
        )
AS
    DECLARE @i_count INT
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    BEGIN
         SET @i_count=(SELECT COUNT(ID)
                                   FROM tblDailyMidDayDetails
                                   WHERE ltrim(rtrim(Date))=ltrim(rtrim(@vDate)) );

                    IF (@i_count  >0)
                        BEGIN
                                SET @ReturnVal = -70;
                        END
                    ELSE
                        BEGIN

                            INSERT INTO tblDailyMidDayDetails
                                (
                                    SchoolID
                                    ,Date
                                    ,NoOfStudent
                                    ,Rice
                                    ,Amount
                                    ,VisitTypeID
                                )
                                VALUES
                                (
                                    @vSchoolID
                                    ,CONVERT(DATETIME,@vDate,103)
                                    ,@vNoOfStudent
                                    ,CONVERT(float,@vRice)
                                    ,CONVERT(FLOAT,@vAmount)
                                    ,@vVisitTypeID
                                )

                                SET @ReturnVal=1
                        END
    END
END

Can anyone guide me what is wrong with my code?

A: You have several different variable types for the date.
@vDate VARCHAR(50)
@vDate NVARCHAR(10)
@vDate NVARCHAR(20)

Why the difference?
Why not just store as
date

A: This is the Correction which i have done it by myself.  Now i am getting perfect result.
ALTER PROCEDURE [dbo].[usp_GetDatailsForDailyReport]
    @vDate VARCHAR(50)

    AS
    --DECLARE @vPrevDate VARCHAR(50)
    BEGIN
    --SET @vPrevDate=(SELECT CONVERT(VARCHAR(50),DATEADD(DD, DATEDIFF(DD, 0, CONVERT(datetime,'19/06/2014',103)), -1),103))
        SET NOCOUNT ON;

        -- Insert statements for procedure here
     select PrevOpening.SchoolID,
     SCHOOLDETAILS.SchoolName,
     SCHOOLDETAILS.SchoolCode,
     SCHOOLDETAILS.SansadNo,
     SCHOOLDETAILS.Circle,
     isnull(NOOFSTUDENTS.TotalNoOfStudents,0) AS NoOfStudents,
     isnull(PrevOpening.RecRice,0)-isnull(PrevConsumption.ConRice,0)+ isnull(RECEIVING.CurRecRice,0) OpeningRice,
     isnull(RECEIVING.CurRecRice,0) RecvRice,
      isnull(CONSUMPTION.CurConRice,0) ConRice,
     (((isnull(PrevOpening.RecRice,0)-isnull(PrevConsumption.ConRice,0))+ isnull(RECEIVING.CurRecRice,0))- isnull(CONSUMPTION.CurConRice,0)) ClosingRice,
     isnull(PrevOpening.RecAmount,0)-isnull(PrevConsumption.ConAmount,0)+ isnull(RECEIVING.CurRecAmount,0) OpeningAmount,
     isnull(RECEIVING.CurRecAmount,0) RecvAmount,
      isnull(CONSUMPTION.CurConAmount,0) ConAmount,
     (((isnull(PrevOpening.RecAmount,0)-isnull(PrevConsumption.ConAmount,0))+ isnull(RECEIVING.CurRecAmount,0))- isnull(CONSUMPTION.CurConAmount,0)) ClosingAmount
     FROM
            (
            SELECT
            SchoolID,
            SchoolName,
            SchoolCode,
            SansadNo,
            Circle
            FROM
            tblSchoolDetails

            WHERE IsApproved=1
            ) SCHOOLDETAILS
            LEFT JOIN
              (
             SELECT
                    SchoolID,
                    ISNULL (SUM(isnull(Rice,0)),0) AS RecRice,
                    ISNULL (SUM(isnull(Amount,0)),0) AS RecAmount
            FROM tblOpeningBalance
            WHERE Date<CONVERT(datetime,@vDate,103) Group BY SchoolID
           ) PrevOpening
           ON   SCHOOLDETAILS.SchoolID=PrevOpening.SchoolID
           LEFT JOIN

            (
            SELECT SchoolID,
                    ISNULL (SUM(isnull(Rice,0)),0) AS ConRice,
                    ISNULL (SUM(isnull(Amount,0)),0) AS ConAmount
                    --SUM(NoOfStudent) AS PrevTotalNoOfStudents
            FROM tblDailyMidDayDetails
            WHERE Date<CONVERT(datetime,@vDate,103) Group BY SchoolID
            ) PrevConsumption
             ON  SCHOOLDETAILS.SchoolID=PrevConsumption.SchoolID
             LEFT JOIN
         (
            SELECT
            SchoolID,
            ISNULL (SUM(isnull(Rice,0)),0) AS CurRecRice,
            ISNULL (SUM(isnull(Amount,0)),0)AS CurRecAmount
            FROM tblOpeningBalance
            WHERE
            Date=CONVERT(datetime,@vDate,103) GROUP BY SchoolID
            ) RECEIVING
            ON SCHOOLDETAILS.SchoolID=RECEIVING.SchoolID
            LEFT JOIN

            (
            SELECT
            SchoolID,
            ISNULL (SUM(isnull(Rice,0)),0) AS CurConRice,
            ISNULL (SUM(isnull(Amount,0)),0) AS CurConAmount
            --ISNULL (SUM(isnull(NoOfStudent,0)),0) AS TotalNoOfStudents
            FROM tblDailyMidDayDetails
            WHERE
            Date=CONVERT(datetime,@vDate,103) GROUP BY SchoolID
            ) CONSUMPTION
            ON  SCHOOLDETAILS.SchoolID=CONSUMPTION.SchoolID

                LEFT JOIN
            (
            SELECT
            SchoolID,
            SUM(NoOfStudent) AS TotalNoOfStudents
            FROM
            tblDailyMidDayDetails
            WHERE
            Date=CONVERT(datetime,@vDate,103) GROUP BY SchoolID
            ) NOOFSTUDENTS
            ON SCHOOLDETAILS.SchoolID=NOOFSTUDENTS.SchoolID

END


text:
Q: How to plot one line in different colors I have two list as below:
latt=[42.0,41.978567980875397,41.96622693388357,41.963791391892457,...,41.972407378075879]
lont=[-66.706920989908909,-66.703116557977069,-66.707351643324543,...-66.718218142021925]

now I want to plot this as a line, separate each 10 of those 'latt' and 'lont' records as a period and give it a unique color.
what should I do?

A: Copied from this example:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm

x = np.linspace(0, 3 * np.pi, 500)
y = np.sin(x)
z = np.cos(0.5 * (x[:-1] + x[1:]))  # first derivative

# Create a colormap for red, green and blue and a norm to color
# f' < -0.5 red, f' > 0.5 blue, and the rest green
cmap = ListedColormap(['r', 'g', 'b'])
norm = BoundaryNorm([-1, -0.5, 0.5, 1], cmap.N)

# Create a set of line segments so that we can color them individually
# This creates the points as a N x 1 x 2 array so that we can stack points
# together easily to get the segments. The segments array for line collection
# needs to be numlines x points per line x 2 (x and y)
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)

# Create the line collection object, setting the colormapping parameters.
# Have to set the actual values used for colormapping separately.
lc = LineCollection(segments, cmap=cmap, norm=norm)
lc.set_array(z)
lc.set_linewidth(3)

fig1 = plt.figure()
plt.gca().add_collection(lc)
plt.xlim(x.min(), x.max())
plt.ylim(-1.1, 1.1)

plt.show()

A: There are several different ways to do this. The "best" approach will depend mostly on how many line segments you want to plot.
If you're just going to be plotting a handful (e.g. 10) line segments, then just do something like:
import numpy as np
import matplotlib.pyplot as plt

def uniqueish_color():
    """There're better ways to generate unique colors, but this isn't awful."""
    return plt.cm.gist_ncar(np.random.random())

xy = (np.random.random((10, 2)) - 0.5).cumsum(axis=0)

fig, ax = plt.subplots()
for start, stop in zip(xy[:-1], xy[1:]):
    x, y = zip(start, stop)
    ax.plot(x, y, color=uniqueish_color())
plt.show()

If you're plotting something with a million line segments, though, this will be terribly slow to draw.  In that case, use a LineCollection. E.g.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

xy = (np.random.random((1000, 2)) - 0.5).cumsum(axis=0)

# Reshape things so that we have a sequence of:
# [[(x0,y0),(x1,y1)],[(x0,y0),(x1,y1)],...]
xy = xy.reshape(-1, 1, 2)
segments = np.hstack([xy[:-1], xy[1:]])

fig, ax = plt.subplots()
coll = LineCollection(segments, cmap=plt.cm.gist_ncar)
coll.set_array(np.random.random(xy.shape[0]))

ax.add_collection(coll)
ax.autoscale_view()

plt.show()

For both of these cases, we're just drawing random colors from the "gist_ncar" coloramp. Have a look at the colormaps here (gist_ncar is about 2/3 of the way down): http://matplotlib.org/examples/color/colormaps_reference.html

A: See the answer here to generate the "periods" and then use the matplotlib scatter function as @tcaswell mentioned.  Using the plot.hold function you can plot each period, colors will increment automatically.

A: Cribbing the color choice off of @JoeKington,
import numpy as np
import matplotlib.pyplot as plt

def uniqueish_color(n):
    """There're better ways to generate unique colors, but this isn't awful."""
    return plt.cm.gist_ncar(np.random.random(n))

plt.scatter(latt, lont, c=uniqueish_color(len(latt)))

You can do this with scatter.

A: I have been searching for a short solution how to use pyplots line plot to show a time series coloured by a label feature without using scatter due to the amount of data points.
I came up with the following workaround:
plt.plot(np.where(df["label"]==1, df["myvalue"], None), color="red", label="1")
plt.plot(np.where(df["label"]==0, df["myvalue"], None), color="blue", label="0")
plt.legend()

The drawback is you are creating two different line plots so the connection between the different classes is not shown. For my purposes it is not a big deal. It may help someone.


text:
Q: How to calculate what gas price to use for transactions on RSK? I need to know how to set a proper gas price for my transactions on RSK network. I am familiar with the eth_gasPrice approach from Ethereum:
$ curl https://public-node.testnet.rsk.co -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_gasPrice","params":[],"id":1}'
{"jsonrpc":"2.0","id":1,"result":"0x3938700"}

Is the above recommended for RSK as well?

A: You have several ways to calculate the gas price.
From an end user point of view, you can get the gas price from:

*

*RSK Stats

*Metamask/Nifty/MEW proposed gasPrice  value when preparing a transaction

From a developer point of view, you need to know that RSK has a minimumGasPrice limit, this means that if you set a gasPrice below that minimum, your transaction will be rejected.
How to get gasPrice:
Using JSON-RPC method eth_gasPrice. This gives you a current average gas price in the network. It's a good idea to specify an additional 5% gas price as a buffer, in order to be above the average gas price.
The example code above you have is correct:
$ curl https://public-node.testnet.rsk.co -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_gasPrice","params":[],"id":1}'
{"jsonrpc":"2.0","id":1,"result":"0x3938700"}

... however, do the following as well to calculate the amount with buffer:
$ node -e "console.log(0x3938700 / 20 * 21);"
63000000

eth_gasPrice returns 60 million, but we use 63 million when submitting transactions.
For those familiar with Ethereum development, this is the same method as you would use there.
How to get minimumGasPrice:
Using JSON-RPC method eth_getBlockByNumber with best block number as parameter and getting minimumGasPrice from the response. As the minimum gas price may change 1% between blocks, see RSKIP-09, it is recommended to specify an additional 10% gas price as buffer, to ensure a 10 block window of valid gasPrice. This caters to a pessimistic scenario.
Example code to perform the above:
curl https://public-node.testnet.rsk.co -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["latest",false],"id":1}'

{
   "jsonrpc" : "2.0",
   "result" : {
      "cumulativeDifficulty" : "0x2b7cd0b2",
      "size" : "0xbcc",
      "uncles" : [],
      "gasUsed" : "0x546fe",
      "hash" : "0x68abc09397ec6ae77acf52c195638dd9f93e5756eb1856c81e8e30cbbeef6b39",
      "difficulty" : "0x2b7cd0b2",
      "miner" : "0x1fab9a0e24ffc209b01faa5a61ad4366982d0b7f",
      "bitcoinMergedMiningMerkleProof" : "0x8bfb89a6e8a8fa0fee018e9dd0d86c0aea40806d3e8fe45e9454a250b763d978c812164690d7af62b31743db9944cc5ac6038d210ef6d1e4fb08c712f9a318c0538845ed4d3f3b61879aba5e79c58bc754213a9872f54c2da44051b3c0e04d4be382b6f1303386afc08c991a85aae39fa3263cbcbd9d4a05d8a2d0797204902de56af20198ad4a3b2c553e0c2500da50a536fd10233204c5a9837802f6816f740a146e58ebae0d7be3ca3a79f7d2a942e5ade058baa53e252162fefc136f33434e84753446aad913ea4baafd6bcaa145d37b9b3b85fec42d7bf47d5efef8e000",
      "paidFees" : "0x1395b92f0000",
      "stateRoot" : "0xb7fc903f8f60a3e0d0d80ea58348e9637e3a9a4c8f9de6e089326c9bfbb698ed",
      "transactions" : [ "<< redacted for brevity >>" ],
      "totalDifficulty" : "0x2eff7f12ec2c2655d",
      "bitcoinMergedMiningHeader" : "0x00000020901806378d89a22c6aaa772bab42ec41dfdb4dce77d361181600000000000000a0782738fa6b7ef70644de0aca393597462d9fb97d59c92680eba5e5a2b66af14c6efe5f5c75161904657655",
      "receiptsRoot" : "0xc930346e224a837fc426b900c07d3f744f4c82ac789d05624dbbe4e008dc2f22",
      "hashForMergedMining" : "0xb58502263dd8363d0c88287eb3436c731ff5763e5ed4d4919306b028001738f9",
      "transactionsRoot" : "0x9cc25cf985416ef18fa171f59b9d03f6921bad3c93f956dc0d472f9429b81167",
      "gasLimit" : "0x67c280",
      "bitcoinMergedMiningCoinbaseTransaction" : "0x00000000000000801d9be7d007fe4505303282a8fdd52df91d1292256a776a2181521c4513ee6c246088ac0000000000000000266a24aa21a9edee78f53b94245e73c99fb98a96b539836fa82b85a20de1c0d7984f0eabd198f600000000000000002a6a52534b424c4f434b3ab58502263dd8363d0c88287eb3436c731ff5763e5ed4d4919306b028001738f900000000",
      "logsBloom" : "0x00000000000000000000001000000008000000000040000000000000000000000000400000050000000400000000000400000000010000000000000000000000000000000080000000000004000000000000000000000080000000004000000000000000800000000000001000000000000000000000000002000008080000000000000000000000000001000208000000000000040000000000000420080000000000020008100000000000020010000080000000000082001000000000000000000001040000000000000000080000000030000001000880200004100200000000000020000000002000000000100000000000000000010200000000000000",
      "minimumGasPrice" : "0x387ee40",
      "timestamp" : "0x5ffe6e40",
      "number" : "0x1738f9",
      "parentHash" : "0x1276aa271525f757166acf767cd6100a25d0cba18f6caf925299276f3d439404",
      "sha3Uncles" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
      "extraData" : "0xd1018f504150595255532d62643739313837"
   },
   "id" : 1
}

The response for this is pretty large (see above), however, it does contain the info we need: "minimumGasPrice" : "0x387ee40",. The final step to include the buffer:
$ node -e "console.log(0x387ee40 / 10 * 11);"
65164000

eth_getBlockByNumber.minimumgasPrice returns approximately 59 million, but we use approximately 65 million when submitting transactions.
For those familiar with Ethereum development, this is approach is different and only available on RSK.


text:
Q: how to fix PyCharm python console prompt? Somehow python console's working ability is lost in my PyCharm.
In python console, Normally after  "enter" primary prompt >>> we get >>> next line.
In my case after "enter" primary prompt >>>, I am getting secondary prompts ...
I am unable to execute anything with the python console.
If I run code from a script they run fine.
I have checked Run >> Edit Configuration >> execution with all options nothing works.

Does anyone know why it happens and how to fix it?
Thanks


text:
Q: multiple regexes on single string I have been looking for  solution to figure out how to apply multiple regexes using | (or) condition but it does not seem to work. Can someone shine some light on it? Here is what I have been trying to do. I searched StackOverflow for a solution and posting it here.
This is javascript language.
regex1 = "/d", regex2 = "/W"

merging both using | like this regex3 = new Regex(regex1+"|"+regex2,"gi");
This seems to work fine.
When I try to use the same login for lookahead, it fails.
Text to be searched:  Red _Red 'Red test
eg:
regex1 = "(?:^)red" , regex2 = "(?=[_])red"
regex3 = new Regex(regex1+"|"+regex2, "gi");

What am I missing here?

A: The issue with look-arounds is that they are "zero-width assertions" that don't actually match anything, so (?=_)red can never match "_red", because the "_", while seen by the lookahead, is never actually able to match.
We could fix your pattern like this:
(?:^)red|((?=[_]).)red

https://regex101.com/r/H9VSzQ/2/
Or simply get rid of the redundant lookahead (and the single-character character class!) and go ahead and match that underscore:
(?:_|^)red

https://regex101.com/r/flUTmp/1


text:
Q: Invalid email or password error when testing devise sign in with RSpec feature spec I keep getting Invalid email or password. error in RSpec feature test when I try to test sign in implemented using Devise.
spec/features/signing_in_spec.rb
require 'spec_helper'

feature 'Signing in' do
  let!(:user) { create :user }

  scenario 'signs in user with valid credentials', js: true do
    visit '/users/sign_in'

    fill_in 'Email', with: user.email
    fill_in 'Password', with: user.password
    click_button 'Sign in'

    expect(page).to have_content 'Dashboard'
  end
end

spec/factories/users.rb
FactoryGirl.define do
  factory :user do
    email 'user@mail.com'
    password '12345678'
    password_confirmation '12345678'

    factory :admin do
      email 'admin@mail.com'
    end
  end
end

I already verified that user is saved into DB and that sing in works in development.

A: I actually had the same issue
this https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara helped me.
I had to add this file to my support folder
https://github.com/railscasts/391-testing-javascript-with-phantomjs/blob/master/checkout-after/spec/support/share_db_connection.rb

A: I believe after you created your user record, the field password does not have its original value anymore. So try, instead of
fill_in 'Password', with: user.password

to use
fill_in 'Password', with: '12345678'

EDIT
You need to call skip_confirmation! on your user record, update your factory like this:
FactoryGirl.define do
  factory :user do
    email 'user@mail.com'
    password '12345678'
    password_confirmation '12345678'

    factory :admin do
      email 'admin@mail.com'
    end

    ignore { confirm_user true }

    after(:build) do |object, evaluator|
      object.skip_confirmation! if evaluator.confirm_user
    end
  end
end

If ever you need in another test to create a user without confirming it, you can call create :user, confirm_user: false

A: You can update specs like this:
describe "the signin process", :type => :feature do
  before :each do
    User.make(:email => 'user@example.com', :password => 'caplin')
  end

  it "signs me in" do
    visit '/sessions/new'
    within("#session") do
      fill_in 'Login', :with => 'user@example.com'
      fill_in 'Password', :with => 'password'
    end
    click_link 'Sign in'
    expect(page).to have_content 'Success'
  end
end


text:
Q: Linux shell scripting: How can I remove final numbers in a word list file? I have this example list text file (one word per line):
John
J0hn
John45
Smith
Sm1th
Jane
Jane333
Doe555

And I want to obtain:
John
J0hn
Smith
Sm1th
Jane
Doe

This is: I would like to remove numbers to the end of the words (note that numbers inside words are allowed) and then remove duplicates.
I have some experience in programming, so I could implement some loop/s to check for those numbers, and then another loop/s to remove duplicate words, but I think the Linux Shell must have some simple commands or parameter expansions that could solve this for me.
Removing original file sorting is a possibility, but it would be fine if some method does not require it.
Possible usage:

*

*Isolating words used in passwords databases (John, 45John, 12345John) to obtain statistics of diversity.

Ideas are welcome. Thanks you.
EDIT-1: whitespaces are not expected in this kind of "dictionary" text files (thanks you anyway, @rottweilers_anonymous).
EDIT-2: Added example of a possible ambiguity, a "word" that has only numbers: it must be left (I know, I know, that is not strictly a "word" ;-) ). Example original file:
John
J0hn
John45
Smith
Sm1th
Jane
Jane333
Doe555
12345

As long as a line like 12345 (numbers without word) is not really a number to the end of a word, I would like to keep it, so the results must be:
John
J0hn
Smith
Sm1th
Jane
Doe
12345

A: A simple way would be with sed and uniq:
sed "s/\([^0-9]\)[0-9]*\s*$/\1/" file | uniq

This does assume that the names are in order. If they aren't, you can use sort:
sed "s/\([^0-9]\)[0-9]*\s*$/\1/" file | sort -u

EDIT: per @rottweilers_anonymous suggestion, added the check for white space at the end of line.
EDIT: per OP's modification of question conditions, don't remove numbers from line that is only numbers.

A: Using perl :
$ perl -ne '/^\d+$/ or s/\d+$//;$names{$_}++;END{print sort keys %names} ' file

OUTPUT:
12345
Doe
J0hn
Jane
John
Sm1th
Smith

A: Here's awk in action - this also retains original order
awk '/[^[:digit:]]/{sub(/[[:digit:]]+$/, "")};!a[$0]++' file
John
J0hn
Smith
Sm1th
Jane
Doe
12345


text:
Q: JSON parsing returning a null value I am trying to parse the response i get from the network database. I am getting only one value i.e. seller id in response. When i try to pass it in JSON Object, somehow the toast after it doesn't execute and the toast after it is not executed.
I know there are many related questions but i can't find whats wrong... please help. Thanks.
        try {

        JSONArray jArray = new JSONArray(stuff.toString());

        Toast.makeText(this, "len: " + jArray.length(), 1000).show(); // length is 1

        for (int i = 0; i < jArray.length(); i++) {
            Toast.makeText(this, "Arr: " + stuff, 1000).show();
                              // Arr: [{"seller_id":"5"}]

            JSONObject jObject = jArray.getJSONObject(i);
            j_id = jObject.getString(stuff);

                            // not getting executed
            Toast.makeText(this, "JSON: " + j_id, 1000).show();
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    Toast.makeText(this, "View: " + j_id, 1000).show(); // j_id is giving null value

This is my json data [{"seller_id":"5"}] i am trying to get the value of seller id (ie 5 here) out of it.

A: There is a problem in jObject.getString() method args
JSONObject jObject = jArray.getJSONObject(i);
        j_id = jObject.getString(stuff);

Your giving the array. It should the name of the object i.e seller_id
so after the modification your code would be  j_id = jObject.getString("seller_id");

A: After the following code:
j_id = jObject.getString(stuff);

add            textview.settext(j_id);
and change  this textview  with your textview name
and if its not working  than show your complete json data.


text:
Q: /dev/loop0 doesn't have enough disk space I have too little space in my /dev/loop0 :
/dev/loop0 5,6G 5,1G 170M 97% /
none 3,0G 268K 3,0G 1% /dev
none 3,0G 1,5M 3,0G 1% /dev/shm
none 3,0G 144K 3,0G 1% /var/run
none 3,0G 0 3,0G 0% /var/lock
/dev/sda5 16G 9,5G 6,2G 61% /host
/dev/sdb1 373G 373G 130M 100% /media/disco externo-1

How can I expand the space for /dev/loop0?  Basically, the system is always warning about lack of space.
Thanks.

A: It seems you have installed through WUBI, so you can try this solution: How to increase wubi /root disk space


text:
Q: class giving an error and not running? So i have just learned how to use classes and i made this class but i can't make it to run i use
spacecraft1 = spacecraft(500,500,100,34)

to make the class
then on loop i use spacecraft1.motion() to update / move. From all of this i get error:
Traceback (most recent call last):
  File "C:\Users\Redstone3\Desktop\Desctop\Centers\game5\gameBuild 0.04.py", line 107, in <module>
    spacecraft1 = spacecraft(500,500,100,34)
TypeError: 'pygame.Surface' object is not callable

and is it possible to create like 40 of these spaceships at same time without defining everyone of them like
spacecraft1 = spacecraft(500,500,100,34)
spacecraft2 = spacecraft(500,500,100,34)
spacecraft3 = spacecraft(500,500,100,34)
spacecr...

Here is my class if it helps something. And this class and the main gamefile are in seperate files but in same folders.
import pygame
import random

class BaseClass(pygame.sprite.Sprite):

 allsprites = pygame.sprite.Group()
 def __init__(self, x, y, width, height,):

    pygame.sprite.Sprite.__init__(self)
    BaseClass.allsprites.add(self)

    self.shipDefaultUp = pygame.image.load("textures/ships/shipDefault/shipUP.png")
    self.shipDefaultRight = pygame.image.load("textures/ships/shipDefault/shipRIGHT.png")
    self.shipDefaultDown = pygame.image.load("textures/ships/shipDefault/shipDOWN.png")
    self.shipDefaultLeft = pygame.image.load("textures/ships/shipDefault/shipLEFT.png")

    self.shipCargo1Up = pygame.image.load("textures/ships/shipCargo1/shipCargo1UP.png")
    self.shipCargo1Right = pygame.image.load("textures/ships/shipCargo1/shipCargo1RIGHT.png")
    self.shipCargo1Down = pygame.image.load("textures/ships/shipCargo1/shipCargo1DOWN.png")
    self.shipCargo1Left = pygame.image.load("textures/ships/shipCargo1/shipCargo1LEFT.png")

    self.shipCargo2Up = pygame.image.load("textures/ships/shipCargo2/shipCargo2UP.png")
    self.shipCargo2Right = pygame.image.load("textures/ships/shipCargo2/shipCargo2RIGHT.png")
    self.shipCargo2Down = pygame.image.load("textures/ships/shipCargo2/shipCargo2DOWN.png")
    self.shipCargo2Left = pygame.image.load("textures/ships/shipCargo2/shipCargo2LEFT.png")

    self.image = pygame.image.load("textures/ships/shipDefault/shipUP.png")

    self.rect = self.image.get_rect()
    self.rect.x = x
    self.rect.y = y

    self.width = width
    self.height = height

    #self.dirrection = random.randrange(1,5)
    self.dirrection = 1
    self.timer = random.randrange(10,50)
    self.speed = random.randrange(2,10)

    self.shiptype = 3#random.randrange(1,3)

    #shiptypes#
    #1 = shipDefault
    #2 = shipCargo1
    #3 = shipCargo2

    self.move1 = ((1),(2),(4))
    self.move2 = ((1),(2),(3))
    self.move3 = ((2),(3),(4))
    self.move4 = ((1),(3),(4))

class spacecraft(BaseClass):
    ships = pygame.sprite.Group()

    def __init__(self, x, y, width, height,):
        BaseClass.__init__(self, x, y, width, height,)
        spacecraft.ships.add(self)

    def motion(self):

        #1 = UP
        #2 = RIGHT
        #3 = DOWN
        #4 = LEFT

        self.timer -=1

        if self.dirrection == 1: ##############SHIP UP
            self.rect.y -=self.speed

            if self.shiptype == 1:
                self.image = self.shipDefaultUp

            if self.shiptype == 2:
                self.image = self.shipCargo1Up

        if self.dirrection == 2:################SHIP RIGHT
            self.rect.x +=self.speed

            if self.shiptype == 1:
                self.image = self.shipDefaultRight

            if self.shiptype == 2:
                self.image = self.shipCargo1Right

            if self.shiptype == 3:
                self.image = self.shipCargo2Right

        if self.dirrection == 3: ##############SHIP DOWN
            self.rect.y +=self.speed

            if self.shiptype == 1:
                self.image = self.shipDefaultDown

            if self.shiptype == 2:
                self.image = self.shipCargo1Down

            if self.shiptype == 3:
                self.image = self.shipCargo2Down

        if self.dirrection == 4: ################SHIP LEFT
            self.rect.x -=self.speed

            if self.shiptype == 1:
                self.image = self.shipDefaultLeft

            if self.shiptype == 2:
                self.image = self.shipCargo1Left

            if self.shiptype == 3:
                self.image = self.shipCargo2Left

        if self.dirrection == 5:   ####IF SHIP IS NOT MOVING####
            print("loitter")

        if self.timer < 0:####GET NEW DIRECTION FOR SHIP####
            self.dirrection = random.randrange(1,6)
            self.timer = random.randrange(10,50)

Full code here(Google Drive)

A: Given that the error says "surface object not callable" that means at some point in your function where you think you are instantiating an instance of spacecraft, you have previously created a local variable containing a pygame.Surface object that overrides the class "spacecraft" from the global scope. Your class is not where the problem is, it's the previous code in the function where you're trying to instantiate it.
e.g.
 class spacecraft:
   ...

 def someOtherFunction:
    ...
    # this valid line of code is actually where the problem
    # is as it hides your spacecraft class with a local variable instead.
    spacecraft = some pygame.Surface instance
    ...
    spacecraft1 = spacecraft(...)
    ...


text:
Q: ssrs reporting report with addition RowNumber function I want to make report table in ssrs like this
row  D/C          nominal saldo

1   Credit        10      10
2   Debet         1       9 (from 10-1)
3   Credit        6       15 (from 9+6)

How to make function "saldo" field as above?
the logical flow
when row number = 1 then saldo = nominal (just for first row).
when row number = 2 and  D/C = Debit then "saldo" row 1 - nominal
when row number = 2 and  D/C = Credit then "saldo" row 1 + nominal
when row number = 3 and  D/C = Debit then "saldo" row 2 - nominal
when row number = 3 and  D/C = Credit then "saldo" row 2 + nominal

I'm trying to use function RowNumber (Nothing),
Iif(RowNumber(nothing)=1,Fields!nominal.Value),
Iif(RowNumber(nothing)=2 and Fields!dc.Value = "Debit",previousFields!saldo.Value - Fields!nominal.Value ),

and so on..
Could you give me suggestion about that scribs?
Regardz
Thanks

A: You can do this with a running total. Assuming your number are all positive then just check the debit/credit column and multiply the value by -1 when required.
Something like this should work.
=RunningValue(Fields!nomial.Value * (IIF(Fields!dc.Value="Debit",-1,1) ,Sum,"yourDataSetName")

If you really want the row number as well then you can just add a column with the expression set to =RowNumber(nothing)


text:
Q: SQL script to generate another [INSERT] SQL script I have a weird SQL situation in which I need to create a SQL script that I would run against database A and it would output another SQL script that would contain INSERT statements which I can then run against database B and upload the data (essentially an Export from A to B but a longer way).
I was wondering if anyone has worked on this an can suggest a way to generate INSERT statements that would contain data from [Database A].[Table Student] which can then be uploaded to [Database B].[Table Student].
Thanks a lot.

A: You can concat the values from student into an insert string like:
SELECT concat('Insert INTO Students VALUES(', Col1,', ', '''', Col2, '''', ')')
     AS [Details]
     FROM Student
     WHERE ...

N.B The four single quotes is to create a single quote before and after varchar columns for example.
To generate a new SQL script from this, I'd create a cmd file with something like:
SET SERVER=YOUR_SERVER
SET DATABASE=YOUR_DB

sqlcmd -S %SERVER% -d %DATABASE% -h -1 -i Script.sql -o NewScript.sql -W

A: --  You Can Simple Use insert into statement
INSERT INTO [Database B].[Table Student]
SELECT * FROM [Database A].[Table Student]
WHERE StudentID NOT IN (SELECT  StudentID FROM  [Database B].[Table Student])

A: Here is one way that would insert data from one database table to other database table
INSERT INTO [DestinationDB].[dbo].Student
SELECT * FROM [SourceDB].[dbo].Student
GO

A: If you have access to the both databases you can do it in one query like this:
INSERT INTO [Database A].[Table Student]
OUTPUT inserted.*
INTO [Database B].[Table Student]
SELECT *
FROM [newdata];


text:
Q: Como pegar a variavel de ambiente do arquivo .env utilizando Typescript? Estou utilizando a biblioteca dotenv para pegar a chave de API do Google Maps que está no arquivo .env, eu tentei dessa forma:
Imagem
Só que retornou esse erro :
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
dotenv: https://www.npmjs.com/package/dotenv

A: Bem eu estou com essa mesma dúvida atualmente...
Mas resolvi colocar uma exclamação após o uso dessa várialvel de ambiente, para o typescript não se preocupar com isso. Por que sabemos que essa várialvel de ambiente não vai deixar de existir ou ser undefined em algum momento dévido ao fato que nós mesmos vamos ter que declara-lá como váriavel de ambiente em hardcode no momento de fazer o deploy ou até no de desenvolvimento.


text:
Q: Speed and Time Problem
A boy is climbing up a flight of $35$ steps from Level $1$ to Level $2$ of a building. If he climbs at his fastest speed for $15$ steps and slowest speed for $15$ steps, he will take $40$ seconds to climb $30$ steps. If he climbs at his fastest speed for $26$ steps and slowest speed for $9$ steps, he will reach Level $2$ from Level $1$ in $41$ seconds. Find the shortest time it will take him to reach Level $2$ from Level $1$.

The conditions for the first given hint and the second given hint are different - one is for $30$ steps total and the other one is for $35$ steps. How would I solve this?

A: Set variables. Let his slowest speed be $x$ seconds per step and let his fastest speed be $y$ seconds per step. Then try to turn the pieces of data you have into equations.

A: Think of it this way: set his slowest speed as $x$ seconds per step, and his fastest speed as $y$ seconds per step. Then you can get two equations:
$(1)\,15\,\mathrm{steps} \cdot x\,\mathrm{\frac{secs}{step}}+15\,\mathrm{steps} \cdot y\,\mathrm{\frac{secs}{step}}=40\,\mathrm{secs}$
$(2)\,26\,\mathrm{steps} \cdot x\,\mathrm{\frac{secs}{step}}+9\,\mathrm{steps} \cdot y\,\mathrm{\frac{secs}{step}}=41\,\mathrm{secs}$
which cancels to
$(1)\,15x\,\mathrm{secs}+15y\,\mathrm{secs}=40\,\mathrm{secs}$
$(2)\,26x\,\mathrm{secs}+9y\,\mathrm{secs}=40\,\mathrm{secs}$
then, dividing the $\mathrm{secs}$ unit from each side
$(1)\,15x+15y=40$
$(2)\,26x+9y=41$
Can you solve from here? As you can see, the "different" amount of steps was merely an illusion. Generally you can break down system of equations problems questions like this using unit cancellation.


text:
Q: How can I create a stretching line with a box attached on a slider with jQuery? The line has a box attached to it which is the drag point for sliding and stretching the line.
How can I set the drag point outside the bar and modificate the line?


text:
Q: How do I perform a network process in a kotlin coroutine I am attempting to run the getByName method in my android app, but have found that doing so in the main activity is cause for concern. I know I need to use coroutines, or async, or threads. But I'm not sure how to go about this. I'm somewhat self-taught with the software so forgive any obvious errors.
'''
class MainActivity : AppCompatActivity() {

private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)

    val adr = getIpStr()
    val serverAdr = "http://" + adr + ":5000"
    val myWebView: WebView = findViewById(R.id.webView)
    myWebView.webViewClient = WebViewClient()
    myWebView.loadUrl(serverAdr)
}

fun goToSettings(view: View) {
    val intent = Intent(this, SettingsActivity::class.java)
    startActivity(intent)
}

private suspend fun getIpStr(): String? {
    delay(2000L)
    return getByName("raspberrypi").hostAddress
}
}

'''

A: You are getting exception because you starts your coroutine on main thread.
To perform network request,you need to use background thread .For that you can use " launch " coroutine builder with IO dispatcher to start new coroutine on background thread.
lifecycleScope.launch(Dispatchers.IO) {
val adr = getIpStr()
val serverAdr = "http://" + adr + ":5000"
//here switch to Main thread to Update your UI related task
withContext(Dispatchers.Main){
myWebView.loadUrl(serverAdr)}
}

A: You need to launch a coroutine using lifecycleScope:
lifecycleScope.launch {
    val adr = getIpStr()
    val serverAdr = "http://" + adr + ":5000"
    val myWebView: WebView = findViewById(R.id.webView)
    myWebView.webViewClient = WebViewClient()
    myWebView.loadUrl(serverAdr)
}

Alternatively, we can setup webview outside of launch():
val myWebView: WebView = findViewById(R.id.webView)
myWebView.webViewClient = WebViewClient()

lifecycleScope.launch {
    val adr = getIpStr()
    val serverAdr = "http://" + adr + ":5000"
    myWebView.loadUrl(serverAdr)
}


text:
Q: is there a way to append leading zero's to an ordered number list? (01 or 001 as opposed to just 1) by default when you use the
 tag to create an ordered list you get something like:
1.
.
.
10.
.
.
100
...but is there a way to change or style the format where it appends a certain number of leading zero's to the list? I want the numbers to all line up and my list will go into the hundreds so I would need 2 leading zero's for single digits, 1 leading zero for double digits, and none for triple digits:
001
.
.
010
.
.
100
I haven't created the list yet but I wanted to know before I start if there is a simple or easy way to do this? I only need this effect for ordered lists. Do not want it to be a universal effect.

A: ol {
    list-style-type: decimal-leading-zero;
}

A: You need to use JavaScript for this.
function addzeros(number, length) {
    var num = '' + number;
    while (num.length < length) {
        num = '0' + num;
    }
    return num;
}

alert(addzeros(100, 5))

Example usage
addzeros(1,3) will give you 001
addzeros(10,3) will give you 010
addzeros(100,0) will give you 100
addzeros(100,6) will give you 000100
Check working example at http://jsfiddle.net/ED8Hj/

A: Here's a CSS solution using counters:

ol {
  counter-reset: items;
}
li {
  display: block;
  counter-increment: items;
}
li:before {
  content: "00" counter(items)". ";
}
li:nth-child(n+10):before {
  content: "0" counter(items)". ";
}
li:nth-child(n+100):before {
  content: counter(items)". ";
}

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

Item 7

Item 8

Item 9

Item 10

Item 11

Item 12

Item 13

Item 14

Item 15

Item 16

Item 17

Item 18

Item 19

Item 20

Item 21

Item 22

Item 23

Item 24

Item 25

Item 26

Item 27

Item 28

Item 29

Item 30

Item 31

Item 32

Item 33

Item 34

Item 35

Item 36

Item 37

Item 38

Item 39

Item 40

Item 41

Item 42

Item 43

Item 44

Item 45

Item 46

Item 47

Item 48

Item 49

Item 50

Item 51

Item 52

Item 53

Item 54

Item 55

Item 56

Item 57

Item 58

Item 59

Item 60

Item 61

Item 62

Item 63

Item 64

Item 65

Item 66

Item 67

Item 68

Item 69

Item 70

Item 71

Item 72

Item 73

Item 74

Item 75

Item 76

Item 77

Item 78

Item 79

Item 80

Item 81

Item 82

Item 83

Item 84

Item 85

Item 86

Item 87

Item 88

Item 89

Item 90

Item 91

Item 92

Item 93

Item 94

Item 95

Item 96

Item 97

Item 98

Item 99

Item 100

Item 101

Item 102

Item 103

Item 104

Item 105

Item 106

Item 107

Item 108

Item 109

Item 110

Item 111

Item 112

Item 113

Item 114

Item 115

Item 116

Item 117

Item 118

Item 119

Item 120

Item 121

Item 122

Item 123

Item 124

Item 125

Item 126

Item 127

Item 128

Item 129

Item 130

Item 131

Item 132

Item 133

Item 134

Item 135

Item 136

Item 137

Item 138

Item 139

Item 140

Item 141

Item 142

Item 143

Item 144

Item 145

Item 146

Item 147

Item 148

Item 149

Item 150

Item 151

Item 152

Item 153

Item 154

Item 155

Item 156

Item 157

Item 158

Item 159

Item 160

Item 161

Item 162

Item 163

Item 164

Item 165

Item 166

Item 167

Item 168

Item 169

Item 170

Item 171

Item 172

Item 173

Item 174

Item 175

Item 176

Item 177

Item 178

Item 179

Item 180

Item 181

Item 182

Item 183

Item 184

Item 185

Item 186

Item 187

Item 188

Item 189

Item 190

Item 191

Item 192

Item 193

Item 194

Item 195

Item 196

Item 197

Item 198

Item 199

Item 200

Item 201

Item 202

Item 203

Item 204

Item 205

Item 206

Item 207

Item 208

Item 209

Item 210

Item 211

Item 212

Item 213

Item 214

Item 215

Item 216

Item 217

Item 218

Item 219

Item 220

Item 221

Item 222

Item 223

Item 224

Item 225

Item 226

Item 227

Item 228

Item 229

Item 230

Item 231

Item 232

Item 233

Item 234

Item 235

Item 236

Item 237

Item 238

Item 239

Item 240

Item 241

Item 242

Item 243

Item 244

Item 245

Item 246

Item 247

Item 248

Item 249

Item 250

Item 251

Item 252

Item 253

Item 254

Item 255

Item 256

Item 257

Item 258

Item 259

Item 260

Item 261

Item 262

Item 263

Item 264

Item 265

Item 266

Item 267

Item 268

Item 269

Item 270

Item 271

Item 272

Item 273

Item 274

Item 275

Item 276

Item 277

Item 278

Item 279

Item 280

Item 281

Item 282

Item 283

Item 284

Item 285

Item 286

Item 287

Item 288

Item 289

Item 290

Item 291

Item 292

Item 293

Item 294

Item 295

Item 296

Item 297

Item 298

Item 299

Item 300

Item 301

Item 302

Item 303

Item 304

Item 305

Item 306

Item 307

Item 308

Item 309

Item 310

Item 311

Item 312

Item 313

Item 314

Item 315

Item 316

Item 317

Item 318

Item 319

Item 320

Item 321

Item 322

Item 323

Item 324

Item 325

Item 326

Item 327

Item 328

Item 329

Item 330

Item 331

Item 332

Item 333

Item 334

Item 335

Item 336

Item 337

Item 338

Item 339

Item 340

Item 341

Item 342

Item 343

Item 344

Item 345

Item 346

Item 347

Item 348

Item 349

Item 350

Item 351

Item 352

Item 353

Item 354

Item 355

Item 356

Item 357

Item 358

Item 359

Item 360

Item 361

Item 362

Item 363

Item 364

Item 365

Item 366

Item 367

Item 368

Item 369

Item 370

Item 371

Item 372

Item 373

Item 374

Item 375

Item 376

Item 377

Item 378

Item 379

Item 380

Item 381

Item 382

Item 383

Item 384

Item 385

Item 386

Item 387

Item 388

Item 389

Item 390

Item 391

Item 392

Item 393

Item 394

Item 395

Item 396

Item 397

Item 398

Item 399

Item 400

Item 401

Item 402

Item 403

Item 404

Item 405

Item 406

Item 407

Item 408

Item 409

Item 410

Item 411

Item 412

Item 413

Item 414

Item 415

Item 416

Item 417

Item 418

Item 419

Item 420

Item 421

Item 422

Item 423

Item 424

Item 425

Item 426

Item 427

Item 428

Item 429

Item 430

Item 431

Item 432

Item 433

Item 434

Item 435

Item 436

Item 437

Item 438

Item 439

Item 440

Item 441

Item 442

Item 443

Item 444

Item 445

Item 446

Item 447

Item 448

Item 449

Item 450

Item 451

Item 452

Item 453

Item 454

Item 455

Item 456

Item 457

Item 458

Item 459

Item 460

Item 461

Item 462

Item 463

Item 464

Item 465

Item 466

Item 467

Item 468

Item 469

Item 470

Item 471

Item 472

Item 473

Item 474

Item 475

Item 476

Item 477

Item 478

Item 479

Item 480

Item 481

Item 482

Item 483

Item 484

Item 485

Item 486

Item 487

Item 488

Item 489

Item 490

Item 491

Item 492

Item 493

Item 494

Item 495

Item 496

Item 497

Item 498

Item 499

Item 500

Item 501

Item 502

Item 503

Item 504

Item 505

Item 506

Item 507

Item 508

Item 509

Item 510

Item 511

Item 512

Item 513

Item 514

Item 515

Item 516

Item 517

Item 518

Item 519

Item 520

Item 521

Item 522

Item 523

Item 524

Item 525

Item 526

Item 527

Item 528

Item 529

Item 530

Item 531

Item 532

Item 533

Item 534

Item 535

Item 536

Item 537

Item 538

Item 539

Item 540

Item 541

Item 542

Item 543

Item 544

Item 545

Item 546

Item 547

Item 548

Item 549

Item 550

Item 551

Item 552

Item 553

Item 554

Item 555

Item 556

Item 557

Item 558

Item 559

Item 560

Item 561

Item 562

Item 563

Item 564

Item 565

Item 566

Item 567

Item 568

Item 569

Item 570

Item 571

Item 572

Item 573

Item 574

Item 575

Item 576

Item 577

Item 578

Item 579

Item 580

Item 581

Item 582

Item 583

Item 584

Item 585

Item 586

Item 587

Item 588

Item 589

Item 590

Item 591

Item 592

Item 593

Item 594

Item 595

Item 596

Item 597

Item 598

Item 599

Item 600

Item 601

Item 602

Item 603

Item 604

Item 605

Item 606

Item 607

Item 608

Item 609

Item 610

Item 611

Item 612

Item 613

Item 614

Item 615

Item 616

Item 617

Item 618

Item 619

Item 620

Item 621

Item 622

Item 623

Item 624

Item 625

Item 626

Item 627

Item 628

Item 629

Item 630

Item 631

Item 632

Item 633

Item 634

Item 635

Item 636

Item 637

Item 638

Item 639

Item 640

Item 641

Item 642

Item 643

Item 644

Item 645

Item 646

Item 647

Item 648

Item 649

Item 650

Item 651

Item 652

Item 653

Item 654

Item 655

Item 656

Item 657

Item 658

Item 659

Item 660

Item 661

Item 662

Item 663

Item 664

Item 665

Item 666

Item 667

Item 668

Item 669

Item 670

Item 671

Item 672

Item 673

Item 674

Item 675

Item 676

Item 677

Item 678

Item 679

Item 680

Item 681

Item 682

Item 683

Item 684

Item 685

Item 686

Item 687

Item 688

Item 689

Item 690

Item 691

Item 692

Item 693

Item 694

Item 695

Item 696

Item 697

Item 698

Item 699

Item 700

Item 701

Item 702

Item 703

Item 704

Item 705

Item 706

Item 707

Item 708

Item 709

Item 710

Item 711

Item 712

Item 713

Item 714

Item 715

Item 716

Item 717

Item 718

Item 719

Item 720

Item 721

Item 722

Item 723

Item 724

Item 725

Item 726

Item 727

Item 728

Item 729

Item 730

Item 731

Item 732

Item 733

Item 734

Item 735

Item 736

Item 737

Item 738

Item 739

Item 740

Item 741

Item 742

Item 743

Item 744

Item 745

Item 746

Item 747

Item 748

Item 749

Item 750

Item 751

Item 752

Item 753

Item 754

Item 755

Item 756

Item 757

Item 758

Item 759

Item 760

Item 761

Item 762

Item 763

Item 764

Item 765

Item 766

Item 767

Item 768

Item 769

Item 770

Item 771

Item 772

Item 773

Item 774

Item 775

Item 776

Item 777

Item 778

Item 779

Item 780

Item 781

Item 782

Item 783

Item 784

Item 785

Item 786

Item 787

Item 788

Item 789

Item 790

Item 791

Item 792

Item 793

Item 794

Item 795

Item 796

Item 797

Item 798

Item 799

Item 800

Item 801

Item 802

Item 803

Item 804

Item 805

Item 806

Item 807

Item 808

Item 809

Item 810

Item 811

Item 812

Item 813

Item 814

Item 815

Item 816

Item 817

Item 818

Item 819

Item 820

Item 821

Item 822

Item 823

Item 824

Item 825

Item 826

Item 827

Item 828

Item 829

Item 830

Item 831

Item 832

Item 833

Item 834

Item 835

Item 836

Item 837

Item 838

Item 839

Item 840

Item 841

Item 842

Item 843

Item 844

Item 845

Item 846

Item 847

Item 848

Item 849

Item 850

Item 851

Item 852

Item 853

Item 854

Item 855

Item 856

Item 857

Item 858

Item 859

Item 860

Item 861

Item 862

Item 863

Item 864

Item 865

Item 866

Item 867

Item 868

Item 869

Item 870

Item 871

Item 872

Item 873

Item 874

Item 875

Item 876

Item 877

Item 878

Item 879

Item 880

Item 881

Item 882

Item 883

Item 884

Item 885

Item 886

Item 887

Item 888

Item 889

Item 890

Item 891

Item 892

Item 893

Item 894

Item 895

Item 896

Item 897

Item 898

Item 899

Item 900

Item 901

Item 902

Item 903

Item 904

Item 905

Item 906

Item 907

Item 908

Item 909

Item 910

Item 911

Item 912

Item 913

Item 914

Item 915

Item 916

Item 917

Item 918

Item 919

Item 920

Item 921

Item 922

Item 923

Item 924

Item 925

Item 926

Item 927

Item 928

Item 929

Item 930

Item 931

Item 932

Item 933

Item 934

Item 935

Item 936

Item 937

Item 938

Item 939

Item 940

Item 941

Item 942

Item 943

Item 944

Item 945

Item 946

Item 947

Item 948

Item 949

Item 950

Item 951

Item 952

Item 953

Item 954

Item 955

Item 956

Item 957

Item 958

Item 959

Item 960

Item 961

Item 962

Item 963

Item 964

Item 965

Item 966

Item 967

Item 968

Item 969

Item 970

Item 971

Item 972

Item 973

Item 974

Item 975

Item 976

Item 977

Item 978

Item 979

Item 980

Item 981

Item 982

Item 983

Item 984

Item 985

Item 986

Item 987

Item 988

Item 989

Item 990

Item 991

Item 992

Item 993

Item 994

Item 995

Item 996

Item 997

Item 998

Item 999

A: This can be done, depending on the browser. (Experimental api)
    @counter-style pad-3 {
        system: numeric;
        symbols: "0" "1" "2" "3" "4" "5" "6" "7" "8" "9";
        pad: 3 "0";
    }
    ol {
      list-style-type: pad-3;
     }


text:
Q: Split Line at Point not working in ArcGIS Desktop?
While i was using the "Split Line at Point" function with two features, both with 80000 point features and 90000 line features each, the finished result wouldnt split on the points. It would split a bit further away from the desired point.
Given the line feature has multiple lines overlapping indicating the multiple "routes", is there any way i could split the line features by point regardless of how many line feature it has beneath?
The picture shows what happens after i split using points. The points are on top/intersecting the line feature.


text:
Q: Excel listObject doesn't show updated values in worksheet.Change event I have an excel table created programmatically, which uses a List<Object> as a data source. I am creating this table by adding a ListObject using Tools.Worksheet AddListObject(), and then assigning listObject.DataSource with List<Object>. Table is getting created and works fine and user can edit any cell/row in a table.
I am handling edits using the WorkSheet.Change event. When a user edits a cell which belongs to a table the worksheet.Change event is fired (Verified by setting a breakpoint in the Change event handler) as expected.
I am accessing the table/listObject using target sent to Change event handler then I am using Factory.GetVstoObject(target.ListObject) to get Tools.ListObject. Everything works fine till this point.
Issue:
When I access ListObject.DataSource, I see that the values in dataSource is not updated with new value. I need this new value in workSheet.Change event to do some validation and other stuff. Why am I not seeing updated values in Change event handler? DataSource values should be updated to new values before reaching WorkSheet.Change event handler right? Is there any way to fix this issue or Is there any other way to get new values of table/listObject?
PS: After change event handler is executed and say if User edits again, I see 1st edited value in listObject.DataSource (Not 2nd edit value). I tried ListObject.Change event as well, still seeing old value.
Here's the code :
This is how I am creating a new worksheet.
public static Worksheet CreateNewExcelSheet(string sheetName)
{
    var newWorksheet = (Worksheet)Globals.ThisAddIn.Application.Worksheets.Add();
    newWorksheet.Name = sheetName;
    newWorksheet.Activate();
    newWorksheet.Change += WorkSheetChange_EventHandler;
    newWorksheet.CustomProperties.Add(IsTableSelected, "false");
    return newWorksheet;
}

Code for creating listobject:
public static Tools.ListObject CreateListObject(Worksheet workSheet, Range startingPosition, string listObjectName)
{
    var vstoWorkSheetObject = GetVstoWorkSheetObject(workSheet);
    var listObject =
    vstoWorkSheetObject.Controls.AddListObject(startingPosition, listObjectName);
    listObject.Deselected += ListObject_Deselected;
    listObject.Selected += ListObjectOnSelected;
    listObject.Change += ListObject_Change;
    listObject.DataBindings.Clear();
    listObject.TableStyle = TableStyle;
    return listObject;
}

Main Code:
private void CreateTable(string sheetName, string listObjectName)
{
    var workSheet = CreateNewExcelSheet(sheetName);
    var listObject = CreateListObject(workSheet, Globals.ThisAddIn.Application.Range["A4"], listObjectName);
    listObject.SetDataBinding(dataSourceFromServer);
    var counter = 0;
    foreach (Range cell in listObject.HeaderRowRange.Cells)
    {
        cell.Value2 = ColumnNames[counter];
        counter++;
    }
    listObject.HeaderRowRange.EntireColumn.AutoFit();
}

dataSourceFromServer is of type List<Object>


text:
Q: Loading a Reusable UITableViewCell from a Nib I am able to design custom UITableViewCells and load them just fine using the technique described in the thread found at http://forums.macrumors.com/showthread.php?t=545061.  However, using that method no longer allows you to init the cell with a reuseIdentifier which means you have to create whole new instances of each cell at every call.  Has anyone figured out a good way to still cache particular cell types for reuses, but still be able to design them in Interface Builder?

A: Just implement a method with the appropriate method signature:
- (NSString *) reuseIdentifier {
  return @"myIdentifier";
}

A: As of iOS circa 4.0, there are specific instructions in the iOS docs that make this work super-fast:
http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/TableViewCells/TableViewCells.html#//apple_ref/doc/uid/TP40007451-CH7
Scroll down to where it talks about subclassing UITableViewCell.

A: Now, in iOS 5 there is an appropriate UITableView method for that:
- (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier

A: Here is another option:
NSString * cellId = @"reuseCell";
//...
NSArray * nibObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomTableCell" owner:nil options:nil];

for (id obj in nibObjects)
{
    if ([obj isKindOfClass:[CustomTableCell class]])
    {
        cell = obj;
        [cell setValue:cellId forKey:@"reuseIdentifier"];
        break;
    }
}

A: I can't remember where I found this code originally, but it's been working great for me so far.
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"CustomTableCell";
    static NSString *CellNib = @"CustomTableCellView";

    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:CellNib owner:self options:nil];
        cell = (UITableViewCell *)[nib objectAtIndex:0];
    }

    // perform additional custom work...

    return cell;
}

Example Interface Builder setup...

A: Louis method worked for me.  This is the code I use to create the UITableViewCell from the nib:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"CustomCellId"];

    if (cell == nil)
    {
        UIViewController *c = [[UIViewController alloc] initWithNibName:@"CustomCell" bundle:nil];
        cell = (PostCell *)c.view;
        [c release];
    }

    return cell;
}

A: I create my custom view cells in a similar manner - except I connect the cell through an IBOutlet.
The [nib objectAt...] approach is susceptible to changes to positions of items in the array.
The UIViewController approach is good - just tried it, and it works nice enough.
BUT...
In all cases the initWithStyle constructor is NOT called, so no default initialisation is done.
I have read various places about using initWithCoder or awakeFromNib, but no conclusive evidence that either of these is the right way.
Apart from explicitly calling some initialization method in the cellForRowAtIndexPath method I haven't found an answer to this yet.

A: A while back I found a great blog post on this topic at blog.atebits.com, and have since started using Loren Brichter ABTableViewCell class to do all of my UITableViewCells.
You end up with a simple container UIView to put all of your widgets, and scrolling is lightning fast.
Hope this is useful.

A: This technique also works and doesn't require a funky ivar in your view controller for memory management.
Here, the custom table view cell lives in a xib named "CustomCell.xib".
 static NSData *sLoadedCustomCell = nil;

 cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
 if (cell == nil)
 {
   if (sLoadedCustomCell == nil)
   {
      // Load the custom table cell xib
      // and extract a reference to the cell object returned
      // and cache it in a static to avoid reloading the nib again.

      for (id loadedObject in [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:nil options:nil])
      {
        if ([loadedObject isKindOfClass:[UITableViewCell class]])
        {
          sLoadedCustomCell = [[NSKeyedArchiver archivedDataWithRootObject: loadedObject] retain];
          break;
        }
    }
    cell = (UITableViewCell *)[NSKeyedUnarchiver unarchiveObjectWithData: sLoadedCustomCell];
  }

A: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *simpleTableIdentifier = @"CustomCell";

CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
    cell = [nib objectAtIndex:0];

    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}

return cell;
}

A: Look at the answer I gave to this question:
Is it possible to design NSCell subclasses in Interface Builder?
It's not only possible to design a UITableViewCell in IB, it's desirable because otherwise all of the manual wiring and placement of multiple elements is very tedious.  Performaance is fine as long as you are careful to make all elements opaque when possible.  The reuseID is set in IB for the properties of the UITableViewCell, then you use the matching reuse ID in code when attempting to dequeue.
I also heard from some of the presenters at WWDC last year that you shouldn't make table view cells in IB, but it's a load of bunk.

A: Actually, since you are building the cell in Interface Builder, just set the reuse identifier there:

Or if you are running Xcode 4, check the Attributes inspector tab:

(Edit: After your XIB is generated  by XCode, it contains an empty UIView, but we need a UITableViewCell; so you have to manually remove the UIView and insert a Table View Cell. Of course, IB will not show any UITableViewCell parameters for a UIView.)

A: The gustavogb solution doesn't work for me, what I tried is :
ChainesController *c = [[ChainesController alloc] initWithNibName:@"ChainesController" bundle:nil];
[[NSBundle mainBundle] loadNibNamed:@"ChaineArticleCell" owner:c options:nil];
cell = [c.blogTableViewCell retain];
[c release];

It seems to work.
The blogTableViewCell is the IBOutlet for the cell and ChainesController is the file's owner.

A: From the UITableView docs regarding dequeueWithReuseIdentifier: "A string identifying the cell object to be reused. By default, a reusable cell's identifier is its class name, but you can change it to any arbitrary value."
Overriding -reuseIdentifer yourself is risky. What happens if you have two subclasses of your cell subclass, and use both of these in a single table view? If they send the reuse identifier call onto super you'll dequeue a cell of the wrong type.............. I think you need to override the reuseIdentifier method, but have it return a supplanted identifier string. Or, if one has not been specified, have it return the class as a string.

A: For what it's worth, I asked an iPhone engineer about this at one of the iPhone Tech Talks. His answer was, "Yes, it's possible to use IB to create cells. But don't. Please, don't."

A: I followed Apple's instructions as linked by Ben Mosher (thanks!) but found that Apple omitted an important point.  The object they design in IB is just a UITableViewCell, as is the variable they load from it.  But if you actually set it up as a custom subclass of UITableViewCell, and write the code files for the subclass, you can write IBOutlet declarations and IBAction methods in the code and wire them up to your custom elements in IB.  Then there is no need to use view tags to access these elements and you can create any kind of crazy cell you want.  It's Cocoa Touch heaven.


text:
Q: How to use and create tag library for select (combobox) in grails I'm very new to grails, What I want to do is load the data elements from enum class to the select(combo box) then create an tag library for it.
Tag library class
package feedback
import imocha.project.Feedback
import imocha.project.FeedbackType

class FeedbackTagLib {
   static namespace = "l"

    def enumFeedbackType ={attrs, body ->
        attrs.name = "type"
        attrs.from = "${FeedbackType.values()}"
        out << g.select(attrs.name, attrs.from, attrs.value, attrs.optionKey)
    }
}

Enum class
public enum FeedbackType {
    CLA('Complaint'),
    CLE('Complement'),
    ENQ('Enquiry')

    final String value
    FeedbackType(String value){ this.value = value }

    @Override
    String toString(){ value }
    String getKey() { name() }

}

I called the tag library in GSP with this
<l:enumFeedbackType value="${feedbackInstance?.type}" optionKey ="key" />

This is the errors
URI /feedback/feedback/create
Class groovy.lang.MissingMethodException
Message No signature of method: org.codehaus.groovy.grails.web.pages.GroovyPage.select() is applicable for argument types: (java.lang.String, org.codehaus.groovy.runtime.GStringImpl, null, null) values: [type, [Complaint, Complement, Enquiry], null, null] Possible solutions: collect(), getOut(), inspect(), every()

A: this should work:
def enumFeedbackType ={attrs, body ->
    attrs.name = "type"
    attrs.from = FeedbackType.values()
    out << g.select(attrs)
}


text:
Q: Using jQuery at Console? I'm learning more about jQuery and would like to use it interactively at the JavaScript console in Chrome. Is that possible? I envision something like this, but it doesn't work:
> use('jquery.js')
jquery loaded
> $("span").html("Hello World!")

This would cause "Hello World!" to be inserted between the span tags and displayed.

A: If you have jQuery included in the page that you have the console open on you should be free to use it in the console.

A: The simpliest way to do this, is to edit the header of the page and add a <script> tag pointing to jQuery.
Then you will be able to execute the code in your console.

A: There is no "use" so of course it will not work.
You can append it to a page.
var scr = document.createElement("script");
scr.src = "http://code.jquery.com/jquery-1.9.1.min.js";
document.body.appendChild(scr);

A: Never mind. Figured it out :-) I created a simple HTML file that loaded jQuery and then went into the console. This works for me.

A: You may want to check out http://jsfiddle.net/ or http://codepen.io/pen/
You can still access the scripts you create via the chrome console and it will be easier to share with others if you have any questions.

A: If you want to use jQuery frequently from the console you can easily write a userscript.
First, install Tampermonkey if you are on Chrome and Greasemonkey if you are on Firefox. Write a simple userscript with a use function like this:
var scripts = []
function use(libname){
var src;
if(scripts.indexOf(libname)==-1){
switch(libname.toLowerCase()){
case "jquery":
src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
break;
case "angularjs":
src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js";
break;
}
}else{
console.log("Library already in use.");
return;
}
if(src){
scripts.append(libname);
var script = document.createElement("script");
script.src = src;
document.body.appendChild(scr);
}else{
console.log("Invalid Library.");
return;
}
}


text:
Q: Cannot query UserRecordAccess for Tasks I am running my query using the Rest API, but I have reproduced the issue in Workbench as well. The below query works for Account, Opportunity, and Contact, but fails for Task:
SELECT UserRecordAccess.MaxAccessLevel FROM Task

The above query gives an error.
Why? Workarounds?

A:
Why?

The reason why is that activities are expensive to calculating sharing for. While this isn't called out in any manual I could find, I'm certain that's the reason. If you haven't noticed, UserRecordAccess is limited to just a handful of records at a time (you need to specify a user Id and a list of record Ids).
Using the "parent-style" relationship would cause the query to consume tons of resources and slow down the query significantly. They simply don't want you to do this.
In fact, activities in general usually dominate an average org's storage usage, and further, that's why you'll notice that queries against activities must be more selective than (almost) any other type of object (at least for non-admins), are regularly "archived", and have more restrictive data limitations, such as the number and type of fields you can store in activities.
Interestingly enough, they aren't even listed on the SOQL and SOSL Limits page, even though they're some of the most restricted objects in salesforce (but not as restricted as, say, UserRecordAccess itself).

Workarounds?

Query UserRecordAccess directly. This means you'll need to use at least two queries to get a list of tasks or events and the associated UserRecordAccess data (per user per 200 activities per type). There's no two ways about it.

A: The UserRecordAcceess table is more of a "child" object than a parent (more on that later). I think your query should actually be:
SELECT RecordId, MaxAccessLevel FROM UserRecordAccess WHERE ...

Without any WHERE clause it throws:

Where clause must contain UserId = [single ID]

First I tried:
WHERE Record.Type = 'Task'

but it doesn't work. Apparently it's not a true relationship.

Didn't understand relationship 'Record' in field path.

How about the the following?
WHERE RecordId LIKE '00T%'

Nope.

Can filter on only UserId = [single ID], either RecordId = [single ID] or RecordId IN [list of IDs], and Has*Access = true

Hmm, a bit arcane, but it seems to imply that you can only query for access one user at a time. So it seems you may need one request for every User you want to check. For instance I can figure out all records I can access with the following Execute Anonymous script:
Set<Id> taskIds = new Map<Id, Task>([SELECT Id FROM Task LIMIT 10000]).keySet();
system.debug([
    SELECT RecordId, MaxAccessLevel FROM UserRecordAccess
    WHERE UserId = :UserInfo.getUserId()
    AND RecordId IN :taskIds
]);

The following fails with the same error message, implying that you indeed cannot request access levels for multiple users per request.
system.debug([
    SELECT RecordId, MaxAccessLevel FROM UserRecordAccess
    WHERE UserId IN :(UserInfo.getUserId())
    AND RecordId IN :()
]);


text:
Q: If catching null pointer exception is not a good practice, is catching exception a good one? I have heard that catching NullPointerException is a bad practice, and i think it is sensibly so. Letting the NullPointerException to propagate to the top would allow the detection of a something going wrong. But many times I have seen many of my friends catching Exception directly so that they need not bother about all the different kinds of exceptions that might occur in the above code. Is this a good practice? What are the other kinds of exceptions that are best left unhandled? And besides it also makes sense to me to handle NullPointerException over a specific code where we are sure of the source of the exception. So when are exceptions to be handled and when should they not be handled? And what would be the possible list of exception that are best left unhandled?

A: You should only catch an Exception if you can add some value by doing so. Otherwise you should let it pass to the caller.
NullPointerException is usually the result of a bug in your code.  How can you sensibly fix this in a catch block?
Not being bothered about Exceptions is not good practice.

A: In general, the only times you should catch an exception is if you can handle it in some meaningful way. If you can't you should simply let it bubble to the top and terminate the process. For instance, could you recover in some meaningful way from a NullPointerException or I/O error? I think not.
My rules for exception handling:

*

*In general, don't catch exceptions, unless you can handle them in some meaningful way.

*Catch exceptions at process/machine boundaries, log the caught exception along with any context available to you and re-throw it. If the exception is a custom exception, you may wrap it in an exception of a type known/useful to the invoking process and throw that.

*You may also catch exceptions at a low level, where you have the most runtime context available, log the exception and associated context, then rethrow the exception.

*When rethrowing, use throw ; rather than throw caughtException ;. Use of the former syntax preserves the original stack trace; use of the latter syntax creates a new stack trace, beginning with throw caughtException ; -- you lose all the context and call stack up to the point at which the exception was caught.

*You may, if you so choose, catch exceptions at a high level and gracefully terminate the process, logging the exception information so as to help debug and correct the underlying problem.

Do not use exceptions as a flow control mechanism (if possible). Exceptions are supposed to be, well, exceptional in nature. Rather, premptively, enforce the caller's end of the contract (preconditions) for any methods you are invoking.
See Bertrand Meyers' book , Object Oriented Software Construction, 2nd ed. for more information.

A: Pokemon exception-handling is bad. Especially, if it's an empty block and you're simply swallowing them. You have specifically-typed exceptions for the reason that they actually mean specific things in specific contexts (essentially they're telling you what went wrong). So by catching Exception you're saying that you don't care what those exceptions are and that you don't care what happened. This is probably not what you want.
In general, when catching exceptions follow these rules:

*

*Does it make sense to handle the exception at this level? If yes, then handle it. If not, then propagate.

*In conjunction with the first rule, "handling" can also mean, catching, wrapping, and re-throwing. This is a way of preventing abstraction-leakage so that callers of your method don't have to know about the underlying implementation.

*An empty catch block doesn't mean that you've handled the exception. That's called "swallowing"; at the very least, you want to log the exception. Sometimes an exception happening is actually part of the logical flow of your code, and so you might want to do something special (but this is, pardon the pun, the exception rather than the rule. It is better to check for situations that cause exceptions rather than incorporating them into the logical flow of your code).

You can easily check for a null value in your code, so there is no need to explicitly catch a null-pointer exception. It doesn't make sense to let a NullPointerException happen (and it's bad practice). Even if you have some code that throws a NullPointerException, and it is code that you do not control and cannot fix, you should determine the input parameters that cause the NullPointerException and specifically test for them.
Another exception that you shouldn't catch is the IllegalArgumentException. This exception means that you've passed in an argument that does not make sense. Instead of catching this exception, you should explicitly test your input parameters to ensure that they are sane and that they cannot cause an IllegalArgumentException.

A: The 'reason' that catching NullPointerException is considered a bad practice is not because you're supposed to let it bubble up when something goes wrong!  Saying any exception is 'best left unhandled' based solely on its type seems like a bad idea.
A NPE is considered the result of a programming error.  A strictly correct program should never generate one.  The reason seeing it caught is bad is it usually means that the code threw one, and the programmer decided to just catch it and cover it up, rather than fix the broken code that caused it in the first place!
If, for example, you were coupled for business reasons to an API that has a bug inside and occassionally throws a null pointer, it would be perfectly legitimate to catch it, do something about it/inform the user with a better message.  Letting 'null' hit the UI just because someone said "Catching Null Pointer Exception is bad" would make no sense!
Catching java.lang.Exception can be legitimate in specific cases, but generally "I'm lazy" is not one of them. :)   For example if you're implementing an API and want to make absolutely sure no exception ever comes out of it that isn't in the specification, you might catch Exception and wrap it in some application exception you've defined.

A: The main rule about catching exception is that you have to know why you are doing this. Exception class is caught in cases when programmer wants to do generic error processing and he does not really care what exactly happened, the main thing is just something went wrong. In that case he may decide to rollback transaction or do some cleanup.
If you are catching specific exception try to apply the same rule. I you know exactly why you are doing that, then it's to do that. But it's very rare case when someone would want to do something really special in case of NPE.

A: if you have a graceful way to handle your exception it is useful to catch it, if not hope that the caller has a nice way to handle it.


text:
Q: Toastr for Form validation Im trying to replace javascript alerts with Toastr.  I have successfully linked both css and script.
For example: If the textbox is empty, a Toastr will pop up showing "Please enter your ID". Im new to this Thanks!
HTML Form
<form action="#" method="POST" role="form" onsubmit= "required()" autocomplete="off" name="loginform">

<input type="text" class="form-control" placeholder="Employee Number" name="emp_id" id="emp_id">

<button type="submit" name="login">Sign In</button>

</form>

Script
<script>
function required()
{
var empt = document.loginform.emp_id.value;
if (empt === "")
{
**// enter toastr command here**
return false;
}
else
{
// success
return true;
}
}
</script>

A: I assume that you are using toastr.js so here's the documentation on how to use it
https://github.com/CodeSeven/toastr
Example:
toastr.info('Are you the 6 fingered man?')

A: If you're using Toastrjs you can do something like this:
<script>
function required(){
  var empt = document.loginform.emp_id.value;
  if (empt.length <= 0){
    toastr.error('Please enter your ID')
    return false;
  }
  else {
  // success
  return true;
  }
}
</script>