text:
Q: Searchable index gets locked on manual update (LockObtainFailedException) We have a Grails project that runs behind a load balancer.  There are three instances of the Grails application running on the server (using  separate Tomcat instances). Each instance has its own searchable index. Because the indexes are separate, the automatic update is not enough keeping the index consistent between the application instances. Because of this we have disabled the searchable index mirroring and updates to the index are done manually in a scheduled quartz job. According to our understanding no other part of the application should modify the index.
The quartz job runs once a minute and it checks from the database which rows have been updated by the application, and re-indexes those objects. The job also checks if the same job is already running so it doesn't do any concurrent indexing. The application runs fine for few hours after the startup and then suddenly when the job is starting, LockObtainFailedException  is thrown:

22.10.2012 11:20:40 [xxxx.ReindexJob] ERROR Could not update searchable index, class org.compass.core.engine.SearchEngineException:
  Failed to open writer for sub index [product]; nested exception is
  org.apache.lucene.store.LockObtainFailedException: Lock obtain timed
  out:
  SimpleFSLock@/home/xxx/tomcat/searchable-index/index/product/lucene-a7bbc72a49512284f5ac54f5d7d32849-write.lock

According to the log the last time the job was executed, re-indexing was done without any errors and the job finished successfully. Still, this time the re-index operation throws the locking exception, as if the previous operation was unfinished and the lock had not been released. The lock will not be released until the application is restarted.
We tried to solve the problem by manually opening the locked index, which causes the following error to be printed to the log:

22.10.2012 11:21:30 [manager.IndexWritersManager   ] ERROR Illegal state, marking an index writer as open, while another is marked as
  open for sub index [product]

After this the job seems to be working correctly and doesn't become stuck in a locked state again. However this causes the application to constantly use 100 % of the CPU resource. Below is a shortened version of the quartz job code.
Any help would be appreciated to solve the problem, thanks in advance.
class ReindexJob {

def compass
...

static Calendar lastIndexed

static triggers = {
    // Every day every minute (at xx:xx:30), start delay 2 min
    // cronExpression:                           "s  m h D M W [Y]"
    cron name: "ReindexTrigger", cronExpression: "30 * * * * ?", startDelay: 120000
}

def execute() {
    if (ConcurrencyHelper.isLocked(ConcurrencyHelper.Locks.LUCENE_INDEX)) {
        log.error("Search index has been locked, not doing anything.")
        return
    }

    try {
        boolean acquiredLock = ConcurrencyHelper.lock(ConcurrencyHelper.Locks.LUCENE_INDEX, "ReindexJob")
        if (!acquiredLock) {
            log.warn("Could not lock search index, not doing anything.")
            return
        }

        Calendar reindexDate = lastIndexed
        Calendar newReindexDate = Calendar.instance
        if (!reindexDate) {
            reindexDate = Calendar.instance
            reindexDate.add(Calendar.MINUTE, -3)
            lastIndexed = reindexDate
        }

        log.debug("+++ Starting ReindexJob, last indexed ${TextHelper.formatDate("yyyy-MM-dd HH:mm:ss", reindexDate.time)} +++")
        Long start = System.currentTimeMillis()

        String reindexMessage = ""

        // Retrieve the ids of products that have been modified since the job last ran
        String productQuery = "select p.id from Product ..."
        List<Long> productIds = Product.executeQuery(productQuery, ["lastIndexedDate": reindexDate.time, "lastIndexedCalendar": reindexDate])

        if (productIds) {
            reindexMessage += "Found ${productIds.size()} product(s) to reindex. "

            final int BATCH_SIZE = 10
            Long time = TimeHelper.timer {
                for (int inserted = 0; inserted < productIds.size(); inserted += BATCH_SIZE) {
                    log.debug("Indexing from ${inserted + 1} to ${Math.min(inserted + BATCH_SIZE, productIds.size())}: ${productIds.subList(inserted, Math.min(inserted + BATCH_SIZE, productIds.size()))}")
                    Product.reindex(productIds.subList(inserted, Math.min(inserted + BATCH_SIZE, productIds.size())))
                    Thread.sleep(250)
                }
            }

            reindexMessage += " (${time / 1000} s). "
        } else {
            reindexMessage += "No products to reindex. "
        }

        log.debug(reindexMessage)

        // Re-index brands
        Brand.reindex()

        lastIndexed = newReindexDate

        log.debug("+++ Finished ReindexJob (${(System.currentTimeMillis() - start) / 1000} s) +++")
    } catch (Exception e) {
        log.error("Could not update searchable index, ${e.class}: ${e.message}")
        if (e instanceof org.apache.lucene.store.LockObtainFailedException || e instanceof org.compass.core.engine.SearchEngineException) {
            log.info("This is a Lucene index locking exception.")
            for (String subIndex in compass.searchEngineIndexManager.getSubIndexes()) {
                if (compass.searchEngineIndexManager.isLocked(subIndex)) {
                    log.info("Releasing Lucene index lock for sub index ${subIndex}")
                    compass.searchEngineIndexManager.releaseLock(subIndex)
                }
            }
        }
    } finally {
        ConcurrencyHelper.unlock(ConcurrencyHelper.Locks.LUCENE_INDEX, "ReindexJob")
    }
}
}

Based on JMX CPU samples, it seems that Compass is doing some scheduling behind the scenes. From 1 minute CPU samples it seems like there are few things different when normal and 100% CPU instances are compared:

*

*org.apache.lucene.index.IndexWriter.doWait() is using most of the CPU time.

*Compass Scheduled Executor Thread is shown in the thread list, this was not seen in a normal situation.

*One Compass Executor Thread is doing commitMerge, in a normal situation none of these threads was doing commitMerge.

A: You can try increasing the 'compass.transaction.lockTimeout' setting. The default is 10 (seconds).
Another option is to disable concurrency in Compass and make it synchronous. This is controlled with the  'compass.transaction.processor.read_committed.concurrentOperations': 'false' setting. You might also have to set 'compass.transaction.processor' to 'read_committed'
These are the compass settings we are currently using:
compassSettings = [
'compass.engine.optimizer.schedule.period': '300',
'compass.engine.mergeFactor':'1000',
'compass.engine.maxBufferedDocs':'1000',
'compass.engine.ramBufferSize': '128',
'compass.engine.useCompoundFile': 'false',
'compass.transaction.processor': 'read_committed',
'compass.transaction.processor.read_committed.concurrentOperations': 'false',
'compass.transaction.lockTimeout': '30',
'compass.transaction.lockPollInterval': '500',
'compass.transaction.readCommitted.translog.connection': 'ram://'
]

This has concurrency switched off. You can make it asynchronous by changing the 'compass.transaction.processor.read_committed.concurrentOperations' setting to 'true'. (or removing the entry).
Compass configuration reference:
http://static.compassframework.org/docs/latest/core-configuration.html
Documentation for the concurrency of read_committed processor:
http://www.compass-project.org/docs/latest/reference/html/core-searchengine.html#core-searchengine-transaction-read_committed
If you want to keep async operations, you can also control the number of threads it uses. Using compass.transaction.processor.read_committed.concurrencyLevel=1 setting would allow asynchronous operations but just use one thread (the default is 5 threads). There are also the compass.transaction.processor.read_committed.backlog and compass.transaction.processor.read_committed.addTimeout settings.
I hope this helps.


text:
Q: grouping, splitting, and counting rows given this table and data:
DECLARE @Table table (RowID int, RowCode char(1), RowValue int);set nocount on
INSERT @Table VALUES ( 6,'A',3757 )
INSERT @Table VALUES ( 5,'A',37827)
INSERT @Table VALUES (14,'A',48411)
INSERT @Table VALUES ( 1,'A',48386)
INSERT @Table VALUES (20,'A',48450)
INSERT @Table VALUES ( 7,'A',46155)
INSERT @Table VALUES (13,'A',721  )
INSERT @Table VALUES ( 2,'A',49335)
INSERT @Table VALUES (15,'A',4700 )
INSERT @Table VALUES (19,'A',64416)
INSERT @Table VALUES ( 8,'A',27246)
INSERT @Table VALUES (12,'B',54929)
INSERT @Table VALUES (16,'B',3872 )
INSERT @Table VALUES ( 3,'C',728  )
INSERT @Table VALUES (11,'C',1050 )
INSERT @Table VALUES ( 9,'C',3191 )
INSERT @Table VALUES (17,'C',866  )
INSERT @Table VALUES ( 4,'C',838  )
INSERT @Table VALUES (10,'D',550  )
INSERT @Table VALUES (18,'D',1434 );set nocount off

I need this:
                       VVVVVVVV
RowID RowCode RowValue RowChunk
----- ------- -------- --------
1     A       48386    1
2     A       49335    1
5     A       37827    1
6     A       3757     1
7     A       46155    1
8     A       27246    2
13    A       721      2
14    A       48411    2
15    A       4700     2
19    A       64416    2
20    A       48450    3
12    B       54929    4
16    B       3872     4
3     C       728      5
4     C       838      5
9     C       3191     5
11    C       1050     5
17    C       866      5
10    D       550      6
18    D       1434     6

RowChunk starts at 1 and is incremented by 1 for each RowCode change and/or when there have been 5 of the same RowCode values.

A: Basically my solution uses the same approach as yours, only with slightly different devices employed.
WITH NumberedRows AS (
  SELECT
    RowID,
    RowCode,
    RowValue,
    CodeChunk = (ROW_NUMBER() OVER (PARTITION BY RowCode ORDER BY RowID) - 1) / 5
  FROM @Table
)
SELECT
  RowID,
  RowCode,
  RowValue,
  RowChunk = DENSE_RANK() OVER (ORDER BY RowCode, CodeChunk)
FROM NumberedRows

A: I don't think there's an analysis function, or any reasonable combination of such, which will address this.  You'll have to do it RBAR with a cursor or, slightly faster in my experience, a loop.
This example of looping assumes that RowID is unique.  If RowID is not the clustered PK, this will be very slow, so if that's the case you'll want to create a temp table.
DECLARE @RowID         INT = (SELECT MIN(RowID) FROM @Table)
DECLARE @MaxRowID      INT = (SELECT MAX(RowID) FROM @Table)
DECLARE @RowCode       CHAR(1)
DECLARE @LastRowCode   CHAR(1)
DECLARE @RowValue      INT
DECLARE @Chunk         INT = 0
DECLARE @RecsThisChunk INT
DECLARE @Results       TABLE (RowID INT NOT NULL PRIMARY KEY, RowCode     CHAR(1) NOT NULL, RowValue INT NOT NULL, Chunk INT NOT NULL)

WHILE @RowID <= @MaxRowID
    BEGIN
    -- Handle gaps in RowID
    IF NOT EXISTS (SELECT * FROM @Table WHERE RowID = @RowID) GOTO EndOfLoop

    -- Load values for this record
    SELECT @RowCode = RowCode, @RowValue = RowValue FROM @Table WHERE RowID = @RowID

    IF @LastRowCode IS NULL OR @RowCode <> @LastRowCode OR @RecsThisChunk = 5
        BEGIN
        -- Start a new chunk
        SET @Chunk = @Chunk + 1
        SET @RecsThisChunk = 1
        END
    ELSE
        BEGIN
        -- Same chunk
        SET @RecsThisChunk = @RecsThisChunk + 1
        END

    SET @LastRowCode = @RowCode

    INSERT INTO @Results (RowID, RowCode, RowValue, Chunk) VALUES (@RowID, @RowCode, @RowValue, @Chunk)

    EndOfLoop:
    SET @RowID = @RowID + 1
    END

SELECT * FROM @Results

You may have tweak this a bit for 2005, I use 2008 routinely and don't recall all the little differences.
FYI, the results you show don't quite match the sample data.
Hope this helps!  The only alternative I see is a cursor, or handling this in the application layer.

A: This is the answer you are looking for :
create Table [table] (RowID int, RowCode char(1), RowValue int)
INSERT [Table] VALUES ( 6,'A',3757 )
INSERT [Table] VALUES ( 5,'A',37827)
INSERT [Table] VALUES (14,'A',48411)
INSERT [Table] VALUES ( 1,'A',48386)
INSERT [Table] VALUES (20,'A',48450)
INSERT [Table] VALUES ( 7,'A',46155)
INSERT [Table] VALUES (13,'A',721  )
INSERT [Table] VALUES ( 2,'A',49335)
INSERT [Table] VALUES (15,'A',4700 )
INSERT [Table] VALUES (19,'A',64416)
INSERT [Table] VALUES ( 8,'A',27246)
INSERT [Table] VALUES (12,'B',54929)
INSERT [Table] VALUES (16,'B',3872 )
INSERT [Table] VALUES ( 3,'C',728  )
INSERT [Table] VALUES (11,'C',1050 )
INSERT [Table] VALUES ( 9,'C',3191 )
INSERT [Table] VALUES (17,'C',866  )
INSERT [Table] VALUES ( 4,'C',838  )
INSERT [Table] VALUES (10,'D',550  )
INSERT [Table] VALUES (18,'D',1434 )

IF object_id('tempdb..#tempTable') IS NOT NULL
BEGIN
  DROP TABLE #tempTable
END

CREATE TABLE #tempTable
(RowID int, RowCode char(1), RowValue int,RowChunk int)

INSERT INTO #tempTable
select RowID,RowCode,RowValue,null from [table]

declare @RowId int
declare @RowCode char(1)
declare @Count int
declare @CurrentCode char(1)
declare @CountCurrent int

set @Count=1
set @CurrentCode=1
set @CountCurrent=0

DECLARE contact_cursor CURSOR FOR
SELECT RowID,RowCode FROM [table]

OPEN contact_cursor
FETCH NEXT FROM contact_cursor into @RowId,@RowCode
set @CurrentCode=@RowCode
WHILE @@FETCH_STATUS = 0
BEGIN
  if(@CurrentCode=@RowCode)

  begin
    if(@CountCurrent=5)
    begin
      set @CountCurrent=1
      set @Count=@Count+1
      update #tempTable set RowChunk=@Count where RowID=@RowID
    end
    else
    begin
      set @CountCurrent=@CountCurrent+1
      update #tempTable set RowChunk=@Count where RowID=@RowID
    end
  end

  else
  begin
    set @CurrentCode=@RowCode
    set @CountCurrent=1
    set @Count=@Count+1
    update #tempTable set RowChunk=@Count where RowID=@RowID
  end

  FETCH NEXT FROM contact_cursor into @RowId,@RowCode
END
CLOSE contact_cursor
DEALLOCATE contact_cursor

select * from #tempTable
GO

A: this does the trick without a loop:
;WITH NumberedRows AS (
SELECT
r.RowID, r.RowCode, r.RowValue, CEILING(ROW_NUMBER() OVER(PARTITION BY r.RowCode ORDER BY r.RowCode,r.RowID)/5.0) AS CodeRowChunk
FROM @Table  r
)
, AllChunks AS (
SELECT r.*,ROW_NUMBER() OVER(ORDER BY RowCode,CodeRowChunk) AS ChunkRowNumber
FROM (SELECT DISTINCT
      RowCode, CodeRowChunk
      FROM NumberedRows) r
)
SELECT
a.RowID, RowCode, a.RowValue,
(SELECT ChunkRowNumber FROM AllChunks c WHERE c.RowCode=a.RowCode and c.CodeRowChunk=a.CodeRowChunk) AS RowChunk
FROM NumberedRows  a

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pass a sharepoint folder path as an argument in python without the need for a for loop to look through the drives Not sure if anyone can help me with this problem that I have but I have written a script that takes a file from a location on a server and puts it on a sharepoint location.
I have managed to get a function to work with passing the arguments for the log in credentials as well as the location of the file to be uploaded.
The issue I am having is that I want to add a further argument that will be fed into the function for the location of the folder that the file I want to upload will go into. Below is some of the logic I used in my for loop that I want to replace with a string that I can feed as an argument.
def uploadfunc(report,account):
    """[uploads csv file tp sharepoint]

    Args:
        report ([str]): the folder path in which the files are located #########
        filename ([str]): the filename for the file to be processed ############
    """
    site_id = "id"
    site_sp = account.sharepoint().get_site(site_id)

    for drive in site_sp.list_document_libraries():
        if 'Drive: Documents' in str(drive):
            for item in drive.get_root_folder().get_items():
                if item.is_folder and str(item) == 'Folder: F1':
                    for subfolder in item.get_items():
                        if subfolder.is_folder and str(subfolder) == 'Folder: F2':
                            for subfolder2 in subfolder.get_items():
                                if subfolder2.is_folder and str(subfolder2) == 'Folder: F3':
                                    subfolder2.upload_file(item=report)

def main(path, client_id, tenant_id, secret_id):
    account = login(client_id, secret_id, tenant_id)
    report = path
    uploadfunc(report, account)

if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])

#What I would idealy like to do is to be able to feed it into something like the below:

def main(file_path, target_path, client_id, tenant_id, secret_id):
    account = login(client_id, secret_id, tenant_id)
    report = file_path
    target_path
    uploadfunc(report, account)

if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])

# The target path argument will be the sharepoint site path


text:
Q: Access violation when opening form 2th time on Android in Delphi XE7 When I open my form for the first time I get no violation, but when I first select a TEdit field and then close the form and then recreate the form and open it I get the Violation.
Code for creating the form:
procedure TfrmNocoreDKS.actConfigExecute(Sender: TObject);
var
  confForm: TConfiguratie;
begin
  confForm := TConfiguratie.Create(nil);
  confForm.ShowModal(
    procedure(ModalResult: TModalResult)
    begin
      confForm.DisposeOf;//Also tried confForm.Free;
    end);
end;

I've also tried this for creating the form:
procedure TfrmNocoreDKS.actConfigExecute(Sender: TObject);
var
  confForm: TConfiguratie;
begin
  confForm := TConfiguratie.Create(nil);
  try
    confForm.ShowModal(
      procedure(ModalResult: TModalResult)
      begin
      end);
  finally
    confForm.free;
  end;
end;

Code for Closing the form:
procedure TConfiguratie.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Action := TCloseAction.caFree;
end;

Because the violation only appears when you click on any TEdit and then close the form I think it has something to do with the virtual keyboard, but i'm not sure. I don't have any methods that use the virtual keyboard itself.

A: Update
While my suggestions here are as documented, there are still problems with Android and multiple forms. See later in this post.

Do not call DisposeOf() or Free at all. The FormClose() and the caFree call is the key to make it work.
The documentation how to dispose of a modal dialog has been changed: Using FireMonkey Modal Dialog Boxes.
The FireMonkey architects has struggled with this for several versions now, and finally it works.
Example from doc how to create a modal dialog:
procedure MyCurrentForm.MyButtonClick(Sender: TObject);
var
  dlg: TMyModalForm;
begin
  // Create an instance of a form.
  dlg := TMyModalForm.Create(nil);

  // Configure the form. For example, give it a display name.
  dlg.Caption := 'My Modal Dialog Box';

  // Show your dialog box and provide an anonymous method that handles the closing of your dialog box.
  dlg.ShowModal(
    procedure(ModalResult: TModalResult)
    begin
      // Do something.
    end
  );
end;

And to free your modal dialog:
procedure TMyModalForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Action := TCloseAction.caFree;
end;

Update
The OP has tried this solution and it does not work as expected.
Looking into QC, there are reports claiming that this does not work as expected on mobile android platforms:
RSP-9692 Runtime creation of forms in Android
and
RSP-9665 Access Violation in FMX.Platform.Android SendCMGestureMessage.
(You must login to access them).
The latter explains what is happening. When the modal form is destroyed, it is possible that FFocusedControl points to a destroyed control. When ARC is trying to release FFocusedControl this will cause a segmentation fault. FFocusedControl must be declared [weak]. See the RSP-9665 for more details.
There is also QC-126524 [Android] Open/Close/Free sub form multiple times may cause crash on Android Platform when removing Focus from TEdit reporting the same thing and closed as resolved in XE7. This apparently not true.

A: Embarcadero documentation regarding FMX ShowModal and mobile platforms says
Caution: Modal dialog boxes are not supported in Android apps. Instead of calling ShowModal, you should call Show, and have the form return and call your event. We recommend that you not use modal dialogs on either of the mobile platforms (iOS and Android) because unexpected behavior can result. Not using modal dialogs eliminates potential problems in debugging and supporting your mobile apps.

A: This issue seemed to be only accuring in Delphi XE7. I am now using Delphi XE8 and don't have this problem anymore.


text:
Q: How to convert nested list into a dataframe I have a nested list looked liek this:
[[{'aaa': '42'}, {'bbb': '60'}, {'ccc': '25'}, {'ddd': '14'}, {'eee': '15'}, {'eee': '84'}],
 [{'aaa': '4'}, {'bbb': '0'}, {'ccc': '25'}, {'ddd': '1'}, {'eee': '1'}, {'eee': '8'}]]

And I want to convert it into a Dataframe.
I looked at many solutions on our portal but nothing works for me :(
Please help me as I'm a fresher in Python and Pandas module. Thank you!
Here is my desired Output:

I'm doing something like this but it's not working for me:
DataFrame(data_dicts)

A: Assuming L your input list, you can use a list/dictionary comprehension:
df = pd.DataFrame([{k:v for d in l for d in l for k,v in d.items()} for l in L])

NB. note that you have duplicated keys in your dictionaries, the last ones take precedence
output:
  aaa bbb ccc ddd eee
0  42  60  25  14  84
1   4   0  25   1   8

input:
L = [[{'aaa': '42'}, {'bbb': '60'}, {'ccc': '25'}, {'ddd': '14'}, {'eee': '15'}, {'eee': '84'}],
     [{'aaa': '4'}, {'bbb': '0'}, {'ccc': '25'}, {'ddd': '1'}, {'eee': '1'}, {'eee': '8'}]]

A: You can use a collections.defaultdict to collect all values of a key together and then use pd.concat to construct a dataframe  -
from collections import defaultdict

lld = [[{'aaa': '42'}, {'bbb': '60'}, {'ccc': '25'}, {'ddd': '14'}, {'eee': '15'}, {'eee': '84'}],
 [{'aaa': '4'}, {'bbb': '0'}, {'ccc': '25'}, {'ddd': '1'}, {'eee': '1'}, {'eee': '8'}]]

d = defaultdict(list)
for sublist in lld:
    for subdict in sublist:
        for k, v in subdict.items():
            d[k].append(v)
df = pd.concat([pd.DataFrame(value, columns=[key]) for key, value in d.items()], axis=1)

Output
   aaa  bbb  ccc  ddd eee
0   42   60   25   14  15
1    4    0   25    1  84
2  NaN  NaN  NaN  NaN   1
3  NaN  NaN  NaN  NaN   8


text:
Q: Is the limit $\lim_{(x,y) \to \infty} \frac{x+2y}{x^2 - 2xy + 2y^2}$ zero? I have this limit:$$\lim_{(x,y) \to \infty} \frac{x+2y}{x^2 - 2xy + 2y^2}$$
At first sight seems that limit equals 0. But WolframAlpha says that there is no limit. I tried to prove it. I considered cases $y = kx$, and so on. I never got to find subsequence, whose has limit $\neq 0$.
I think there is a problem in denominator. When $x\rightarrow \infty$ and $y \rightarrow \infty$ we got there $\infty - \infty + \infty$. It's unclear what to do with it and how to find necessary subsequence.
Maybe i'm on the wrong way to solve it. Please, give me a tip.

A: The expression equals
$$\frac{x+2y}{(x-y)^2 + y^2}.$$
Go to the usual polar coordinates: $x=r\cos t,y=r\sin t.$ The expression then equals
$$\tag 1 \frac{1}{r}\frac{\cos t + 2\sin t}{(\cos t-\sin t)^2 + \sin^2t}.$$
Now the denominator is nonnegative and never $0,$ and therefore is bounded below by a positive constant $c.$ It follows that the absolute value of $(1)$ is bounded above by
$$\frac{1}{r}\cdot \frac{3}{c}.$$
As $(x,y)\to \infty$ (whatever that means, I'm guessing it means $(x^2+y^2)^{1/2} \to \infty$), we must have $r\to \infty,$ so the limit is $0.$

A: For
$$\lim_{\substack{x\rightarrow\infty \\y\rightarrow\infty}} \frac{x+2y}{(x - y)^2 + y^2}$$
Let $x-y=r\cos t$ and $y=r\sin t$ so the limit
$$\lim_{\substack{r\rightarrow\infty \\t\rightarrow\infty}}\dfrac{3\sin t+\cos t}{r}$$
doesn't exist, since you can move along $r=3\sin t+\cos t$.
Update:
As people said, this approach is wrong actually, since $|r|\leq\sqrt{10}$ won't go to $\infty$, but I think with $x=\dfrac1s$ and $y=\dfrac1t$ then
$$\lim_{(x,y) \to \infty} \frac{x+2y}{x^2 - 2xy + 2y^2}=\lim_{(s,t) \to (0,0)} \frac{st^2+2s^2t}{(t-s)^2+s^2}=\lim_{(s,t) \to (0,0)} \frac{s(t-s)^2+4s^2t-s^3}{(t-s)^2+s^2}$$
so the limit will be $0$ since
$$\Big|\frac{s(t-s)^2+4s^2t-s^3}{(t-s)^2+s^2}\Big|\leq\Big|\frac{(t-s)^2}{(t-s)^2+s^2}\Big||s|+\Big|\frac{s^2}{(t-s)^2+s^2}\Big||4t-s|\leq6\delta$$

A: It seems to me like the limit is zero. Write the function as
$$
\frac{(x-y)+y}{(x-y)^2+y^2}+\frac{2y}{(x-y)^2+y^2}
$$
The second fraction goes to zero since
$$
\left|\frac{2y}{(x-y)^2+y^2}\right|=\frac{|2y|}{(x-y)^2+y^2}\le \frac{2|y|}{y^2}=\frac2{|y|}\stackrel{y\to\infty}\to 0
$$
For the first fraction, use the Cauchy-Schwarz inequality:
$$
|(x-y)\cdot1+y\cdot1|\le \sqrt{(x-y)^2+y^2}\cdot \sqrt{1^2+1^2}
$$
Then
$$
\left|\frac{(x-y)+y}{(x-y)^2+y^2}\right|\le \sqrt{2}\cdot \frac{\sqrt{(x-y)^2+y^2}}{(x-y)^2+y^2}=\sqrt{2}\cdot\frac1{\sqrt{(x-y)^2+y^2}}\le \frac{\sqrt 2}{\sqrt{y^2}} \stackrel{y\to\infty}\to 0
$$

A: An easier answer maybe:
$$\frac{x+2y}{x^{2}-2xy+2y^{2}} = \frac{x+2y}{(x^{2}+2y^{2})-2xy} \leq \frac{x+2y}{2\sqrt{2}xy -2xy} = \frac{1}{(2\sqrt{2}-2)y} + \frac{1}{(\sqrt{2}-1)x}$$ by noting that the denominator is positive (equal to $(x-y)^{2}+y^{2}$) and by using $x^{2}+2y^{2} \geq 2\sqrt{2}xy$.
Now this obviously tends toward $0$ as $(x,y) \rightarrow +\infty$.

A: $$
\begin{align}
(x-y)^2+y^2
&=x^2-2xy+2y^2\\
&=(2-\phi)x^2+(\phi-1)x^2-2xy+\phi y^2+(2-\phi)y^2\\
&=(2-\phi)\left(x^2+y^2\right)+\left(\sqrt{\phi-1}\,x+\sqrt{\phi}\,y\right)^2\\
&\ge(2-\phi)\left(x^2+y^2\right)\\
&=\frac1{\phi^2}\left(x^2+y^2\right)
\end{align}
$$
Therefore,
$$
\begin{align}
\left|\frac{x+2y}{(x-y)^2+y^2}\right|
&\le\phi^2\frac{|x+2y|}{x^2+y^2}\\
&\le\frac{3\phi^2}{\sqrt{x^2+y^2}}
\end{align}
$$


text:
Q: How to make the styled dropdown scrollable? I'm using the following styled dropdown menu:
https://codepen.io/wallaceerick/pen/ctsCz
<select id="mounth">
    <option value="hide">-- Month --</option>
    <option value="january" rel="icon-temperature">January</option>
    <option value="february">February</option>
    <option value="march">March</option>
    <option value="april">April</option>
    <option value="may">May</option>
    <option value="june">June</option>
    <option value="july">July</option>
    <option value="august">August</option>
    <option value="september">September</option>
    <option value="october">October</option>
    <option value="november">November</option>
    <option value="december">December</option>
</select>

The problem is that this menu is not scrollable and its height has no limit. Could anybody please tell me how I can modify the css to limit the height of the dropdown to certain number of items and make it scroll like a normal dropdown?

A: You can add a max-height to .select-options and set overflow-y: scroll

/*
Reference: http://jsfiddle.net/BB3JK/47/
*/

$('select').each(function(){
    var $this = $(this), numberOfOptions = $(this).children('option').length;

    $this.addClass('select-hidden');
    $this.wrap('

');
    $this.after('

');

    var $styledSelect = $this.next('div.select-styled');
    $styledSelect.text($this.children('option').eq(0).text());

    var $list = $('
', {
        'class': 'select-options'
    }).insertAfter($styledSelect);

    for (var i = 0; i < numberOfOptions; i++) {
        $('
', {
            text: $this.children('option').eq(i).text(),
            rel: $this.children('option').eq(i).val()
        }).appendTo($list);
    }

    var $listItems = $list.children('li');

    $styledSelect.click(function(e) {
        e.stopPropagation();
        $('div.select-styled.active').not(this).each(function(){
            $(this).removeClass('active').next('ul.select-options').hide();
        });
        $(this).toggleClass('active').next('ul.select-options').toggle();
    });

    $listItems.click(function(e) {
        e.stopPropagation();
        $styledSelect.text($(this).text()).removeClass('active');
        $this.val($(this).attr('rel'));
        $list.hide();
        //console.log($this.val());
    });

    $(document).click(function() {
        $styledSelect.removeClass('active');
        $list.hide();
    });

});
@import url("https://fonts.googleapis.com/css?family=Lato");
body {
  font-family: Lato, Arial;
  color: #fff;
  padding: 20px;
  background-color: #e74c3c;
}

h1 {
  font-weight: normal;
  font-size: 40px;
  font-weight: normal;
  text-transform: uppercase;
}
h1 span {
  font-size: 13px;
  display: block;
  padding-left: 4px;
}

p {
  margin-top: 200px;
}
p a {
  text-transform: uppercase;
  text-decoration: none;
  display: inline-block;
  color: #fff;
  padding: 5px 10px;
  margin: 0 5px;
  background-color: #b83729;
  -moz-transition: all 0.2s ease-in;
  -o-transition: all 0.2s ease-in;
  -webkit-transition: all 0.2s ease-in;
  transition: all 0.2s ease-in;
}
p a:hover {
  background-color: #ab3326;
}

.select-hidden {
  display: none;
  visibility: hidden;
  padding-right: 10px;
}

.select {
  cursor: pointer;
  display: inline-block;
  position: relative;
  font-size: 16px;
  color: #fff;
  width: 220px;
  height: 40px;
}

.select-styled {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: #c0392b;
  padding: 8px 15px;
  -moz-transition: all 0.2s ease-in;
  -o-transition: all 0.2s ease-in;
  -webkit-transition: all 0.2s ease-in;
  transition: all 0.2s ease-in;
}
.select-styled:after {
  content: "";
  width: 0;
  height: 0;
  border: 7px solid transparent;
  border-color: #fff transparent transparent transparent;
  position: absolute;
  top: 16px;
  right: 10px;
}
.select-styled:hover {
  background-color: #b83729;
}
.select-styled:active, .select-styled.active {
  background-color: #ab3326;
}
.select-styled:active:after, .select-styled.active:after {
  top: 9px;
  border-color: transparent transparent #fff transparent;
}

.select-options {
  display: none;
  position: absolute;
  top: 100%;
  right: 0;
  left: 0;
  z-index: 999;
  margin: 0;
  padding: 0;
  list-style: none;
  background-color: #ab3326;
}
.select-options li {
  margin: 0;
  padding: 12px 0;
  text-indent: 15px;
  border-top: 1px solid #962d22;
  -moz-transition: all 0.15s ease-in;
  -o-transition: all 0.15s ease-in;
  -webkit-transition: all 0.15s ease-in;
  transition: all 0.15s ease-in;
}
.select-options li:hover {
  color: #c0392b;
  background: #fff;
}
.select-options li[rel="hide"] {
  display: none;
}

.select-options {
  max-height: 176px;
  overflow-y: scroll;
}

Custom Select Without Plugin

<select id="mounth">
    <option value="hide">-- Month --</option>
    <option value="january" rel="icon-temperature">January</option>
    <option value="february">February</option>
    <option value="march">March</option>
    <option value="april">April</option>
    <option value="may">May</option>
    <option value="june">June</option>
    <option value="july">July</option>
    <option value="august">August</option>
    <option value="september">September</option>
    <option value="october">October</option>
    <option value="november">November</option>
    <option value="december">December</option>
</select>

<select id="year">
    <option value="hide">-- Year --</option>
    <option value="2010">2010</option>
    <option value="2011">2011</option>
    <option value="2012">2012</option>
    <option value="2013">2013</option>
    <option value="2014">2014</option>
    <option value="2015">2015</option>
</select>

See the Custom File Upload demo!

A: You can set the overflow property of the dropdown-content of the dropdown menu in your CSS. Then, if you set the height of the .dropdown-content, the menu will automatically allow scrolling if it is limited in height.


text:
Q: OS X Mavericks Guest Mode with Filevault → Safari flickers + crashes Did anyone tried out the Guest Account feature in Mac OS X Mavericks with Filevault2 = on?
I did and
- Safari flickers (like with wrong graphic driver) → https://discussions.apple.com/message/23784151#23784151
- Safari / the complete system crashs and freezes on several websites.
Summary it's not usable! :(
Does anyone have similar issues?
Who does know a solution or has an idea to get the bug?
Thank you!

A: The Guest account only appears on the FileVault 2 pre-boot login screen if iCloud's Find My Mac is enabled. It's essentially a way to encourage someone to get online from that laptop without having to unlock the encryption. Once online, the laptop phones home to the Find My Mac service immediately with its current IP and location information.
Long story short, the Safari-Only Mode is not really meant for everyday use. It's meant to be a trap for thieves.


text:
Q: C# Fetching data from external source using infinite loop for multiple attempts My application uses MongoDB and I need to connect to the server and fetch some critical data when the application launches. If the connection attempt fails, I need to ask the user if he wants to try again or shutdown the application.
So far I went with the following solution:
public async Task LoadCriticalData()
{
    bool IsBusy = true;
    CancellationTokenSource Source = new CancellationTokenSource();
    CancellationToken Token = Source.Token;

    while (!Token.IsCancellationRequested)
    {
        try
        {
            await FetchCriticalData();

            IsBusy = false;

            Source.Cancel();
        }
        catch (Exception E)
        {
            bool Retry = RequestUserInteraction();

            if (!Retry)
            {
                Source.Cancel();
                CloseApplication();
            }
        }
    }
}

I really don't like infinite loops (never used them for years before) but looks like there is no other way to implement this.
Is this sufficient or this can be done in a better way?

A: It is generally fine to retry an operation in a loop as long as there is some exit criteria. Either when the operation succeeds, or the operator selects to terminate the operation or application. In either case it is not truly an infinite loop.


text:
Q: How to integrate dotcover and Jenkins How to integrate dotcover and Jenkis.
Any PDF or Guide?
I was able to run the dot cover through command line and it generate test results. However when I try to run in Jenkins through windows batch command it throws an error as
Command 'cover' doesn't support 2 unnamed arguments
Type 'dotCover help' for usage.
Anything missing?

A: I use dotCover from Jenkins. I have multiple DLL's that need testing, so my job will execute dotcover for each DLL, merge the test snapshots, and generate a HTML report. My Jenkins setup includes "HTML Publisher plugin" and "NUnit plugin"
First grab the command line tools and put it on the Jenkins server:

Run the command line tool in a windows batch command:

I had little luck trying to pass params into the command line, so I used the settings xml from dotCover (contents of dotCoverTRAEngineTest.xml):
    <?xml version="1.0" encoding="utf-8"?>
    <CoverageParams>
      <TargetExecutable>C:\NUnit-2.6.3\bin\nunit-console.exe</TargetExecutable>
<TargetArguments>C:\Jenkins\workspace\TRA.CodeCoverage\TRAEngine\TRAEngineTest\bin\x64\RduDev\TRAEngineTest.dll /xml:C:\Jenkins\workspace\TRA.CodeCoverage\TestReports\dotCoverTRAEngineTestRESULTS.xml</TargetArguments>
        <TargetWorkingDir></TargetWorkingDir>
      <Output>TRAEngineTestSnapshot.dcvr</Output>
    </CoverageParams>

Paths on the Jenkins server are hard coded because I'm lazy. I know it should be a parameter somehow but it's working for now.
Next I merge all the snapshots:

Contents of merge xml:
<?xml version="1.0" encoding="utf-8"?>
<MergeParams>
  <Source>TRAUnitTests.dcvr</Source>
  <Source>TRAEngineTestSnapshot.dcvr</Source>
  <Output>MergedSnapshots.dcvr</Output>
</MergeParams>

Then run the report:

Contents of report.xml:
<?xml version="1.0" encoding="utf-8"?>
<ReportParams>
  <Source>MergedSnapshots.dcvr</Source>
  <Output>CoverageReport.html</Output>
  <ReportType>HTML</ReportType>
</ReportParams>

All the .xml files above reside in a folder named "TestReports", and that's where I output all the results to. Jenkins will look there to publish the HTML report and nunit results:

When it all works right you should get the dotCover report and the nunit results on the job page.


text:
Q: Read multidimensional NetCDF as data frame in R I use a netCDF file which stores one variable and has following dimensions: lon, lat, time.
Generally speaking I wish to compare it against different data that I have already in R stored as dataframe - first two columns are coordinates in WGS84, and next are values for specific time.
So I wrote following code.
# since # ncFile$dim$time$units  say:  [1] "days since 1900-1-1"
daysFromDate <- function(data1, data2="1900-01-01")
{
  round(as.numeric(difftime(data1,data2,units = "days")))
}

#study area:
lon <- c(40.25, 48)
lat <- c(16, 24.25)
myTime <- c(daysFromDate("2008-01-16"), daysFromDate("2011-12-31"))
varName <- "spei"

require(ncdf4)
require(RCurl)
x <- getBinaryURL("http://digital.csic.es/bitstream/10261/104742/3/SPEI_01.nc")
ncFile <- nc_open(x)

LonIdx <- which( ncFile$dim$lon$vals >= lon[1] | ncFile$dim$lon$vals <= lon[2])
LatIdx <- which( ncFile$dim$lat$vals >= lat[1] & ncFile$dim$lat$vals <= lat[2])
TimeIdx <- which( ncFile$dim$time$vals >= myTime[1] & ncFile$dim$time$vals <= myTime[2])
MyVariable <- ncvar_get( ncFile, varName)[ LonIdx, LatIdx, TimeIdx]

I thought that data frame will be returned so that I will be able to easily manipulate data (in example - check correlation or create a plot).
Unfortunately 3-dimensional list has been returned instead.
How can I reformat this to data frame with following columns X-Y-Time1-Time2-...
So, example data will looks as follows
X Y 2014-01-01 2014-01-02 2014-01-02
50 17 0.5 0.4 0.3
where 0.5, 0.4 and 0.3 are example variable values
Or maybe there is different solution?

A: Ok, try following code, but it assumes that ranges are dense filled. And I changed lon test from or to and
require(ncdf4)

nc <- nc_open("SPEI_01.nc")
print(nc)

lon <- ncvar_get(nc, "lon")
lat <- ncvar_get(nc, "lat")
time <- ncvar_get(nc, "time")

lonIdx <- which( lon >= 40.25 & lon <= 48.00)
latIdx <- which( lat >= 16.00 & lat <= 24.25)

myTime <- c(daysFromDate("2008-01-16"), daysFromDate("2011-12-31"))
timeIdx <- which(time >= myTime[1] & time <= myTime[2])

data <- ncvar_get(nc, "spei")[lonIdx, latIdx, timeIdx]

indices <- expand.grid(lon[lonIdx], lat[latIdx], time[timeIdx])
print(length(indices))
class(indices)
summary(indices)
str(indices)

df <- data.frame(cbind(indices, as.vector(data)))
summary(df)
str(df)

UPDATE
ok, looks like I got the idea what do you want, but have do direct solution. What I've got so far is this: split data frame using either split() function or data.table package. After splitting by X&Y, you'll get lists of small data frames where X&Y are a constant for a given frame. Probably is it possible to transpose and recombine them back, but I have no idea how. It might be a good idea to continue to work with data as columns, Lists are nested, could be flattened, and here is link for splitting in R: http://www.uni-kiel.de/psychologie/rexrepos/posts/dfSplitMerge.html
Code, as continued from previous example
require(data.table)

colnames(df) <- c("X","Y","Time","spei")
df$Time <- as.Date(df$Time, origin="1900-01-01")

dt <- as.data.table(df)
summary(dt)

# Taken from https://github.com/Rdatatable/data.table/issues/1389
# x data.table
# f use `by` argument instead - unlike data.frame
# drop logical default FALSE will include `by` columns in resulting data.tables - unlike data.frame
# by character column names on which split into lists
# flatten logical default FALSE will result in recursive nested list having data.table as leafs
# ... ignored
split.data.table <- function(x, f, drop = FALSE, by, flatten = FALSE, ...){
    if(missing(by) && !missing(f)) by = f
    stopifnot(!missing(by), is.character(by), is.logical(drop), is.logical(flatten), !".ll" %in% names(x), by %in% names(x), !"nm" %in% by)
    if(!flatten){
        .by = by[1L]
        tmp = x[, list(.ll=list(.SD)), by = .by, .SDcols = if(drop) setdiff(names(x), .by) else names(x)]
        setattr(ll <- tmp$.ll, "names", tmp[[.by]])
        if(length(by) > 1L) return(lapply(ll, split.data.table, drop = drop, by = by[-1L])) else return(ll)
    } else {
        tmp = x[, list(.ll=list(.SD)), by=by, .SDcols = if(drop) setdiff(names(x), by) else names(x)]
        setattr(ll <- tmp$.ll, 'names', tmp[, .(nm = paste(.SD, collapse = ".")), by = by, .SDcols = by]$nm)
        return(ll)
    }
}

# here is data.table split
q <- split.data.table(dt, by = c("X","Y"), drop=FALSE)
str(q)

# here is data frame split
qq <- split(df, list(df$X, df$Y))
str(qq)


text:
Q: Getting permissions on Ubuntu to create Eclipse project I am trying to set up a new project in Eclipse, but it gives me an error saying that the directory where I am trying to set up the project is read-only.
Here is the error:
Parent of resource: /path/to/project/.project is marked as read-only. (Permission denied)
I do know the password for the machine to get root permissions.  How can I use it to give Eclipse complete editing permissions so that this error does not happen?
Thanks,
Alex

A: Assuming you're logging in as a non-root user myuser, simply run:
sudo chown -R myuser:myuser /path/to/project

which will make you the owner of that directory (and subdirectories).


text:
Q: MySQL query not visualizing on Django HTML page I'm currently trying to take specific queries of databases and display them on an HTML page. I'm working on the Django framework with mySQL as the DB. I've run the queries successfully in mySQL and the server isn't giving me any errors so I'm lost as where to go next.
My views.py file where I have the queries
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from student.models import StudentDetails, CourseDetails
from django.db import connection
from django.core.paginator import Paginator

def dictfetchall(cursor):
    "Return all rows from a cursor as a dict"
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]
# Create your views here.
@login_required
def home(request):

    cursor = connection.cursor()
    cursor.execute("SELECT COUNT(*) 'totalstudents' FROM student_studentdetails")
    cursor.execute("SELECT COUNT(*) 'totalseniors' FROM student_studentdetails WHERE year='Senior' ")
    cursor.execute("SELECT COUNT(*) 'totaljuniors' FROM student_studentdetails WHERE year='Junior' ")
    cursor.execute("SELECT COUNT(*) 'totalfreshman' FROM student_studentdetails WHERE year='Freshman' ")
    cursor.execute("SELECT COUNT(*) 'coursecount' FROM student_coursedetails")
    cursor.execute("SELECT AVG(GPA) 'averagegpa' FROM student_studentdetails")
    homedata =  dictfetchall(cursor)

    return render(request, 'student/home.html', {'data' : homedata})

My home.html where they should be loading. The aesthetics of how they are displayed is secondary right now, I'm still trying to figure out how to pull the data without having to use rows but that's for another day.
{% extends 'student/base.html' %}

{% block content %}

<tbody>
  {% for row in data %}
    <tr>
        <td> {{ row.averagegpa }} </td>
        <td> {{ row.totalstudents}} </td>
        <td> {{ row.totalseniors}} </td>
        <td> {{ row.totaljuniors}} </td>
        <td> {{ row.totalfreshman}} </td>
        <td> {{ row.coursecount}} </td>
    </tr>
  {% endfor %}
</tbody>

{% endblock %}

and this is what I see when I run my server and go to the homepage

A: The problem is that you are executing queries one after the other, without actually recovering the results in between - excepted for last query, that gives you the average GPA for all students.
Even if you were, this still seems like a suboptimal approach. Apart from the course count, which comes from another table, you can get all the information in just one query, using conditional aggregation on table student_studentdetails:
select
    count(*) totalstudents,
    sum(year = 'Senior') totalseniors,
    sum(year = 'Junior') totaljuniors,
    sum(year = 'Freshman') totalfreshman,
    avg(gpa) average gpa
from student_studentdetails

That way, you just need two queries to get the data (you need fo fetch in between!).
You can even merge the other query as follows:
select
    count(*) totalstudents,
    sum(year = 'Senior') totalseniors,
    sum(year = 'Junior') totaljuniors,
    sum(year = 'Freshman') totalfreshman,
    avg(gpa) average gpa,
    (select count(*) from student_coursedetails) course_count
from student_studentdetails


text:
Q: Module has no default export vue/ts/webpack I'm experiencing an issue while trying to compile my code written in vue js 3 composition with typescript and webpack.

[tsl] ERROR in .../index.ts(5,8)
TS1192: Module 'Application.vue"' has no default export.

Here is my bootstrap file.
import {createApp} from 'vue';
import {createStore, Store} from 'vuex';
import {App} from '@vue/runtime-core';

import Application from './Application'; <= this line fails
import 'bootstrap';
import 'bootstrap/scss/bootstrap.scss';
import {Identity} from "../../interface/identity";

const store : Store<object> = createStore({
    state: {
        formData : new FormData,
        identity : <Identity>{}
    },
    mutations : {
        setFormData (state, formData: FormData) {
            state.formData = formData;
        },
        setIdentity (state, identity: Identity) {
            state.identity = identity
        }
    },
    getters : {
        getFormData : (state) : FormData => {
            return state.formData;
        },
        getIdentity : (state) : Identity => {
            return state.identity;
        }
    },
    actions : {
        setFormData(context, formData) {
            context.commit('setFormData', formData);
        },
        setIdentity(context, identity) {
            context.commit('setIdentity', identity)
        }
    }
});
const app : App = createApp(Application);

app
    .use(store)
    .mount('#app');

Which is importing Application from Application.vue file located in the same directory.
<template>
  <Navigation />
  <SearchForm :form-data="formData"/>
  <MergeRequest />
</template>

<script lang="ts">
import {defineComponent} from 'vue'

import Navigation from './Navigation.vue';
import MergeRequest from "./MergeRequest.vue";
import SearchForm from "./SearchForm.vue";

export default defineComponent({
  name: 'Application',
  components: {
    Navigation,
    MergeRequest,
    SearchForm
  },
  setup() {

    const formData : FormData = new FormData

    // code

    return {
      formData
    }
  }
})
</script>

<style scoped lang="scss">
</style>

tsconfig.json
{
  "extends": "@tsconfig/recommended/tsconfig.json",
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "jsx": "preserve",
    "moduleResolution": "Node"
  }
}

webpack.config.js
const path = require('path');
const { VueLoaderPlugin } = require('vue-loader')
const CopyPlugin = require('copy-webpack-plugin');

module.exports = {
    entry: {
        'application/index/index' : './assets/ts/application/index/index.ts',
        'application/authentication/sign-in': './assets/ts/application/authentication/sign-in.ts',
        'application/authentication/sign-out': './assets/ts/application/authentication/sign-out.ts'
    },
    output: {
        path: path.resolve(__dirname, 'public'),
        filename: 'js/dist/[name].js'
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader'
            },
            {
                test: /\.ts?$/, // typescript files
                loader: 'ts-loader',
                exclude: /node_modules/,
                options: {
                    appendTsSuffixTo: [/\.vue$/],
                },
            },
            {
                test: /\.scss?$/,
                use: [
                    'vue-style-loader',
                    'css-loader',
                    'sass-loader'
                ]
            },
            {
                test: /\.(svg|woff|woff2|eot|ttf|otf)$/i,
                type: 'asset/resource',
            },
        ]
    },
    resolve: {
        extensions: [
            '.ts', '.tsx', '.vue', '.js'
        ],
        modules: [
            'assets', 'node_modules'
        ]
    },
    plugins: [
        new VueLoaderPlugin(),
        new CopyPlugin({
            patterns: [
                { from: "assets/img", to: "img" },
                { from: "assets/favicons", to: "favicons" }
            ],
        }),
    ],
    watch: process.env.NODE_ENV === 'development'
}

package.json
{
  "scripts": {
    "dev": "NODE_ENV=development webpack",
    "prod": "NODE_ENV=production webpack"
  },
  "dependencies": {
    "@fortawesome/fontawesome-free": "^5",
    "@vue/compiler-sfc": "^3",
    "bootstrap": "^5",
    "bootstrap.native": "^4",
    "copy-webpack-plugin": "^8.1.1",
    "ts-loader": "^8",
    "typescript": "^4.3.5",
    "vue": "^3",
    "vue-loader": "^16",
    "vue-template-compiler": "^2",
    "vuex": "^4",
    "webpack": "^5",
    "webpack-cli": "^4"
  },
  "devDependencies": {
    "@tsconfig/recommended": "^1",
    "css-loader": "^5",
    "sass": "^1",
    "sass-loader": "^11",
    "vue-style-loader": "^4"
  }
}

I'm running webpack command through npm.
Any idea ? Could it be dependencies compatibility issues ?
Thanks!

A: I think you'll need to import it with the extension:
import Application from './Application.vue'
And make sure you have the shims-vue.d.ts in your project.


text:
Q: Why does nodejs memory keeps on growing in this test? I am trying to get a better understanding of memory consumption in node.js. I've created a small test script that does:

*

*every second: log current memory consumption

*after 5 seconds: every 10 seconds: create a big JS object

*after 10 seconds: every 10 seconds: delete that big JS object

Here is the script.
So it only ever has a single big object to keep track of, and between deleting it there is 5 seconds before it creates a new one.
How come the memory keeps on growing?

A: Perhaps you are not measuring the best metric.
According to the API doc page, process.memoryUsage() returns 3 properties:

*

*rss

*heapTotal

*heapUsed
http://www.nodejs.org/api/process.html#process_process_memoryusage
rss is the operating system level measure of memory being used.  node.js will lazily expand its heap the max. heap size as needed (very similar to Java).  It grows, but never shrinks.  This is ok for 2 reasons:

*

*node manages its memory internally

*the garbage collector eventually frees memory used by unreferenced objects.

*there is an upper cap on the size of the heap.  I know it was 1.4 GB at some point, but that may not be accurate any more.  Sorry I am not up-to-date on these details of node.

Freeing does not free at the OS allocator level, but just marks that memory in node's (V8 actually) memory manager as available for other objects.
If you measure the heapUsed property instead of rss, you should see it go up as objects are allocated and down as the GC runs.
If your goal is to avoid your code from running out of heap space, then that metric is exactly what you need.
If your goal is avoid the node process running out of memory by the OS denying it memory, then  technically rss is the correct metric, but I don't think it will help you.  This isn't a leak.  You simply don't have 1.4 GB (or whatever the current limit is) of memory available to give to the process.  Either the box itself is underpowered or you have a configured resource constraint (like ulimit on Linux systems).
TL;DR
If you are worried about new object creations failing in JavaScript code due to memory not being reclaimed, then heapUsed is the right metric to capture.  If you are worried about the OS refusing to give the node process more memory, then you either do not have enough memory or there is a software setting preventing more memory.

A: This delete candles; doesn't work. delete deletes properties and candles is not one. Switch it with candles = []

A: From the delete docs on MDN:

delete is only effective on an object's properties. It has no effect on variable or function names.

Your delete candles call doesn't do anything. For instance, if you add console.log(candles.length);, you can see that it continues to grow constantly.
You should replace your delete candles with candles = []; to clear all of the candles. Note, it would be a good idea to consider writing your code in strict mode by prepending "use strict"; to the top of your file. This would have caused your delete candles; line to throw a syntax error, making it quite clear that there was a problem.


text:
Q: How to define a class with published method in a separate unit that is available at design-time to other units? To overcome a bug in 10.3.3 (see QC report https://quality.embarcadero.com/browse/RSP-29565) relating to TFDTable detailed elsewhere (Delphi TFDTable open fails when indexname is set), I want to be able to define a class with a method in a common unit that can be assigned (programmatically) as a BeforeOpen event in the relevant DFM for TFDTable components defined on a Form or DataModule.
I realize that this question has been asked before (e.g. How to make a separate unit for event methods, which IDE allows me to assign to component events at design time?), but the solutions batted about there match what I have done, and they do not work.
So, in a unit that must already be listed in the uses clause of the units using TFDTable, I define my class thus:
Common_unit:
type
  TmyMethodHolder = class(TComponent)
  published
    procedure FDTableBeforeOpen(DataSet: TDataSet);
  end;

...

var
  myMethodHolder : TmyMethodHolder=nil;

...

procedure TmyMethodHolder.FDTableBeforeOpen(DataSet: TDataSet);
begin
  // this procedure below is also defined within this "common_unit"
  FDTableSetCatalogName(Dataset);
end;

...

initialization
  myMethodHolder := TmyMethodHolder.Create(nil);
finalization
  myMethodHolder.Free;

In the Registration unit, the component (and the class - though this seems to make no difference) are registered as follows:
RegisterComponents('MyComponents', [TmyMethodHolder]);
RegisterClass(TmyMethodHolder);

Finally, in a test unit, I define a Form with a TFDTable. That unit uses the "common_unit" above:
unit FDTable_Bug_Demo2;

interface

uses
  ... Common_Unit, ....

type

  TForm2 = class(TForm)
    DBGrid1: TDBGrid;
    Button1: TButton;
    FDConnection1: TFDConnection;
    DataSource1: TDataSource;
    edServer: TLabeledEdit;
    edDatabase: TLabeledEdit;
    edUserName: TLabeledEdit;
    edPassword: TLabeledEdit;
    Button2: TButton;
    Button3: TButton;
    FDTable1: TFDTable;
    ...

With the above in place, I can assign the BeforeOpen event of FDTable1 at runtime like so, and everything works as expected:
FDTable1.BeforeOpen := myMethodHolder.FDTableBeforeOpen;

However, I cannot assign the BeforeOpen event of FDTable1 at design-time (to e.g. myMethodHolder.FDTableBeforeOpen). The IDE complains that it is not a valid identifier.
Even if I drop a TMyMethodHolder component onto the Form as myMethodHolder1 (which rather defeats my purpose), I cannot assign the BeforeOpen event to myMethodHolder1.FDTableBeforeOpen. Again, not a valid identifier.
I assume what I am trying to do is possible, and I have just missed something basic. Help please.

A: As per Remy Lebeau's comment, this looks like the best avenue of attack:
Why not just create an interposer class named TFDTable that derives from FireDAC.Comp.Client.TFDTable? It can override the virtual DoBeforeOpen() method, and you don't have to install it into the IDE if it is in another unit, just make sure that unit is in the Form/DataModule's uses clause after the FireDAC.Comp.Client unit, so that your TFDTable is the last one in scope so the DFM will stream it instead


text:
Q: Using "gridGraphics" package to plot multiple heatmaps I came across this answer from @baptiste that uses gridGraphics package in R to plot multiple heatmaps.  https://stackoverflow.com/a/31768236/11696009
But while I was able to recreate the example (obviously), I need to apply it to my own unique condition. I have an excel workbook with 6 sheets in it. I want to plot each sheet as a separate heatmap so that all 6 heatmaps are plotted in a 3x2 grid (3 heatmaps arranged one below the other).
I am very new to R but I gather if I am to able to pass all these sheets to arr[[]] here, I might be able to use this code. Please help me on how to do that.
This is the code that I am trying to adapt.
library(gridGraphics)
library(grid)

grab_grob <- function(){
  grid.echo()
  grid.grab()
}

arr <- replicate(4, matrix(sample(1:100),nrow=10,ncol=10), simplify = FALSE)

library(gplots)
gl <- lapply(1:4, function(i){
  heatmap.2(arr[[i]], dendrogram ='row',
            Colv=FALSE, col=greenred(800),
            key=FALSE, keysize=1.0, symkey=FALSE, density.info='none',
            trace='none', colsep=1:10,
            sepcolor='white', sepwidth=0.05,
            scale="none",cexRow=0.2,cexCol=2,
            labCol = colnames(arr[[i]]),
            hclustfun=function(c){hclust(c, method='mcquitty')},
            lmat=rbind( c(0, 3), c(2,1), c(0,4) ), lhei=c(0.25, 4, 0.25 ),
  )
  grab_grob()
})

grid.newpage()
library(gridExtra)
grid.arrange(grobs=gl, ncol=2, clip=TRUE)

Thanks.
edit:
So, I added some lines and I got 6 plots (3 in each row) but it only plots two graphs - the first in the list and the last one. i.e the heatmap for 1st sheet goes in the first row (repeated thrice) and that of the 6th sheet goes in the second row (repeated thrice).
for (i in 6) {
    arr = as.data.frame(SheetList[i])

    g1 <- lapply(1:6, function(j){
      heatmap.2(as.matrix(arr[2:7]), dendrogram ='none',
                Colv=FALSE, Rowv = FALSE,
                key=FALSE, keysize=1.0, symkey=FALSE, density.info='none',
                trace='none',
                scale="none",cexRow=0.2,cexCol=0.9,
                breaks = col_breaks,col=my_palette,
                labRow = arr[,1],
                hclustfun=function(c){hclust(c, method='mcquitty')},
                lmat=rbind(c(0, 3), c(2,1), c(0,4)), lhei=c(0.25, 4, 0.25),
      )
      grab_grob()
    })
}

grid.newpage()
grid.arrange(grobs = g1, ncol=3, clip=TRUE)

This is the plot I get

A: For those who might need it.
# load and install necessary packages
install.packages("pacman")
library(pacman)
pacman::p_load(gridGraphics,grid,gridExtra,gplots,lubridate, install = TRUE)

file = "something.xlsx"

## load all sheets
sheets <- openxlsx::getSheetNames(file)
SheetList <- lapply(sheets,openxlsx::read.xlsx,xlsxFile=file)
names(SheetList) <- sheets

## create color ramp and colour breaks
col_breaks <- c(-2,-1.5,-1,0,1,1.5,2) #provide col breaks
my_palette<-colorRampPalette(c("red4","red1","darkorange2","gold2",
                               "yellow4","yellow",
                               "chartreuse3","green4")) #color ramp

#Define a new function to create Row labels
#I have six heatmaps; three with same date row
#First three heatmap start from 1982-2017 and last three from 2021-2100
rname <- function(i){
  if (i <= 3)
    rname = seq(as.Date("1982-01-01"), as.Date("2017-12-01"), by = "months")
  else
    rname = seq(as.Date("2021-01-01"), as.Date("2100-12-01"), by = "months")
}

grab_grob <- function(){
  grid.echo()
  grid.grab()
}

g1 = lapply(1:6, function(i) {
  arr = as.data.frame(SheetList[i])
  heatmap.2(as.matrix(arr[2:7]),
            dendrogram ='none',
            Colv=FALSE, Rowv = FALSE,
            key=FALSE, keysize=1.0, symkey=FALSE, density.info='none',
            trace='none',
            scale="none",cexRow=0.7,cexCol=0.9,
            breaks = col_breaks,col=my_palette,
            labRow = format(ymd(rname(i)),"%b-%Y"),
            labCol = c("spei-3", "spei-6", "spei-9", "spei-12", "spei-15", "spei-24"),
            colsep = 0:3, sepwidth = c(0.01),
            sepcolor = c("grey")
  )

  grab_grob()
}
)

grid.newpage()
title1=textGrob("MAIN TITLE", gp=gpar(fontface="bold"), vjust = 0.7)
grid.arrange(grobs = g1, ncol = 3, clip = TRUE, top = title1)


text:
Q: TypeError: Cannot read properties of undefined (reading 'getRange') function lockCells(spreadsheet, cell, rangeToLock) {
  // Get the value of the specified cell
  var cellValue = spreadsheet.getRange(cell).getValue();
  // If the cell value is true, lock the specified range of cells
  if (cellValue === true) {
    spreadsheet.getRange(rangeToLock).setLocked(true);
  // Call the lockCells function to lock cells A1:A5 if cell B1 is set to TRUE
lockCells(SpreadsheetApp.getActiveSheet(),"B1","A1:A5");
  }
}

TypeError: Cannot read properties of undefined (reading 'getRange')
lockCells   @ LockCells.gs:3

How to correct the error.

A: when calling lockCells you are not sending the value for spreadsheet which makes it undefined. Hence you are facing the following error
Make the following changes in the code:
var cellValue;
if(spreadsheet != undefined)
     cellValue = spreadsheet.getRange(cell).getValue();

if(spreadsheet != undefined)
    spreadsheet.getRange(rangeToLock).setLocked(true);

A: The primary issue with the code you quote is that it attempts to use a method called Range.setLocked() which does not exist.
To lock cells, use the Protection class.


text:
Q: bootstrap css fit the background image with the screen body {
   -webkit-font-smoothing: none;
     background: url('../img/logo.png') top left;
}

Bootstrap-CSS : I would like to create an authentication page and I want to use the image logo.png for the background but I couldn't adapt the image to the screen. For example if I reduce the screen of my window, the picture still have the same size. Thank you very much for your help !

A: Like it was already suggested on the comments, you can use the background-size property for the.
I have created a small example for you...

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

body {
  width: 100%;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-image: url('https://images.pexels.com/photos/1054218/pexels-photo-1054218.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1');
  background-size: cover;
}

h1 {
  font-family: sans-serif;
  color: white;
}
<body>
  <h1> Just a title</h1>
</body>

You can read about the background-size property here.
The background-size property sets the size of the element's background image. The image can be left to its natural size, stretched, or constrained to fit the available space.
In my example i have used background-size: cover which scales the image (while preserving its ratio) to the smallest possible size to fill the container

A: SEE "CSS Background Size" on https://www.w3schools.com/css/css3_backgrounds.asp
background-size(property) will help u


text:
Q: How can I prevent a given user group accessing global files? Apologies if this is the incorrect forum.
I am looking for a solution to a problem as follows:
We have protected information on our system with global read/execute access (555) owned by a user in group A, allowing users in groups A,B,C etc. access. This system has worked effectively for many years.
I would now however like to add a new group to the network, group X where group X will not be able to read/execute according to the file permissions. Please can you suggest a solution?
My initial thoughts were to modify each user's cd command but \cd will overcome that hurdle, additionally this will not affect the GUI environment.
Edit: I have been reading about ACLs and I have touched on them in the past. As all of the data is on a separate partition I could activate ACL for the partition e.g.
LABEL=/home             /home                   ext3    rw,acl          1 2

and then modify ACL permissions at the highest level. Will this then bypass the original global permission? Is this a viable option?
Thanks.

A: Having a blacklist on a file that is world-readable is not a safe approach.  Consider what happens if a user is created lacking that group by accident?  Instead, it's best to assign permissions additively.  You could do this by adding a new group that is inclusive of all the users that need access, or by using facls to assign permissions to each group.
Adding the 'users1' group to have read/write/execute permissions on a directory:
setfacl -m g:users1:rwx <directory name>

To automatically assign these same permissions to newly created files/directories inside that directory, add the -d option:
setfacl -d -m g:users1:rwx <directory name>

Use getfacl to check your work.
I would suggest reading through SETFACL(1) and GETFACL(1) by using man setfacl and man getfacl.
In addition, you will need to remount your root partition in a way that supports ACLs:
mount -o remount,acl /

And modify /etc/fstab to include the acl option on reboot, for example:
/dev/xvda       /              ext3     noatime,errors=remount-ro,acl 0       1

A: When you set a file's permissions to 555, you give permissions to three things:

*

*The first 5 is the permissions given to the user owner of the file.

*The second 5 is the permissions given to the group owner of the file.

*The third 5 is the permissions given to everybody else.

5 indeed stands for read and execute permission, so if you want to give read and execute permissions to the user and the group that owns the file, but no permission to others, you can set the file permissions to 550
Note: you mentioned modifying the cd command, I guess you want to forbid people from going into a folder with cd. To do this you simply remove execute permission on the folder.
This is a really simple approach, I don't know how precisely you want to grant permissions, if you need more than simply modify the permissions given to the owner user / owner group / everybody else, you might indeed want to use ACL.


text:
Q: What Kind of Service Do I Need to Use for Sending User-to-User Push Notifications on iOS I need a little help with understanding what to look for when selecting a service to use for allowing my application's users to create accounts and send push notifications to each other. I do not have any backend service experience, except for with Parse, and I don't understand some of the functionality requirements.
I want users to be able to register an account and add other users. Then, I would like the users to be able to select specific users from their "friends" list in order to send a push notification to each selected user for a meeting. However, I honestly don't even know where to start.
It seems that many of the services that I have looked at are set up for sending targeted push notifications to groups of users from a dashboard (seemingly for marketing and other purposes).
I am completely new to servers and backends, except for a little activity with Parse, so can anyone recommend a direction for me to take for integrating such functionality in an iOS application that I am working on?

A: You can use mbaas providers like built.io backend, It provides push notification functionality on object creation event, and a set of ACL can be specified on these objects. This will act as a filter criteria as to who are the allowed to receive this push notification.
You can refer to their docs here https://docs.built.io


text:
Q: In this onClick Slider last slide goes to first slide without clicking and animation

 $(document).ready(function(){
 //configerations
 var width = 720;
 var animationSpeed = 700;
 var currentSlide = 1;
 //DOM items
 var $slider = $('#slider');     //main sliding div
 var $slideContainer = $slider.find('.slides'); //ULs
 var $slides = $slideContainer.find('.slide'); // LIs

  $slider.click(function() {
   $slideContainer.animate({'margin-left': '-=720px'},animationSpeed, function() {
   currentSlide++;
   if (currentSlide == $slides.length) {
   currentSlide = 1;
   $slideContainer.css('margin-left', 0); }
   });
  });
 });
 #slider {width:720px; height:400px; overflow:hidden; float:left; border: 1px solid black;}
 #slider .slides {display: block; width:6000px; height:400px; margin:0; padding:0;}
 #slider .slide {float:left; list-style-type:none; width:720px; height:400px;}

111

222

333

444

555

666

In this onClick Slider, it works fine upto the last slide and then without clicking it goes to first slide.
Please see the following Link:
Please see this Link to check the slider

A: As I mentioned in comments, the original problem i.e. $slideContainer moving to the first slide as soon as the last slide becomes active (which is the li element containing 666) can be resolved by simply changing the original if condition from currentSlide == $slides.length to currentSlide > $slides.length.
But, as you had noticed, it still does a sudden jump to the first slide. To solve this, you may have to re-think how the $slideContainer should be animated.
Originally, we were checking for a specific condition after the sliding animation has completed. But my proposal would be to check for a condition even before an animation has started.
What I am trying to say is that if you change your JS to look like the below, it should produce your desired result.
JavaScript:
$(document).ready(function() {
  var width = 720;
  var animationSpeed = 700;
  var currentSlide = 1;
  var prevSlide;
  var $slider = $('#slider');
  var $slideContainer = $slider.find('.slides');
  var $slides = $slideContainer.find('.slide');

  $slider.click(function() {
    prevSlide = currentSlide;
    if (prevSlide === $slides.length) {
        currentSlide = 1;
        $slideContainer.stop(true, true).animate({'margin-left': 0}, animationSpeed);
    } else {
        currentSlide += 1;
        $slideContainer.stop(true, true).animate({'margin-left': '-=720px'}, animationSpeed);
    }
  });
});

Alternatively, take a look at the jsFiddle.
Let me know if anything is unclear in the code above. Hope this produces the result you are looking for.

A: Following method is doing exactly what I was looking for in the above question:
$(document).ready(function(){

    $("#slider ul").each(function(){
        // Set the interval to be 10 seconds
    //  var t = setInterval(function(){
        $("#rightArrow").click(function(){
            $("#slider ul").animate({marginLeft:-360},1000,function(){
                // This code runs after the animation completes
                $(this).find("li:last").after($(this).find("li:first"));
                // Now we've taken out the left-most list item, reset the margin
                $(this).css({marginLeft:0});
            })
        });
    });
});


text:
Q: 2D graph in jPanel in Netbeans I have a question concerning some primitive graphics.
I am new to java graphics and gui building in general, so I get a lot of questions.
I am using Netbeans 6.9.1. Basically, there is a Main frame and a panel inside it. I want to draw a graph inside the panel. Well, the question is to do that? Below is code for three of the class (mostly auto-generated):
   package graphics;

import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
 * The application's main frame.
 */
public class GraphicsView extends FrameView {

public GraphicsView(SingleFrameApplication app) {
    super(app);

    initComponents();

    jPanel1.add(new Graph());

    // status bar initialization - message timeout, idle icon and busy animation, etc
    ResourceMap resourceMap = getResourceMap();
    int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
    messageTimer = new Timer(messageTimeout, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            statusMessageLabel.setText("");
        }
    });
    messageTimer.setRepeats(false);
    int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
    for (int i = 0; i < busyIcons.length; i++) {
        busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
    }
    busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
            statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
        }
    });
    idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
    statusAnimationLabel.setIcon(idleIcon);
    progressBar.setVisible(false);

    // connecting action tasks to status bar via TaskMonitor
    TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
    taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
        public void propertyChange(java.beans.PropertyChangeEvent evt) {
            String propertyName = evt.getPropertyName();
            if ("started".equals(propertyName)) {
                if (!busyIconTimer.isRunning()) {
                    statusAnimationLabel.setIcon(busyIcons[0]);
                    busyIconIndex = 0;
                    busyIconTimer.start();
                }
                progressBar.setVisible(true);
                progressBar.setIndeterminate(true);
            } else if ("done".equals(propertyName)) {
                busyIconTimer.stop();
                statusAnimationLabel.setIcon(idleIcon);
                progressBar.setVisible(false);
                progressBar.setValue(0);
            } else if ("message".equals(propertyName)) {
                String text = (String)(evt.getNewValue());
                statusMessageLabel.setText((text == null) ? "" : text);
                messageTimer.restart();
            } else if ("progress".equals(propertyName)) {
                int value = (Integer)(evt.getNewValue());
                progressBar.setVisible(true);
                progressBar.setIndeterminate(false);
                progressBar.setValue(value);
            }
        }
    });
}

@Action
public void showAboutBox() {
    if (aboutBox == null) {
        JFrame mainFrame = GraphicsApp.getApplication().getMainFrame();
        aboutBox = new GraphicsAboutBox(mainFrame);
        aboutBox.setLocationRelativeTo(mainFrame);
    }
    GraphicsApp.getApplication().show(aboutBox);
}

/** This method is called from within the constructor to
 * initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is
 * always regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    mainPanel = new javax.swing.JPanel();
    jPanel1 = new javax.swing.JPanel();
    menuBar = new javax.swing.JMenuBar();
    javax.swing.JMenu fileMenu = new javax.swing.JMenu();
    javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
    javax.swing.JMenu helpMenu = new javax.swing.JMenu();
    javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
    statusPanel = new javax.swing.JPanel();
    javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
    statusMessageLabel = new javax.swing.JLabel();
    statusAnimationLabel = new javax.swing.JLabel();
    progressBar = new javax.swing.JProgressBar();

    mainPanel.setName("mainPanel"); // NOI18N

    jPanel1.setName("jPanel1"); // NOI18N

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 380, Short.MAX_VALUE)
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 229, Short.MAX_VALUE)
    );

    javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
    mainPanel.setLayout(mainPanelLayout);
    mainPanelLayout.setHorizontalGroup(
        mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(mainPanelLayout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addContainerGap())
    );
    mainPanelLayout.setVerticalGroup(
        mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(mainPanelLayout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addContainerGap())
    );

    menuBar.setName("menuBar"); // NOI18N

    org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(graphics.GraphicsApp.class).getContext().getResourceMap(GraphicsView.class);
    fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
    fileMenu.setName("fileMenu"); // NOI18N

    javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(graphics.GraphicsApp.class).getContext().getActionMap(GraphicsView.class, this);
    exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
    exitMenuItem.setName("exitMenuItem"); // NOI18N
    fileMenu.add(exitMenuItem);

    menuBar.add(fileMenu);

    helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
    helpMenu.setName("helpMenu"); // NOI18N

    aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
    aboutMenuItem.setName("aboutMenuItem"); // NOI18N
    helpMenu.add(aboutMenuItem);

    menuBar.add(helpMenu);

    statusPanel.setName("statusPanel"); // NOI18N

    statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

    statusMessageLabel.setName("statusMessageLabel"); // NOI18N

    statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
    statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

    progressBar.setName("progressBar"); // NOI18N

    javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
    statusPanel.setLayout(statusPanelLayout);
    statusPanelLayout.setHorizontalGroup(
        statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        .addGroup(statusPanelLayout.createSequentialGroup()
            .addContainerGap()
            .addComponent(statusMessageLabel)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 230, Short.MAX_VALUE)
            .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(statusAnimationLabel)
            .addContainerGap())
    );
    statusPanelLayout.setVerticalGroup(
        statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(statusPanelLayout.createSequentialGroup()
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(statusMessageLabel)
                .addComponent(statusAnimationLabel)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(3, 3, 3))
    );

    setComponent(mainPanel);
    setMenuBar(menuBar);
    setStatusBar(statusPanel);
}// </editor-fold>

// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel mainPanel;
private javax.swing.JMenuBar menuBar;
private javax.swing.JProgressBar progressBar;
private javax.swing.JLabel statusAnimationLabel;
private javax.swing.JLabel statusMessageLabel;
private javax.swing.JPanel statusPanel;
// End of variables declaration

private final Timer messageTimer;
private final Timer busyIconTimer;
private final Icon idleIcon;
private final Icon[] busyIcons = new Icon[15];
private int busyIconIndex = 0;

private JDialog aboutBox;
}

So, here I have added only
jPanel1.add(new Graph());

The next is main class:
package graphics;

import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;

/**
* The main class of the application.
*/
public class GraphicsApp extends SingleFrameApplication {

/**
 * At startup create and show the main frame of the application.
 */
@Override protected void startup() {
    show(new GraphicsView(this));
}

/**
 * This method is to initialize the specified window by injecting resources.
 * Windows shown in our application come fully initialized from the GUI
 * builder, so this additional configuration is not needed.
 */
@Override protected void configureWindow(java.awt.Window root) {
}

/**
 * A convenient static getter for the application instance.
 * @return the instance of GraphicsApp
 */
public static GraphicsApp getApplication() {
    return Application.getInstance(GraphicsApp.class);
}

/**
 * Main method launching the application.
 */
public static void main(String[] args) {
    launch(GraphicsApp.class, args);
}
}

At the last class is with graphics itself:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
*/

package graphics;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import javax.swing.JPanel;

public class Graph extends JPanel{

int[] data = {
    21, 14, 18, 03, 86, 88, 74, 87, 54, 77,
    61, 55, 48, 60, 49, 36, 38, 27, 20, 18
};
final int PAD = 20;

 protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
    int w = getWidth();
    int h = getHeight();
    // Draw ordinate.
    g2.draw(new Line2D.Double(PAD, PAD, PAD, h-PAD));
    // Draw abcissa.
    g2.draw(new Line2D.Double(PAD, h-PAD, w-PAD, h-PAD));
    double xInc = (double)(w - 2*PAD)/(data.length-1);
    double scale = (double)(h - 2*PAD)/getMax();
    // Mark data points.
    g2.setPaint(Color.red);
    for(int i = 0; i < data.length; i++) {
        double x = PAD + i*xInc;
        double y = h - PAD - scale*data[i];
        g2.fill(new Ellipse2D.Double(x-2, y-2, 4, 4));
    }
}

private int getMax() {
    int max = -Integer.MAX_VALUE;
    for(int i = 0; i < data.length; i++) {
        if(data[i] > max)
            max = data[i];
    }
    return max;
}
}

I have several questions:
(a) How to I make graph appear in jPanel1?
(b) What are good practices in initialization graphical components? I mean, where is the best place to call for graph()?
(c) For a different application I have used jfreechart to draw graphs and then dump them to a .jpeg file. Can I use jfreechart to build graphs and to show it directly in a pagel?
Thank you very much in advance!

A: Some answers:
(a) Have jPanel1 use BorderLayout for its layout manager and add the graph JPanel to jPanel1 in the BorderLayout.CENTER position.
(b) I'm not clear what you're asking here. You construct an object when you need it.
(c) Yes. JFreeChart's graph components extend Swing components, I believe JPanel (either that or JComponent), so you should be able to directly add them to your GUI as a component, as long as (and this is key), your component acting as a container, that is the one holding the chart, uses the right layout manager. If you haven't already done so, you should read the Swing tutorial on "Laying out Components in a Container" because it's information is key for this to succeed.
My final recommendation (for now) is to ditch the NetBeans code generation and create your Swing code by hand. It's really the best way to learn Swing.
Luck!


text:
Q: angular with firebase event handling Im making a poll app where people can create a new poll (question and responses) then that gets pushed to my firebase database and the questions get populated as a list in the left  side bar. I got that far and it works great.
Now i'm trying to make the take a poll feature so when a person clicks on the question they want to respond to, it updates the view for just that one question and ng-repeat for the number of responses there are.
Is there a firebase event handling similar to jquerys on click for .this to do this? How can I accomplish this, I feel stuck.

A: So I figured it out. For the nav bar on the left in my anchor tag within a ng repeat. I used a ng-click = "select(poll)" where poll being the ng-repeat = poll in polls
then in my controller I have this simple function
$scope.select = function(poll){
  $scope.selected = poll;
};

which then in my takeApollview (i'm using ui-router) I just use the selected to display all the key values.
Msg me if anyone has a similar problem and needs guidance.


text:
Q: Covering measure one sets by closed null sets (The following question arose in a joint research with Adam Przeździecki and Boaz Tsaban.)
For a $\sigma$-ideal $\mathcal{I}$ of subsets of the unit interval
$[0,1]$, define
$$\newcommand{\card}[1]{\left|#1\right|}\newcommand{\cov}{\operatorname{cov}}\newcommand{\sub}{\subset} \cov(\mathcal{I}):=\min\{\card{\mathcal{A}}: \mathcal{A}\sub \mathcal{I}, \bigcup\mathcal{A}=[0,1]\}.
$$
Let $\mathcal{E}$ be the family of all $F_\sigma$ Lebesgue null subsets of the unit interval, and $\mathcal{N}$ be the family of all Lebesgue null subsets of the unit interval.

*

*Let $\kappa_\mathcal{E}$ be the minimal cardinal number such that some measure one set is covered by $\kappa_\mathcal{E}$ elements of $\mathcal{E}$.

*Similarly, let $\kappa_\mathcal{N}$ be the minimal cardinal number such that some measure one set is covered by $\kappa_\mathcal{N}$ elements of $\mathcal{N}$.

We have $\kappa_\mathcal{E}\leq \cov(\mathcal{E})$, and $\kappa_\mathcal{N}=\cov(\mathcal{N})$.
Question 1: Is it provable that $\kappa_\mathcal{E}=\cov(\mathcal{E})$?
Question 2: Does the cardinal number $\cov(\mathcal{E})$ change if we work in a closed positive subset of the unit interval instead of the whole interval?
A negative answer for Question 2 implies a positive answer for Question 1.

A: The answer to the first question is yes: it is always true that $\kappa_{\mathcal E} = \mathrm{cov}(\mathcal E)$. The answer to the second question is no.
As Piotr points out, a negative answer to the second question implies a positive answer to the first. [This is because if $A \subseteq [0,1]$ is a set of measure one, then it contains a closed $K \subseteq [0,1]$ of positive measure (indeed, we can get the measure of $K$ as close to $1$ as we like). A negative answer to the second question means that it takes at least $\mathrm{cov}(\mathcal E)$ sets in $\mathcal E$ to cover $K$; since $K \subseteq A$, it takes at least $\mathrm{cov}(\mathcal E)$ sets in $\mathcal E$ to cover $A$ too.]
So it suffices to show that the answer to the second question is no: the $\mathcal E$-covering number is the same for any positive-measure closed subsets of $[0,1]$.
To see this, fix a closed $K \subseteq [0,1]$ of positive measure $\alpha$. Let $\mathcal F$ be a family of sets in $\mathcal E$ that covers $K$. Our goal is to cover $[0,1]$ with a family of sets in $\mathcal E$ of size $|\mathcal F|$. This shows that the $\mathcal E$-covering number for $[0,1]$ is no bigger than the analogous number for $K$. It is obvious that the $\mathcal E$-covering number for $[0,1]$ is no smaller than the analogous number for $K$, since any cover of $[0,1]$ by sets in $\mathcal E$ is also a cover of $K$.
Define a map $\phi: K \rightarrow [0,1]$ by
$$\phi(x) = \frac{1}{\alpha} \cdot m(K \cap [0,x])$$
for all $x \in K$, where $m$ denotes the Lebesgue measure. Using the fact that $K$ is closed, one can show that $\phi$ is surjective. In particular,
$$\phi(\mathcal F) = \{\phi[A \cap K] : A \in \mathcal F\}$$
is a family of sets that covers $[0,1]$. To finish the proof, it is enough to show that the map $A \mapsto \phi[A \cap K]$ sends sets in $\mathcal E$ to sets in $\mathcal E$: then $\phi(\mathcal F)$ is the desired $\mathcal E$-cover of $[0,1]$.
From the definition of $\phi$, we see
$$m(\phi[(0,b)]) = \frac{1}{\alpha} \cdot m(K \cap (0,b))$$
and taking complements we get
$$m(\phi[(a,1)]) = \frac{1}{\alpha} \cdot m(K \cap (a,1)).$$
and taking intersections, we see that for any interval $(a,b) \subseteq [0,1]$,
$$m(\phi[(a,b) \cap K]) = \frac{1}{\alpha}(m((a,b) \cap K)).$$
That is, $\phi$ can increase the measure of an interval by at most a factor of $\frac{1}{\alpha}$. With a little more (routine) work, this shows that the map $A \mapsto \phi[A \cap K]$ sends null sets to null sets.
Observe that $\phi$ is continuous (the inverse image of an open interval in $[0,1]$ is an open interval in $K$). Therefore $\phi$ maps compact sets to compact sets. Therefore the map $A \mapsto \phi[A \cap K]$ sends compact sets to compact sets. Since $[0,1]$ is compact, this means that it also sends $F_\sigma$ sets to $F_\sigma$ sets. So we have showed that the map $A \mapsto \phi[A \cap K]$ sends null $F_\sigma$ sets to null $F_\sigma$ sets, and we are done.


text:
Q: Override BQL used for PXProjection on SOShipmentPlan I have a need to override the Select statement being used for the SOShipmentPlan PXProjection/DAC, namely, removing the
And <INPlanType.isFixed, Equal<boolFalse>
condition.
I can override all of the CreateShipment() logic and bring in any other necessary routines into an SOShipmentEntry_Extension class, to the point where I finally can use my own version of a SOShipmentPlan class, but that all seems needlessly complex when all I want to do is override the select for the PXProjection attribute.  Overriding CreateShipment() and supporting routines also seems like a quick way to get in trouble come time for upgrades.
So, is there an easy way to override the PXProjection's BQL, or am I stuck overriding all kinds of code?
UPDATE 1
Based on a link provided below (stackoverflow.com/a/41540659/7376238), I feel like I'm close.  Here's the block of code I end up with:
namespace PX.Objects.SO
{
  public class SOShipmentEntry_Extension : PXGraphExtension<SOShipmentEntry>
  {
    #region Event Handlers

    #endregion

    [Serializable]
    [PXProjection(typeof(Select2<SOOrder,
      InnerJoin<SOOrderType, On<SOOrder.FK.OrderType>,
      InnerJoin<INItemPlan, On<INItemPlan.refNoteID, Equal<SOOrder.noteID>>,
      InnerJoin<INPlanType, On<INItemPlan.FK.PlanType>>>>,
    Where<INItemPlan.hold, Equal<boolFalse>,
      And<INItemPlan.planQty, Greater<decimal0>,
      And<INPlanType.isDemand, Equal<boolTrue>,
      And<INPlanType.isForDate, Equal<boolTrue>,
      And<Where<INItemPlan.fixedSource, IsNull,
        Or<INItemPlan.fixedSource, NotEqual<INReplenishmentSource.transfer>>>>>>>>>))]
    [PXSubstitute()]
    public partial class SOShipmentPlanCst : SOShipmentPlan
    {
      int x = 0;
    }
}

But it doesn't seem to work.  Not sure of where I'm supposed to put the code.  I've tried putting the class definition inside and outside of public class SOShipmentEntry_Extension : PXGraphExtension<SOShipmentEntry> class (currently inside the extension class as shown).  No luck either way.

A: THIS ANSWER DIDN'T WORK
Fair warning... I have not done this to a PXProjection before, so you'll have to see if this works.  The nature of extensions tends to allow overriding views by simply redefining them.  I have not done this myself with a projection, but I suspect it will be similar. Give it a try and see if you get the desired results.  All I can say about testing it is that "it compiled" when I added to my project and removed the INItemPLanType.isFixed condition.
public class SOShipmentEntry_Extension : PXGraphExtension<SOShipmentEntry>
{
    [PXProjection(typeof(Select2<SOOrder,
        InnerJoin<SOOrderType, On<SOOrder.FK.OrderType>,
        InnerJoin<INItemPlan, On<INItemPlan.refNoteID, Equal<SOOrder.noteID>>,
        InnerJoin<INPlanType, On<INItemPlan.FK.PlanType>>>>,
        Where<INItemPlan.hold, Equal<boolFalse>,
        And<INItemPlan.planQty, Greater<decimal0>,
        And<INPlanType.isDemand, Equal<boolTrue>,
        And<INPlanType.isForDate, Equal<boolTrue>,
        And<Where<INItemPlan.fixedSource, IsNull, Or<INItemPlan.fixedSource, NotEqual<INReplenishmentSource.transfer>>>>>>>>>))]
    public partial class SOShipmentPlan : IBqlTable { }
}


text:
Q: PayPal integration - Error #2096 in Flex Mobile So i am trying to integrate PayPal in my Flex Mobile app. I make my first call like this:
(keys are sandbox by paypal dev resources)
protected function getPaypal():void {
  var client_id:String="EOJ2S-Z6OoN_le_KS1d75wsZ6y0SFdVsY9183IvxFyZp";
  var secret:String="EClusMEUk8e9ihI7ZdVLF5cZ6y0SFdVsY9183IvxFyZp";

  var params:Object = new Object();
  params.grant_type="client_credentials";

  var encoder:Base64Encoder = new Base64Encoder();
  encoder.encode(client_id + ":" + secret);

  //var s:String = JSON.stringify(params);
  paypal.contentType = "application/x-www-form-urlencoded";
  paypal.headers["Authorization"] = "Basic " + encoder.toString();
  paypal.method = "POST";
  paypal.url = "https://api.sandbox.paypal.com/v1/oauth2/token";
  paypal.send(params);
  }

This fails and returns the following:
'Error #2096: The HTTP request header Basic RU9KMlMtWjZPb05fbGVfS1MxZDc1d3NaNnkwU0ZkVnNZOTE4M0l2eEZ5WnA6RUNsdXNNRVVrOGU5
aWhJN1pkVkxGNWNaNnkwU0ZkVnNZOTE4M0l2eEZ5WnA= cannot be set via ActionScript.' faultDetail:'null'

I can't figure out what seems to be the problem.
Any help?

A: Maybe this?
https://stackoverflow.com/a/539173/3384609
Gist:

You can fix this by setting (in the above example)
  encoder.insertNewLines = false; The default setting is true.


text:
Q: Firestore firebase admin listCollections get by field value I have subcollections with unknown names,  I can list them with listCollections from Node.js admin sdk. however, I want to list those subcollections based on the field value within that subcollection
root_collecton->docid1->subcollection_eiruj2929383ssk->doc->fieldvalue(timestamp)
subcollection_eiruj2929383ssk subcollection with unknown name
sort the subcollection based on the fieldvalue
Will it be possible? I am free to change the design, if any other suggestion please suggest.
Eg: Restaurants are the subcollection with unknown names, it has documents like menuitems, reviews, customer.
I want to list all unknown named restaurants sort by timestamp, a fieldvalue in customer document. so i want the restaurants to be ordered by the most recent customer check in.

A: It's not possible to filter the results from listCollections.
In general, it's not a good idea to have collections or subcollections with unknown names.  That works against good data modeling, and the way that Firestore was intended to be used.  Any variable values that require filtering need to be in document field values.  Consider instead making a restaurant a document and its menu items a subcollection nested under that document with a known name.


text:
Q: "I feel my heart go boom " or "goes boom"? Which one below is correct?:

*

*I feel my heart go boom

*I feel my heart goes boom

And why? Thank you in advance!

A: Both are possible.
"I feel my heart go boom" is parallel to "I see him go," "I hear it ring," etc., where the last verb (in each example) is an infinitive.
"I feel my heart goes boom" is parallel to "I see he is going," an ellipsis for "I feel that my heart goes boom." Here, obviously, the last verbs are no longer infinitives.
The first alternative seem more likely to be the intended message.
(Soon they'll be gathering in the comments to dock me a few points and whisper "irrealis" to each other; but there it is, I've done it, I've ventured into a discussion of grammar!)


text:
Q: Ansible: How can I group multiple folders with paths in an Inventory file I have five folders which have config files from different regions
I want to keep them under one group called region and run with each region name from the command line.
ex:
ansible-playbook script.yml region_name -k -K

How can I group the folders in Inventory file?

A: If you have a region named Foo defined in your inventory, you can limit the playbook to that using the -l or --limit parameter.
Inventory file (e.g. hosts in the current directory):
[Foo]
host1
host2

[Bar]
host3
host4

In your group_vars folder, you can then have one folder per group/region:
group_vars
  - Foo
    - regionvars.yml
  - Bar
    - regionvars.yml

Then when running the playbook, you can just run it for one region:
ansible-playbook -i hosts -l Foo script.yml

Please refer to the documentation of the ansible-playbook command for more info.


text:
Q: Get define value in preprocessor time in c I want to create a define using macro expansion. The crated define shall hold the value of an other define. :)
Example:
#define ONE            1
#define TWO            2
#define MACRO(x, y)    ...
...
#define MACRO_1_2      3

My question is: how can I resolve / use the value of a define in macro expansion?
I have tried to use
#define TEST_MACRO_V2(x, y)      TEST_MACRO_V2_"x"_"y"

, but I get the following error:

main.c:18:34: error: 'TEST_MACRO_V2_' undeclared (first use in this function)
   #define TEST_MACRO_V2(x, y)      TEST_MACRO_V2_"x"_"y"

My test code:
#include <stdio.h>

#define ONE   1
#define TWO   2

#define TEST_MACRO_V1(x, y)      TEST_MACRO_V1_##x##_##y
#define TEST_MACRO_V1_ONE_TWO    3

//#define TEST_MACRO_V2(x, y)    TEST_MACRO_V2_##('x')##_##('y')  -> this version does not work
#define TEST_MACRO_V2(x, y)      TEST_MACRO_V2_"x"_"y"
#define TEST_MACRO_V2_1_2        4

int main()
{
    printf("Test Macro V1: %d\n", TEST_MACRO_V1(ONE, TWO));
    printf("Test Macro V2: %d\n", TEST_MACRO_V2(ONE, TWO));

    return 0;
}

Note: TEST_MACRO_V1 works fine. I need TEST_MACRO_V2.

A: I tried this on ideone.com:
#include <stdio.h>

#define ONE   1
#define TWO   2

#define TEST_MACRO_HELPER(x, y) TEST_MACRO_##x##_##y
#define TEST_MACRO(x, y)        TEST_MACRO_HELPER(x, y)
#define TEST_MACRO_1_2          4

int main()
{
    printf("Test Macro: %d\n", TEST_MACRO(ONE, TWO));
    return 0;
}

Output:
Test Macro: 4