text:
Q: How are DACs integrated in color LCD screens? I'm having trouble imagining what actually happens inside an LCD screen.
I picture digital RGB data for each pixel getting sent to the screen through a connector. Lets say we have 24-bit color for each pixel, so 8 bits each for red, green, and blue subpixel. Inside the LCD, for each subpixel a voltage must be applied to control its intensity. This is where a DAC must come in to convert each 8 bit intensity value (digital) to a proportional voltage (analog). But, surely there is no DAC for every subpixel? My laptop screen is 1920x1080 so it has over 6 million subpixels.
So, how are these DACs integrated into the architecture of this LCD? How many DACs are in a single LCD screen?
I read that a transistor is used to select a particular liquid crystal cell and charge it/light it up, and a capacitor holds the charge briefly until the next refresh cycle. So that would eliminate the need for 6 million DACs, although it would mean you need 6 million transistors and capacitors. But I'm still wondering about these DACs - they never seem to get mentioned because people consider LCD screens "digital".

A: From this patent about TFTs:
The pixels are organized in a matrix like this:

and each pixel circuit looks like this:

During operation, voltage levels according to desired brightness levels for each pixel of a single row are put on the vertical lines Cn. After this, a signal on RAm and RBm activates the transistors of all pixels in that row, and the voltage levels Ci are transferred to a capacitor inside the pixel. The transistors are deactivated, and the whole process continues with the next pixel row.
That capacitor not only stores the voltage applied, it also is part of the liquid crystal cell and its electric field causes the crystals to move into the orientation needed for the desired brightness.
Here is also a drawing of the layout of a pixel:

Finally, I have to say I have no idea why there are two transistors, but I also didn't read the full document. The stuff is not as easy as described here, but it's OK to say that both transistors are used to put the voltage level of Cn onto the capacitor.
Now, you only need as many DACs as there are columns, but DACs can be quite simple and small.


text:
Q: Azure App Service encountering inconsistent HttpClient request failures We have an Azure App Service which is making calls to a third party API. Occasionally, and seemingly randomly, requests to this third party API will fail and then immediately begin working again. Roughly 20% of requests are failing. The third party are claiming that they have no issues on their end.
The code making the request is this:
try
{
  // simplified
  var httpRequest = new HttpRequestMessage
  {
    RequestUri = new Uri(requestUri),
    Method = HttpMethod.Get
  };
  httpRequest.Headers.Add("username", username);
  httpRequest.Headers.Add("token", accessToken);
  response = await _httpClient.SendAsync(httpRequest);

  response.EnsureSuccessStatusCode();
}
catch (Exception ex) {
  _logger.Log(ex)
}

Also note that the HttpClient is using pooling, defined in Startup.cs:
var jitter = new Random();
var retryPolicy = HttpPolicyExtensions.HandleTransientHttpError()
    .OrResult(msg => msg.StatusCode == HttpStatusCode.NotFound)
    .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)) + TimeSpan.FromMilliseconds(jitter.Next(0, 500))); // exponential backoff + jitter to prevent grouping

var sp = ServicePointManager.FindServicePoint(new Uri(_config.BaseUri));
sp.ConnectionLeaseTimeout = 60 * 1000;

services.AddHttpClient<IFooService, FooService>(client =>
{
    client.Timeout = TimeSpan.FromSeconds(10);
}).SetHandlerLifetime(TimeSpan.FromMinutes(10)).AddPolicyHandler(retryPolicy);

The exception, when it occurs, is this:
System.Threading.Tasks.TaskCanceledException: The operation was canceled.
   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at Polly.Retry.AsyncRetryEngine.ImplementationAsync[TResult](Func`3 action, Context context, CancellationToken cancellationToken, ExceptionPredicates shouldRetryExceptionPredicates, ResultPredicates`1 shouldRetryResultPredicates, Func`5 onRetryAsync, Int32 permittedRetryCount, IEnumerable`1 sleepDurationsEnumerable, Func`4 sleepDurationProvider, Boolean continueOnCapturedContext)
   at Polly.AsyncPolicy`1.ExecuteAsync(Func`3 action, Context context, CancellationToken cancellationToken, Boolean continueOnCapturedContext)
   at Microsoft.Extensions.Http.PolicyHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)

Note that at the time the app service fails, any requests sent via Postman work correctly, implying a network level issue in the app service.
I've seen similar questions regarding Azure Web Service/HttpClient issues suggest this is a SNAT exhaustion issue, however the Azure diagnostics tool states that SNAT is not a problem and is well within limits - see the image below:

Can anyone tell me why the app service would randomly prevent HttpClient requests, and how I can determine if this is the issue, and correct it.

redpajama_set_name: RedPajamaStackExchange


text: Q: Differential equations with infinite-dimensional Lie groups I am no expert in solving DEs by symmetry methods, but from pure interest - is it possible for a differential equation to have an infinite-dimesional Lie group as a symmetry group?


text:
Q: how to access a private member function? when it is a boolean? how to access a private member function? when it is a boolean?
this is my code:
    class IntQueue
    {
    private:
        bool isEmpty();         //private member function bool
        bool isFull();          //private member function bool
    public:
        bool isful();          //access isEmpty
        bool isemp();          //access isFull

    };

I was told to make the function isEmpty and isFull to a Private member function.
    //private function

    bool IntQueue::isEmpty()
    {
        bool status;

        if (numItems)
            status = false;
        else
            status = true;

        return status;
    }

    //private function

    bool IntQueue::isFull()
    {
        bool status;

        if (numItems < queueSize)
            status = false;
        else
            status = true;

        return status;
    }

is this a correct way of accessing a private function?
    //ACCESS THE PRIVATE MEMBER FUNCTION

    bool IntQueue::isemp()
    {
        isEmpty();
    }

    bool IntQueue::isful()
    {
        isFull();
    }

A: No because there are not return statement in C++ non-void functions. This invokes undefined behavior. You have to return what isEmpty() and isFull() returns.
    //ACCESS THE PRIVATE MEMBER FUNCTION

    bool IntQueue::isemp()
    {
        return isEmpty();
    }

    bool IntQueue::isful()
    {
        return isFull();
    }

A: how about if you want to use isEmpty() again to another method, can you automatically access isemp() or call isEmpty() again and return it?
like this
void IntQueue::dequeue(int &num)
{
    if (isemp())
        cout << "The queue is empty.\n";
    else
    {
        // Move front
        front = (front + 1) % queueSize;
        // Retrieve the front item
        num = queueArray[front];
        // Update item count
        numItems--;
    }
}

or this:
void IntQueue::dequeue(int &num)
{
    if (isEmpty())
        cout << "The queue is empty.\n";
    else
    {
        // Move front
        front = (front + 1) % queueSize;
        // Retrieve the front item
        num = queueArray[front];
        // Update item count
        numItems--;
    }
return isEmpty();
}


text:
Q: How to remove a line from a file without overwriting the contents in a new file FileName="1.pdf",filepath="f:/test1"
FileName="2.pdf",filepath="f:/test2"
FileName="3.pdf",filepath="f:/test3"
FileName="4.pdf",filepath="f:/test4"
FileName="5.pdf",filepath="f:/test5"
FileName="6.pdf",filepath="f:/test6"

I don't want to create a new file. Overwriting in a same file is ok
I tried the following.
var reader = File.OpenText("f:/test5");
reader. // ?

I don't know what to put after reader. If any alternate way is there, provide me a solution.I want to remove only a particular line based on the unique file name. If I am having 5.pdf as the filename, then I need to delete or remove the entire line which is "FileName="5.pdf"...line from the file. I don't want to overwrite the contents in a new file again. Provide me a solution. Thanks.

A: You cannot reomve a line from a textfile without rewriting the file. Do something like this
string filename =
   Path.Combine(
       Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
       "Test1.txt");

string[] lines = File.ReadAllLines(filename);
var list = new List<string>(lines);
list.RemoveAt(4);
File.WriteAllLines(filename, list.ToArray());

EDIT:
You can find a line with a specific filename like this:
int index = list.FindIndex(s => s.EndsWith("/test5\""));
// Or whatever test is appropriate.

if (index >= 0) {
    list.RemoveAt(index);
    File.WriteAllLines(filename, list.ToArray());
}

A: If you don't mind using gnu tools, you can use sed http://en.kioskea.net/faq/1451-sed-delete-one-or-more-lines-from-a-file

A: It's technically impossible, as much as I'm aware of, as OS will create a new IO artifact.(By the way not very sure on this) .
But what is much more important, that it's extremely dangerous. IO operations are subjects to fail, so you have to gurantee in some way consistency of your operations on file.
One of possible ways of doing this is:

*

*write all lines, except those ones you want to skip, into the new TEMP file

*rename your old file with some other temp name

*rename fisrt TEMP file in name of previous file

*delete original file.

A: No matter what utility you use or what code you write, the operating system will always create a new file to do it.


text:
Q: Automatic creation of Vimeo video previews for use in wordpress archive.php I am trying to find a method of automatically making 3-7 sec long previews of my video + films for use in a WordPress video wall gallery in such as what's found here: https://scale.la/test.html
Currently I have to save these cut down and export each file as a <1mb MP4 and embed using  tags by hand. They then link to pages that have the Vimeo player embedded [using Vimeotheque, a WP plugin for automatic Vimeo posting]. When displaying an archive of posts / Vimeo videos, the previews are based on the Preview Thumbnail.
What I would like to do is replace that Thumbnail with a video thumbnail like my test — that is extracted from the longer form video already on Vimeo.
Are there any provisions to do this with current Vimeo tools?
Thanks,
Todd


text:
Q: Pylint in Codio keeps telling me I have indentation errors, but there is no way to fix the indents without breaking my code I am trying to submit a turtle program in codio, but the autograder keeps telling me I am missing indentations in my function definition section. My program works perfectly in other IDE's like repl.it and VScode. Codio is basically saying that everything needs to be indented 1 more, but if I do that it will break.
Here is a section of my code. The indentation is the same throughout all of my functions:
def triangle(size):
    for _i in range(3):
    bby.forward(size)
    bby.rt(120)

def rectangle(size):
  for _i in range(2):
    bby.forward(size*2)
    bby.rt(90)
    bby.forward(size)
    bby.rt(90)


text:
Q: Slow Excel VBA code I have tried to write a code that will look at cells in B2 from Row 4 to R2000 and if the content is zero then hide the row. My problem is that the code is running very slow and often stops responding.
If you can help me what it is that is causing it to run slow, I can probably fix it myself, but I am not sure what would be a more efficient approach. As you can see I have tried with turning screen updates off, but it didn't help much.
The code is below
Sub HideRows()

   BeginRow = 4
   EndRow = 2059
   ChkCol = 2

   Application.ScreenUpdating = False

   Rows("1:2059").EntireRow.Hidden = False

   For RowCnt = BeginRow To EndRow
       If Cells(RowCnt, ChkCol).Value = 0 Then
           Cells(RowCnt, ChkCol).EntireRow.Hidden = True
       End If
   Next RowCnt

   Application.ScreenUpdating = True

End Sub

A: Try hiding everything in one go instead of every time a 0 is found
Sub HideRows()
    Dim BeginRow As Long, EndRow As Long, ChkCol As Long
    Dim HideRng As Range

    BeginRow = 4
    EndRow = 2059
    ChkCol = 2

    Application.ScreenUpdating = False

    Rows("1:2059").EntireRow.Hidden = False

    For rowcnt = BeginRow To EndRow
        If Cells(rowcnt, ChkCol).Value2 = 0 Then
            If HideRng Is Nothing Then
                Set HideRng = Cells(rowcnt, ChkCol)
            Else
                HideRng = Union(HideRng, Cells(rowcnt, ChkCol))
            End If
        End If
    Next rowcnt

    If Not HideRng Is Nothing Then HideRng.EntireRow.Hidden = True

    Application.ScreenUpdating = True

End Sub

A: Without seeing your workbook, it's hard to know for sure, but generally Excel is pretty slow at hiding rows. In your code, each row is hidden one at a time, so that's potentially 1000+ individual "hide this row" commands to Excel.
It's much faster to hide the rows in "chunks". This macro (I wrote it ages ago because I was dealing with the same problem) does that, so it should be much faster. In your case, you'd call it like this:
Call hideRows(ActiveSheet, 4, 2059, 0, 2, 2)

There's also an inverted setting that would hide rows unless the value in column 2 was equal to zero. You'd just add "True" to the end of your function call.
Sub hideRows(ws As Worksheet, startRow As Long, endRow As Long, valCrit As Variant, Optional startCol As Long = 1, Optional endCol As Long = 1, Optional invert As Boolean = False)

    Dim loopCounter As Long
    Dim rowCounter As Long
    Dim colCounter As Long
    Dim endConsRow As Long
    Dim tempArr As Variant
    Dim toAdd As Long
    Dim toHide As String
    Dim sameVal As Boolean
    Dim consBool As Boolean
    Dim tempBool As Boolean
    Dim rowStr As String
    Dim goAhead As Boolean
    Dim i As Long

    If startRow > endRow Then
        toAdd = endRow - 1
    Else
        toAdd = startRow - 1
    End If

    tempArr = ws.Range(ws.Cells(startRow, startCol), ws.Cells(endRow, endCol)).Value

    ws.Rows(startRow & ":" & endRow).Hidden = False

    loopCounter = 1
    For rowCounter = LBound(tempArr, 1) To UBound(tempArr, 1)
        For colCounter = LBound(tempArr, 2) To UBound(tempArr, 2)
            sameVal = False
            goAhead = False
            If IsNumeric(valCrit) Then
                If tempArr(rowCounter, colCounter) = valCrit Then
                    sameVal = True
                End If
            Else
                If tempArr(rowCounter, colCounter) Like valCrit Then
                    sameVal = True
                End If
            End If
            If sameVal Then
                If invert = True Then
                    loopCounter = loopCounter + 1
                    Exit For
                End If
                goAhead = True
            ElseIf colCounter = UBound(tempArr, 2) Then
                If invert = False Then
                    loopCounter = loopCounter + 1
                    Exit For
                End If
                goAhead = True
            End If
            If goAhead = True Then
                endConsRow = rowCounter
                consBool = True
                Do Until consBool = False
                    tempBool = False
                    For i = LBound(tempArr, 2) To UBound(tempArr, 2)
                        sameVal = False
                        If endConsRow = UBound(tempArr, 1) Then
                            Exit For
                        ElseIf IsNumeric(valCrit) Then
                            If tempArr(endConsRow + 1, i) = valCrit Then
                                sameVal = True
                            End If
                        Else
                            If tempArr(endConsRow + 1, i) Like valCrit Then
                                sameVal = True
                            End If
                        End If
                        If sameVal Then
                            If invert = False Then
                                endConsRow = endConsRow + 1
                                tempBool = True
                            End If
                            Exit For
                        ElseIf i = UBound(tempArr, 2) Then
                            If invert = True Then
                                endConsRow = endConsRow + 1
                                tempBool = True
                            End If
                        End If
                    Next
                    If tempBool = False Then
                        consBool = False
                    End If
                Loop
                rowStr = loopCounter + toAdd & ":" & endConsRow + toAdd
                If toHide = "" Then
                    toHide = rowStr
                ElseIf Len(toHide & "," & rowStr) > 255 Then
                    ws.Range(toHide).EntireRow.Hidden = True
                    toHide = rowStr
                Else
                    toHide = toHide & "," & rowStr
                End If
                loopCounter = loopCounter + 1 + (endConsRow - rowCounter)
                rowCounter = endConsRow
                Exit For
            End If
        Next
    Next

    If Not toHide = "" Then
        ws.Range(toHide).EntireRow.Hidden = True
    End If

End Sub

A: Can you use Autofilter?

Option Explicit

Public Sub HideRowsWhereColBis0()

    ActiveSheet.Range("B4:B2059").AutoFilter Field:=1, Criteria1:="<>0"

End Sub


text:
Q: How to add certificate inside a dind container, because it needs restart of docker I am first spinning up a docker container
docker run --rm -it docker:19.03.13
#/

and then run the below commands
apk update

apk add --update openssl

openssl s_client -showcerts -connect registry.somedomain.com:443 < /dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ca.crt

cp ca.crt /usr/local/share/ca-certificates/

update-ca-certificates

systemclt restart docker    <--- THIS STEP HOW TO DO IN THE DOCKER CONTAINER

docker login registry.gitlab.com

A: first of all, why you need docker inside docker.
A pretty good post why you should not do docker in docker link
There are some use cases where we really need. looks like in your case. as its deals with certificates.
There are some good strategies define in this link here.
Also follow this video tutorial if you really wanted to use docker in docker link


text:
Q: ThreeJS access objects within loaded obj model Say I have a obj model of a map consisted of tree objects, and I can load the model successfully, how can I access one tree object called Tree1?
Currently I have

loader.load( 'map.obj', function ( object ) {
     scene.add( object );
     var Tree1 = object.getObjectByName( "Tree1" );
     console.log(Tree1.position.x + " " + Tree1.position.y + " " + Tree1.position.z);

    }, onProgress, onError );

It always give me (0,0,0) no matter which object I choose.

A: Make sure your Tree1 really contains your mesh. Then call:
console.log( Tree1.getWorldPosition() );
to get its "absolute" position.


text:
Q: Hibernate: Wrong column type: accountBalance, expected: numeric(19,2)? I'm getting the following error.

Wrong column type: accountBalance, expected: numeric(19,2).

I tried adding the columnDefinition="smallmoney"
But didn't work.
I can change it to Integer but I'm little bit cautious after reading this mapping.. http://jtds.sourceforge.net/typemap.html
Any Ideas what to do..I'm using MSSQL server in the backend..
Changed it to Integer now its saying

Wrong column type: accountBalance, expected: int

My current annotation Definition is like this.
@Column(name = "AccountBalance",columnDefinition="smallmoney", nullable = false, precision = 10)
 private BigDecimal accountBalance;

A: What I was doing was correct, I was getting that error because I had kept
hibernate.hbm2ddl.auto = validate //validate the schema, makes no changes to the database.

After changing This value to
hibernate.hbm2ddl.auto = update  // update the schema.

everything works fine..
but not sure about the actual cause...


text:
Q: comparing two arrays elements, in similar indexes with each other I have two arrays with same number of members (always)$userInputArr=array("z","z","E","z","z","E","E","E","E","E"); and $user2InputArr=array("a","a","a","z","a","E","E","E","a","E"); I know how to find matching members in two arrays. Here I want to find matching elements with similar indexes e.g. if $userInputArr[4] == $user2InputArr[4], increment $matches. In my attempt below, I loop through both arrays but I cannot get $matchs to increment.
$match = 0;
for ($c =0; $c < count($$userInputArr); $c++) {
    for ($d = $c; $d<count($user2InputArr);$d++) {
        if ($userAnsStrArr[$c] == $userInputArr[$d]) {
            $match = $match +1;
        }
    }
}

A: This question is the perfect example for the PHP function array_intersect_assoc():
$array1 = array("z","z","E","z","z","E","E","E","E","E");
$array2 = array("a","a","a","z","a","E","E","E","a","E");

// Find the matching pairs (key, value) in the two arrays
$common = array_intersect_assoc($array1, $array2);
// Print them for verification
print_r($common);

// Count them
$match = count($common);
echo($match." common items.\n");

The output is:
Array
(
    [3] => z
    [5] => E
    [6] => E
    [7] => E
    [9] => E
)
5 common items.

A: $match = 0;
for ($c =0; $c < count($$userInputArr); $c++) {

    if ($userAnsStrArr[$c] == $userInputArr[$c]) {
            $match = $match +1;
        }

}

You should do like this.

A: This works for me
$i = sizeof($userInputArr);

 $match = 0;
for($j = 0; $j < $i; $j++)
    if ($userInputArr[$j] == $user2InputArr[$j]) {
        $match = $match +1;
    }

A: Here is the code for you. Just use one foreach, traverse through first array, and check for the key-value in second array.
$s = array("z","z","E","z","z","E","E","E","E","E");
$b = array("a","a","a","z","a","E","E","E","a","E");

foreach($s as $k => $v) {
    if($b[$k] === $s[$k]) {
        echo $k . ' is the index where keys and values exactly match with value as ' . $b[$k];
    }
}

And Output:
3 is the index where keys and values exactly match with value as z
5 is the index where keys and values exactly match with value as E
6 is the index where keys and values exactly match with value as E
7 is the index where keys and values exactly match with value as E
9 is the index where keys and values exactly match with value as E

And here is the link: https://3v4l.org/eX0r4

A: I seems your code not need two for loop increase match in single loop see below code.
<?php
$userInputArr=array("z","z","E","z","z","E","E","E","E","E");
$user2InputArr=array("a","a","a","z","a","E","E","E","a","E");
$match = 0;
for ($c =0; $c < count($userInputArr); $c++) {
    if ($user2InputArr[$c] == $userInputArr[$c]) {
        $match = $match + 1;
    }
}
echo $match;
?>


text:
Q: How do i make my .bat file run linux command to remote linux Below is my current .bat content. i run it on window cmd. it will connect to remote linux server and prompt me password. but after i put the password and login as remotehost, linux server wont run my ls command. please help.
@echo off
ssh remotehost@10.1.1.10
ls

A: You really should do man ssh as this is explained there (and you could also make an internet search to get an answer).
But, to answer your question anyway: you should put all commands you want to run on the remote machine on the same line with the actual ssh command, for example to run directory listing and grep all files containing "foo", do: ssh <user>@<host> 'ls|grep foo'.

A: I hinted that it is possible to have the code in a batch file in my comment to @Sami Laine. This is what it would look like:
@echo off
setlocal
    :: Run the end of this file in remote computer
    more +8 %0 | plink user@remote.compu.ter "tr -d '\r'| bash"
endlocal
exit /b 0

:: remote bash stuff to be bootstrapped

pwd
ls -h

I'm using plink, because that what I have installed but it should work with most flavors of ssh too. Works also with ksh and zsh. Probably also with tcsh csh etc. This can sometimes be useful. Same technique can be used for a lot of things. Be careful with the +8 offset value it has to be on the right line.


text:
Q: FB.Event.subscribe('edge.create') not firing I'm trying to make some functionality happen when the like button in a like box is clicked, however the function isn't firing (as well as two cross-domain errors appearing in the console, but I figure that's unrelated.)
Basically the code I'm using:
<div id="fb-root">
    <fb:like-box href="//www.facebook.com/MYPAGE" width="292" height="290"
     show_faces="true" stream="false" header="true"></fb:like-box>
</div>

<script>
    window.fbAsyncInit = function() {
        FB.init({
            appId: 'MYID',
            status: true,
            cookie: true,
            xfbml: true
        });

        FB.Event.subscribe('edge.create', function (response) {
                alert('You liked the URL: ' + response);
        });
    };

    (function(d) {
        var js, id = 'facebook-jssdk'; if (d.getElementById(id)) { return; }
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        d.getElementsByTagName('head')[0].appendChild(js);
    }(document));
</script>

MYPAGE and MYID are valid in the actual code, of course. 95% of the code is just copy/pasted, so I have no idea why it isn't working. If it's something obvious, then this should be easy points.
Any help would be very appreciated.
Edit- Oh and the HTML tag of course:
<html xmlns="http://www.w3.org/1999/xhtml"
 xmlns:fb="http://www.facebook.com/2008/fbml">


text:
Q: differential equations with 2 independent variables If ${\Phi(x)=z}$ and ${v(z) = y(x)\Psi(x)}$ then how would you solve the equation
$\frac{\Phi''}{\Phi'} = 2\frac{\Psi'}{\Psi}$

A: A quick integration of both sides reveals that:
$$ \Phi^{(1)} = C \Psi^2$$
Using the definition of $\Phi$:
$$ v(\Phi(x)) = y(x) \Psi(x) $$
Squaring this equation, we see that:
$$ C v(\Phi(x))^2 = y(x)^2 \Phi^{(1)}(x)$$
You then have an ODE in only a single variable $\Phi(x)$ to solve.
Edit:  I might not be answering the question you actually want answered.  If this is a general version of a more specific problem, it'd be handy to know the specific problem.


text:
Q: ASP.net MVC 3 changing the default edit boxes generated by controllers to a date time picker Thank you for taking the time to read this.. i have created a model and then created the index,create,edit,delete views using a controller. by default the system gives you views that have edit boxes  and labels like this....

@Html.LabelFor(Function(model) model.LessonDate)

        @Html.EditorFor(Function(model) model.LessonDate)
        @Html.ValidationMessageFor(Function(model) model.LessonDate)

i want to change this editor field to a date time picker. the code i have for the date tim picker is:
<input id="demo2" type="text" size="25">

the date time picker works and appears on the view but it does not save the date to the database i have... how do i achieve this?
thank you in advance for reading this

A: you need to use the name to send the information back to the controller I think all you need to do is to add the name
<input id="demo2" name="LessonDate" type="text" size="25">


text:
Q: How do I hide text that is not wrapped in  or ? I have html where I only want to hide the text portion, but what complicates it is that it is not wrapped in anything. Below is an example:

    Give comfortable and durable place to work with a desk.
    Lock the center drawer and all of the drawers lock,
    keeping your files and supplies secure.

                Available Options:
                Desktop Color: Fusion Maple, Gray Nebula...

                Book Box Construction:
                Not applicable

How can I hide the "Give comfortable and durable..." portion above without changing the html at all? I was hoping to do it via CSS and maybe Javascript if necessary. CSS only would be perfect though. Can anyone help?

A: Look ma', no hands scripts!
CSS only solution
.content
{
    text-indent: -1000em;
}

.content *
{
    text-indent: 0;
}

/* This one's pure cherry on top ;) */
/* Remove excess vertical space */
.content *:first-child
{
    margin-top: -1em;
}

JSFiddle demo.

A: CSS defines the appearance of the contents of a tag. No tag, no styling.
You need to modify the HTML. Sorry.

A: This removes the text node, which is a container for the text:
var div = document.getElementsByTagName('div')[0];
div.removeChild(div.firstChild);

A: Using javascript (and jQuery in my case):
var table = $('.content table'); //copy the table
$('.content').html(table); //replace the html of div.content with table

If you have multiple classes of content then you'll need to rewrite this a bit to work over a collection

A: There is no easy way for that. You'll have to write an html stripper on JavaScript or simply modify your html by hands.

A: CSS:
#content {
  visibility: hidden;
}

JavaScript:
document.getElementsByTagName("div")[0].style.visibility = "hidden";
or:
document.getElementsByClassName("content")[0].style.visibility = "hidden";


text:
Q: Проброс исключения в методе интерфейса Зачем указывать для не дефолтного и не статического (т.е. обычного) метода интерфейса пробрасываемое им исключение?
Ведь при реализации данного метода в каком-то классе, имплементирующем данный интерфейс мы вовсе не обязаны обеспечить проброс данного исключения.
Вот пример:
import java.io.IOException;

public interface MyCommand {
    void exit() throws IOException;
}

public class Main implements MyCommand{
    @Override
    public void exit() {
        System.out.println("Сработал метод exit()");
    }

    public static void main(String[] args) {
        new Main().exit();
    }
}

A: Интерфейс он не для Вас, он для вызывающей стороны и он показывает что вызывающая сторона должна обработать исключение, а бросите вы его или нет в конкретной реализации уже дело реализации.

В вашем примере при вызове исключение не требуется к обработке т.к. вы обращаетесь не к интерфейсу, а к объекту Main и его методу exit напрямую, приведите тип и все произойдет, вот полюбуйтесь:
import java.io.IOException;

public interface MyCommand {
    void exit() throws IOException;
}

public class Main implements MyCommand{
    @Override
    public void exit() {
        System.out.println("Сработал метод exit()");
    }

    public static void main(String[] args) {
        Main m = new Main();
        // не требует обработки т.к. метод Main.exit не имеет исключения в сигнатуре
        m.exit();

        MyCommand c = (MyCommand) m;
        // требует обработки т.к. метод MyCommand.exit имеет исключение в сигнатуре
        c.exit();
    }
}


text:
Q: Android Studio Missing parameter error when calling POST with parameters I am trying make a call to a Web Service (asmx) with parameters but I keep getting a "Missing parameter: Lane" response. the code below is what i am using
final HttpClient Client = new DefaultHttpClient();
        String jsonstring = "", step = "0";
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("Lane", "1"));
            params.add(new BasicNameValuePair("Name", "Test test"));

            HttpPost httppostreq = new HttpPost(url);

            httppostreq.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpresponse = Client.execute(httppostreq);

            jsonstring = EntityUtils.toString(httpresponse.getEntity());

I am able to call the Web Serviceusing Postman when I add the parameters in the header and set the "Content Type:application/x-www-form-urlencoded" but can't make it work in Android Studio

This is the code in my webservice:
   [WebMethod]
    public void MyTestService(string Lane, string Name)
    {
            Dictionary<string, object> parameter = new Dictionary<string, object>();
            parameter.Add("@lane", Lane);
            parameter.Add("@name", Name);

            DataSet dt = DataAccess.executeStoreProcedureDataSet("sp_GetLaneName", parameter);
            string jsonReturned = JsonConvert.SerializeObject(dt, Formatting.Indented);
            Context.Response.ContentType = "text/plain; charset=UTF-8";
            Context.Response.Write(jsonReturned);
    }

A: Add Header to your request below
httppostreq.setHeader(HTTP.CONTENT_TYPE,
                    "application/x-www-form-urlencoded;charset=UTF-8");


text:
Q: Understanding whitespace regex in jQuery source I was just trying to understand jQuery source of the white space trim REGEX and came across the following:
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,

Now using a REGEX TOOL , i understood the following:
/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g
1st Alternative: ^[\s\uFEFF\xA0]+
^ assert position at start of the string
[\s\uFEFF\xA0]+ match a single character present in the list below
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
\s match any white space character [\r\n\t\f ]
\uFEFF matches the character uFEFF literally (case sensitive)
\xA0 matches the character   with position 0xA0 (160 decimal or 240 octal) in the character set
2nd Alternative: [\s\uFEFF\xA0]+$
[\s\uFEFF\xA0]+ match a single character present in the list below
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
\s match any white space character [\r\n\t\f ]
\uFEFF matches the character uFEFF literally (case sensitive)
\xA0 matches the character   with position 0xA0 (160 decimal or 240 octal) in the character set
$ assert position at end of the string
g modifier: global. All matches (don't return on first match)

The above description makes the REGEX very easy to understand, but still thinking about the implementation practically, a few things don't make sense , I.E.
uFEFF why would a sting ever have this character and what does it have to do with white spaces ?  And also what on earth is xA0 ?
Can anybody explain ? you don't have to give the most detailed answer a short brief one will do.

A: 0xFEFF is known as ZERO WIDTH NO-BREAK SPACE and is possibly not caught on some browsers by using \s alone. Ditto for 0x00A0, NO-BREAK SPACE.
See this document for some more detail on what is caught by \s in ECMA 262 (which is the standard for Javascript.) According to that spec, jQuery is being overly cautious since the characters in question are already included. Likely this is due to browser compatibility.


text:
Q: Is it possible to use libcurl without file descriptor based socket? I wrote the following libcurl code with my custom write and read socket functions:
//...
CURL *curl;
FILE *fp;
CURLcode res;
char outfilename[FILENAME_MAX] = "file";
curl = curl_easy_init();

/* no progress meter please */
//curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L);

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &sharedValue);

curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data);
curl_easy_setopt(curl, CURLOPT_READDATA, &sharedValue);

curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, opensocket);
curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, &sharedValue);

curl_easy_setopt(curl, CURLOPT_CLOSESOCKETFUNCTION, closecb);
curl_easy_setopt(curl, CURLOPT_CLOSESOCKETDATA, &sharedValue);

curl_easy_setopt(curl, CURLOPT_URL, hostname.c_str());

curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);

curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);

res = curl_easy_perform(curl);

curl_easy_cleanup(curl);

I didn't know what to do with CURLOPT_SOCKOPTFUNCTION so I did sockopt_callback which is
static curl_socket_t opensocket(void *clientp,
                                curlsocktype purpose,
                                struct curl_sockaddr *address)
{
    return 0;
}

But I get
*   Trying 212.183.159.230:80...
* Could not set TCP_NODELAY: Socket operation on non-socket
* connect to 212.183.159.230 port 80 failed: Socket operation on non-socket
libcurl wants to close 0 now

because probably it's trying to write to the socket 0. Apparently I can't prevent it from calling options on the socket, for example setting TCP_NODELAY and most important, connect.
Is it possible to make libcurl do not call the socket file descriptor ever?
One idea I had was to pass an existing socket to be a dummy for libcurl and then still use my write and read functions. However, libcurl simply send things through the socket, not the write and read functions

A: I thought write_data was a way to redirect the socket calls but it has nothing to do with it, it actually is a function that writes what the client receives.
However, by passing a socketpair, as sugested by @domen, I made it work!
Sketch:

    //...

    static curl_socket_t opensocket(void *clientp,
                                curlsocktype purpose,
                                struct curl_sockaddr *address)
    {
        auto *sharedValue = static_cast<SharedValue *>(clientp);
        return sharedValue->curl_socket;
    }

    int socket_vector[2];
    if (0 != socketpair(AF_UNIX, SOCK_STREAM, 0, socket_vector))
    {
        std::cout << "problem creating socketpair" << std::endl;
        std::exit(2);
    }

    sharedValue.curl_socket = socket_vector[0];
    sharedValue.vpn_socket = socket_vector[1];

    //writes the result to a file
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_file);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, destFile);

    curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, opensocket);
    curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, &sharedValue);

    curl_easy_setopt(curl, CURLOPT_CLOSESOCKETFUNCTION, closecb);
    curl_easy_setopt(curl, CURLOPT_CLOSESOCKETDATA, &sharedValue);

    curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);

    curl_easy_setopt(curl, CURLOPT_URL, hostname.c_str());

    //curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);

    //Start a thread here that will read/write to the socket pair on the other endpoint (in my case vpn_socket)

    res = curl_easy_perform(curl);

    curl_easy_cleanup(curl);

    if (res)
    {
        std::cout << "libcurl error code: " << res << ", libcurl error: " << curl_easy_strerror(res) << std::endl;
        return 1;
    }


text:
Q: How to cancel all queued request onFailure? (Retrofit2) Actually i'm using Retrofit2 in my app for sending some text to my server.
The issue is when i'm using a Radio Frequency Device when the network is interrupted so i'm getting onFailure the call should be cancelled but as soon as the device is reconnected to the network seems it's resending the text or something like that text remain in queue and i would handle it.
Here is my method where i'm sending the text ( i've yet tryed to use call.cancel() in onFailure but that has no effect )
  @SuppressLint("DefaultLocale")
    public void sendPost() {
        @SuppressLint({"SdCardPath", "DefaultLocale"}) final File file = new File("/data/data/app/files/"+String.format("%03d", Integer.valueOf(nTerminalino))+"_"+nTavoli.getText().toString()+".txt");

        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);

        RequestBody fbody = RequestBody.create(MediaType.parse("text/*"), file);
        builder.addFormDataPart(String.format("%03d", Integer.valueOf(nTerminalino))+"_"+nTavoli.getText().toString(), file.getName(),fbody);

        MultipartBody requestBody = builder.build();

        final APIService apiService = ApiUtils.getAPIService(ipCASSA);

        final Call<Void> calls = apiService.savePost(requestBody);

        calls.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) {
                if (response.isSuccessful()) {
                    Log.i("RESPONSE: ", response.toString());
                    Print();
                    file.delete();
                    dialogLoading.dismiss();
                    Runtime.getRuntime().gc();
                }else {
                    calls.cancel();
                }
            }

            @Override
            public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
                    Log.e("TAG", t.toString());
                    MediaPlayer mpFound = MediaPlayer.create(pterm.this, R.raw.errorsound);
                    mpFound.start();
                    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                    if (v.hasVibrator()) {
                        v.vibrate(6000);
                    }
                    new GlideToast.makeToast(pterm.this, "CONNESSIONE FALLITA!", GlideToast.LENGTHLONG, GlideToast.FAILTOAST).show();
                    dialogLoading.dismiss();

            }
        });
    }

In my class where i'm building OkHttpClient i've set retryOnConnectionFailure(false) but still unable to solve the problem that even onFailure i'm getting the POST request.
UPDATE:
After some research i found that OkHttp make's silent retry of POST on connection failure.
So how can i prevent the client to retry?
SOME INFO:
My app is an app for waiter so when i get a onFailure message i notify the waiter that the receipt hasn't been received by POS and hasn't been printed but as OkHttpClient still retry to sending the file and i'm forcing the waiter to resend the receipt after onFailure it cause printing duplicated receipts.
Here is my ApiUtils class , APIService interface and RetrofitClient class
class ApiUtils {

    private ApiUtils() {}

    static APIService getAPIService(String ipCASSA) {

        String BASE_URL = "http://"+ipCASSA+"/web/";

        final OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .writeTimeout(10000, TimeUnit.MILLISECONDS)
                .readTimeout(10000, TimeUnit.MILLISECONDS)
                .retryOnConnectionFailure(false)
                .build();

        return RetrofitClient.getClient(BASE_URL,okHttpClient).create(APIService.class);
    }
}

public interface APIService {

    @POST("CART=PTERM")
    Call<Void> savePost(@Body RequestBody text);

}

class RetrofitClient {

    private static Retrofit retrofit = null;

    static Retrofit getClient(String baseUrl, OkHttpClient okHttpClient) {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

A: You could try canceling the call directly. So when the call fails, in the onFailure callback, you can do something like
@Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
    if (!call.isCanceled()) {
        // Do receipt logic
        call.cancel();
    }
}

A: Since retryOnConnectionFailure(false) didn't help, the problem is not caused by OKHttp retry.
I suspect you are duplicating the request. Check whether sendPost() is getting called multiple times.


text:
Q: Using cmake with a shared (dynamic) library I'm trying to use a simple shared library that I made with a file that just contains a main method.
I first ran cmake . which worked fine and didn't return any errors.
Then I ran make but got this error:
$ make
Scanning dependencies of target myprog
[ 50%] Building C object CMakeFiles/myprog.dir/main.c.o
[100%] Linking C executable myprog.exe
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -lhello-user
collect2: error: ld returned 1 exit status
clang-3.8: error: linker (via gcc) command failed with exit code 1 (use -v to see invocation)
make[2]: *** [CMakeFiles/myprog.dir/build.make:95: myprog.exe] Error 1
make[1]: *** [CMakeFiles/Makefile2:68: CMakeFiles/myprog.dir/all] Error 2
make: *** [Makefile:84: all] Error 2

The CMakeLists.txt file
cmake_minimum_required(VERSION 2.8.8)
project(LIB_EXAMPLE)
set(CMAKE_C_COMPILER clang)
add_executable(myprog main.c)
target_link_libraries(myprog hello-user)

The library exists inside of /usr/local/lib/ as libhello-user.dll.a
Note: Im using Cygwin for cmake and make

A: Turning my comment into an answer
See CMake/Tutorials/Exporting and Importing Targets.
You either have:

*

*to name a full path for the library

*

*CMake is not searching for it automatically

*you would have to add something like find_library(_lib_path NAMES hello-user)

*or - better - put those into an IMPORTED target
cmake_minimum_required(VERSION 2.8.8)
project(LIB_EXAMPLE)

add_library(hello-user SHARED IMPORTED GLOBAL)
set_target_properties(
    hello-user
    PROPERTIES
        IMPORTED_LOCATION /usr/local/lib/libhello-user.dll
        IMPORTED_IMPLIB   /usr/local/lib/libhello-user.dll.a
)

add_executable(myprog main.c)
target_link_libraries(myprog hello-user)


text:
Q: Using Redis to cache data that is in use in a Real TIme Single Page App I've got a web application, it has the normal feature, user settings etc these are all stored in MYSQL with the user etc.....
A particular part of the application a is a table of data for the user to edit.
I would like to make this table real time, across multiple users. Ie multiple users can open the page edit the data and see changes in real time done by other users editing the table.
My thinking is to cache the data for the table in Redis, then preform all the actions in redis like keeping all the clients up to date.
Once all the connection have closed for a particular table save the data back to mysql for persistence, I know Redis can be used as a persistent NoSQL database but as RAM is limited and all my other data is stored in MYSQL, mysql seems a better option.
Is this a correct use case for redis? Is my thinking correct?

A: It depends on the scalability. The number of records you are going to deal with and the structure you are going to use for saving it.
I will discuss about pros and crons of using redis. The decision is up to you.
Advantages of using redis:
    1) It can handle heavy writes and reads in comparison with MYSQL
    2) It has flexible structures (hashmap, sorted set etc) which can
localise your writes instead of blocking the whole table.
    3) Read queries will be much faster as it is served from cache.

Disadvantages of using redis:
    1) Maintaining transactions. What happens if both users try to access a
    particular cell at a time? Do you have a right data structure in redis to
    handle this case?
    2) What if the data is huge? It will exceed the memory limit.
    3) What happens if there is a outage?
    4) If you plan for persistence of redis. Say using RDB or AOF. Will you
    handle those 5-10 seconds of downtime?

Things to be focussed:
1) How much data you are going to deal with? Assume for a table of 10000 rows wit 10 columns in redis takes 1 GB of memory (Just an assumption actual memory will be very much less). If your redis is 10GB cluster then you can handle only 10 such tables. Do a math of about how many rows * column * live tables you are going to work with and the memory it consumes.
2) Redis uses compression for data within a range http://redis.io/topics/memory-optimization. Let us say you decide to save the table with a hashmap, you have two options, for each column you can have a hashmap or for each row you can have a hashmap. Second option will be the optimal one. because storing 1000 (hashmaps -> rows) * 20 (records in each hash map -> columns) will take 10 time less memory than storing in the other way. Also in this way if a cell is changed you can localize in hashmap of within 20 values.
3) Loading the data back in your MYSQL. how often will this going to happen? If your work load is high then MYSQL begins to perform worse for other operations.
4) How are you going to deal with multiple clients on notifying the changes? Will you load the whole table or the part which is changes? Loading the changed part will be the optimal one. In this case, where will you maintain the list of cells which have been altered?
Evaluate your system with these questions and you will find whether it is feasible or not.


text:
Q: Load data from json in tabulator? I have this json variable and want to draw table by tabulator:
mydata=
[
  {
    "trade_symbol": "Media",
    "technical_sum_List": [
      19,
      5,
      4
    ],
    "volume_sum_List": [
      6,
      1
    ],
    "pivot_sum_list": [
      5,
      0,
      0
    ]
  },
  {
    "trade_symbol": "Sport",
    "technical_sum_List": [
      18,
      4,
      4
    ],
    "volume_sum_List": [
      3,
      4
    ],
    "pivot_sum_list": [
      5,
      0,
      0
    ]
  },
  {
    "trade_symbol": "Dance",
    "technical_sum_List": [
      13,
      10,
      5
    ],
    "volume_sum_List": [
      1,
      6
    ],
    "pivot_sum_list": [
      2,
      2,
      0
    ]
  }
]

Now I want to insert technical_sum_List[1] or technical_sum_List[2] in each columns by tabulator.
in tabulator we can only use field:"technical_sum_List" and do not accept technical_sum_List[1]!

A: There might be an easier way but you can do this through using a customFormatter. The gist is that when you define your table columns, you add a formatterParam which tells Tabulator which index in the array to reference and the name of the custom formatter function. Defining a separate function means you can reuse it for all your arrays.
{title:"B-1", field:"technical_sum_List", formatterParams: {index:0}, formatter: customFormatter},

Get the cell value and then use the formatterParams to reference and return the data at that array position.
function customFormatter(cell, formatterParams) {
   return cell.getValue()[formatterParams.index];
}

let myData = [{
  "trade_symbol": "Media",
  "technical_sum_List": [
   19,
   5,
   4
  ],
  "volume_sum_List": [
   6,
   1
  ],
  "pivot_sum_list": [
   5,
   0,
   0
  ]
 },
 {
  "trade_symbol": "Sport",
  "technical_sum_List": [
   18,
   4,
   4
  ],
  "volume_sum_List": [
   3,
   4
  ],
  "pivot_sum_list": [
   5,
   0,
   0
  ]
 },
 {
  "trade_symbol": "Dance",
  "technical_sum_List": [
   13,
   10,
   5
  ],
  "volume_sum_List": [
   1,
   6
  ],
  "pivot_sum_list": [
   2,
   2,
   0
  ]
 }
]

var table = new Tabulator("#example-table", {
    height:"311px",
    columns:[
    {title:"A", field:"trade_symbol"},
    {title:"B-1", field:"technical_sum_List",
    formatterParams: {index:0},
    formatter: customFormatter},

     {title:"B-2", field:"technical_sum_List",
    formatterParams: {index:1},
    formatter: customFormatter},

     {title:"B-3", field:"technical_sum_List",
    formatterParams: {index:2},
    formatter: customFormatter},

    ],
});

function customFormatter(cell, formatterParams) {
   return cell.getValue()[formatterParams.index];
}

table.setData(myData);
<link href="https://unpkg.com/tabulator-tables@4.5.3/dist/css/tabulator.min.css" rel="stylesheet"/>

A: @spring is right, you can only traverse object not arrays for column bindings.
@spring's approach may work, but you would have to be careful as filters and sorting would only see the array not the data.
A better approach would probably to use mutators, which would then make the data accessible to filters and sorters. so we can take @springs code and with a couple of tweaks make it work:
//define mutator
function customMutator(value, data, type, params) {
   return data[params.field][params.index];
}

//assign mutator to columns
var table = new Tabulator("#example-table", {
    height:"311px",
    columns:[
    {title:"A", field:"trade_symbol"},
    {title:"B-1", field:"b1",
    mutatorParams: {index:0, field:"technical_sum_List"},
    mutator: customMutator},

     {title:"B-2", field:"b2",
    mutatorParams: {index:1, field:"technical_sum_List"},
    mutator: customMutator},

     {title:"B-3", field:"b3",
    mutatorParams: {index:2, field:"technical_sum_List"},
    mutator: customMutator},

    ],
});

This approach has several benefits, it means columns can be sorted and filtered and included in downloads.
It also means that now each column has its own unique field, so can be more easily looked-up from outside the table.
in summary formatters are visual only and DO NOT affect sorting and filtering. mutators on the other hand update the underlying data and DO affect sorting, filtering and everything else.
More details of this can be found in the Mutator Documentation

A: Thank you.
I found best answer:
We must use  formatter: customFormatter
        function customFormatter(cell, params) {
           return cell.getValue()[params.myid].rvalue;
        }

        for(var r=0;r<alldata[0].result.length;r++){
            table.addColumn({title:alldata[0].result[r].alias_title ,field:"result", formatterParams: {myid:r}, formatter: customFormatter});
        }


text:
Q: javascript property delete if false nothing if true loop I need to loop through an objects keys and if the property is false then delete the keys property. This is what I have so far but I can't figure out what I am doing wrong.
function onlyTheTruthy() {
 onlyTheTruthy.key;
  var prop;

  for (key in onlyTheTruthy){
    if (key != true) {
     delete onlyTheTruthy.key.prop
    }
  else {
       }

  }
  return onlyTheTruthy;

};

A: In a for...in loop, use the key to access the value on the object. This is done with brackets like obj[key].
function onlyTheTruthy(obj) {

  for (var key in obj) {
    if (!obj[key]) {
      delete obj[key];
    }
  }

  return obj;
}

A: function onlyTheTruthy() {
    onlyTheTruthy.key;
    var prop;
    for (key in onlyTheTruthy) {
        if (key != true) {
            delete onlyTheTruthy.key.prop
        } else {}
    }
    return onlyTheTruthy;
};

This is your code.
Line:

*

*You declare a function named onlyTheTruthy, taking no arguments. However, I think it ought to take one: o.

*This line does nothing. It should be removed.

*You set the scope of the variable prop, but give it no value. Fine.

*A for...in loop. You may want to research exactly what that does. The key variable hasn't been seen before, other than on line 2, but that is a different variable: a property of onlyTheTruthy. Also, you're looping through the keys of the function you're inside of: onlyTheTruthy. I'm confident this isn't what you want. Try:
for (prop in o) {

*Checking if key is not equal to true. Not too often are boolean values used as object keys. Maybe:
if (!o[prop]) { // Or, more verbosely:
if (o[prop] === false) {

*Look up square brackets ([]).

*Empty else. How about no else? It's not required, you know.

*} Closing the for...in loop.

*Returning the function itself. Nope. How about o? Or, if you end up modifying the object itself, there's no need for a return at all.

*No semicolon necessary at the end of a function declaration.

Happy Coding!
Fixed version:
function onlyTheTruthy (o) {
    for (var prop in o) {
        if (!o[prop])
            delete o[prop];
    }
}


text:
Q: Crossfade or buffer a track using Spotify iOS SDK I would like to buffer 5 seconds of the next track so that I can crossfade tracks.

*

*Is it possible using the Spotify iOS SDK? (A similar question has been asked for the older Cocoa Lib Spotify)

*Do I need to make an audio buffer to do this?

*Would somebody be able to point me in the right direction or suggest a class within the SDK reference I should try? (maybe SPTDiskCache?)


text:
Q: Why is radiance measured normal to the beam? Radiance is defined as:
$L=\frac{d \Phi}{\mathop{d \omega} \mathop{d A} \mathop{\cos\theta}}.$
I'm wondering why there is a $\cos \theta$ factor in the denominator of the radiance ($\theta$ is the angle between the normal and the light direction vector). Why would $L=\frac{d \Phi}{\mathop{d \omega} \mathop{d A}}$ be a bad definition of radiance?

A: It is really the dot product between the area and the solid angle - so the radiance "in this direction" that you are looking at. Thus the cosine term.
Expanding...
There is a nice diagram at http://wtlab.iis.u-tokyo.ac.jp/~wataru/lecture/rsgis/rsnote/cp1/1-6-1.gif of which I reproduce part below:

This shows quite clearly that when you are interested in the radiance in a particular direction, the apparent area of the object emitting radiation (area dS in this diagram) will seem to be smaller by $\cos\theta$. You would expect, then, that the flux per unit apparent area is larger, which is where the $\cos$ term comes from.
For a Lambertian source, the flux term $\Phi$ actually has a $\cos\theta$ dependence as well, and the two cosines will in fact cancel out. This is not guaranteed to be true for "any" source which is why the equation you quote makes the $\cos$ term explicit, and leaves it up to you to reflect the actual angular dependence of the source in the numerator term.


text:
Q: How do I tell Hibernate Search to index FetchType.LAZY fields? I have a simple model that looks like this (using Lombok annotations):
@Data
@Entity
@Indexed
public class Game {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;

  @Field(index = Index.YES, store = Store.YES)
  public String name;

  @Column(name="description", columnDefinition="TEXT")
  @Basic(fetch = FetchType.LAZY)
  @Field(index = Index.YES, store = Store.YES)
  public String description;
}

To index this I have written a simple generic indexer that looks like this (this indexes multiple classes hence the lack of a concrete type):
  private int index(Class<?> object, FullTextSession search_session) {
    ScrollableResults results = search_session.createCriteria(object)
                                              .setFetchSize(100)
                                              .scroll(ScrollMode.FORWARD_ONLY);
    int index = 0;
    while(results.next()) {
      index++;
      search_session.index(results.get(0));
      if (index % 10 == 0) {
        search_session.flushToIndexes();
        search_session.clear();
      }
    }
    search_session.flushToIndexes();
    search_session.clear();
    return index;
  }

To invoke this I simple call it like this:
FullTextSession search_session = Search.getFullTextSession(dao);
search_session.setFlushMode(FlushMode.MANUAL);
search_session.setCacheMode(CacheMode.IGNORE);

index(Game.class, search_session);

However while the name field works as expected, the description never gets populated and thus never gets indexed.  If I remove the @Basic(fetch = FetchType.LAZY) annotation from description then the code works as expected.  To work around this I have updated my index function to take a concrete type and now I manually call .getDescription() but is there a cleaner way to accomplish this? Some way to tell Hibernate to fully populate lazy fields on .get()?
In response to karim mohsen's answer I have modified my index() function to look like this (the key difference is that I am calling Hibernate.initialize()):
private <T> int index(Class<T> object, FullTextSession search_session) {
  ScrollableResults results = search_session.createCriteria(object)
                                            .setFetchSize(100)
                                              .scroll(ScrollMode.FORWARD_ONLY);
  int index = 0;
  while(results.next()) {
    index++;
    T item = (T)results.get(0);
    Hibernate.initialize(item);
    search_session.index(item);
    if (index % 10 == 0) {
      search_session.flushToIndexes();
      search_session.clear();
    }
  }
  search_session.flushToIndexes();
  search_session.clear();
  return index;
}

However this approach is still not indexing the description field.

A: If you are lazy-loading a collection normally, but for a particular use, you need to ensure the collection has been loaded before the session is closed, you can use Hibernate.initialize(Object obj)
If you in fact always need the collection loaded, you should indeed load it eagerly


text:
Q: how to track progress and increment count of progress view when dealing with multiple tasks? i need to add circular progress view which shows progress of downloading and other multiple task completion status and want to show 100% completion and hide the progress view when all the task are completed. for Eg.
func downloadAndProcessImages(imagesArray: [URL]){

downloadimages()
resizeImages()
addToDB()

}

func downloadimage(){

for image in imagesArray{

saveImaege()

}

}

func addToDB(){

// db tasks
}

So where to increment the count / progress of the progressview , when you have multiple tasks ?

A: you can use this code in viewWillAppear method:
  DownloadManager.shared.onProgress = { (progress) in
      OperationQueue.main.addOperation {
          self.hud_download.show(in: self.view)
          self.hud_download.detailTextLabel.text = "0%"
           self.hud_download.textLabel.text = "Downloading"
                var progress = Int(round(progress * 100))
                self.hud_download.progress = Float(progress)
                self.hud_download.detailTextLabel.text = "\(progress)%"

                if progress == 100{
                    DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) {
                        UIView.animate(withDuration: 0.1, animations: {
                            self.hud_download.textLabel.text = "Download completed"
                            self.hud_download.detailTextLabel.text = nil
                            self.hud_download.indicatorView = JGProgressHUDSuccessIndicatorView()
                        })
                        self.hud_download.dismiss(afterDelay: 1.0)
     }
}

The hud_download is:
let hud_download = JGProgressHUD(style: .dark)

that you must created in your ViewController
& the DownloadManager class is:
 import Foundation

 class DownloadManager : NSObject, URLSessionDelegate, URLSessionDownloadDelegate {

static var shared = DownloadManager()
var destinationFileUrl : URL? = nil
var file_name = String()
var file_extension = String()

typealias ProgressHandler = (Float) -> ()

var onProgress : ProgressHandler? {
    didSet {
        if onProgress != nil {
            let _ = activate()
        }
    }
}

override private init() {
    super.init()
}

func activate() -> URLSession {
    let config = URLSessionConfiguration.default

    // Warning: If an URLSession still exists from a previous download, it doesn't create a new URLSession object but returns the existing one with the old delegate object attached!
    return URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue())
}

private func calculateProgress(session : URLSession, completionHandler : @escaping (Float) -> ()) {
    session.getTasksWithCompletionHandler { (tasks, uploads, downloads) in
        let progress = downloads.map({ (task) -> Float in
            if task.countOfBytesExpectedToReceive > 0 {
                return Float(task.countOfBytesReceived) / Float(task.countOfBytesExpectedToReceive)
            } else {
                return 0.0
            }
        })
        completionHandler(progress.reduce(0.0, +))
    }
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {

    if totalBytesExpectedToWrite > 0 {
        if let onProgress = onProgress {
            calculateProgress(session: session, completionHandler: onProgress)
        }
        let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
        debugPrint("Progress \(downloadTask) \(progress)")

    }
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    print("Downlaod Finished")
    // download finished.do what you want
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {

    print("Task completed: \(task), error: \(error)")
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
    // unused in this example
}

func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {

    downloadFinished = false
    isRedirected = true
    Functions.functions.resetDefaults()

    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "isRedirected"), object: nil)
}

}
just create the DownloadManager.swift file & paste code.
& use this method for download and every things its gone be okey.
    func dl(file_name : String ,file_extension : String, file_path : String) {
    // for saving in device
    let documentsUrl:URL =  (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL?)!
    DownloadManager.shared.destinationFileUrl = documentsUrl.appendingPathComponent(file_name)
    DownloadManager.shared.file_name = file_name
    DownloadManager.shared.file_extension = file_extension
    let fileURL = URL(string: file_path)
    var request = URLRequest(url:fileURL!)
    // you can set request header by request.allHTTPHeaderFields
    let task = DownloadManager.shared.activate().downloadTask(with: request)
    task.resume()
}

hope to this help you.


text:
Q: Filtering a CSV file to find if a the country is present in a defined list I am trying to pull data out of a spreadsheet and create new csv's for each country and continent.
The country section works well as the countries are already present in the spreadsheet.
However when i try to create a new csv file for each continent i reference a text file with a list of all the countries in said continent.
I am struggling to get the for loop to check whether the country is in a continent. The csv files generate for each continent however they are empty and not written to.
'''
pull data from spreadsheet
'''

import pandas as pd

# Create data
df = pd.read_csv('Copy of KEYWORD LIST_ALL.csv')

# Set index
df = df.set_index('Keyword')

#get list of destinations
destlist = df['Destination'].tolist()

#turn list into set to make it easier to work with
destinations = set(destlist)

continents = ['Asia','Europe','Africa','North America','South America','Oceania']

#loop to create a csv for each destination
for dest in destinations:
    tempdf = df[(df['Destination'] == dest)]
    tempdf.to_csv(dest + ".csv")
    print(tempdf.head())
    #print(dest)

This is the loop I have issues with, I can open the file but in the line
tempdf = df[(df['Destination'] in countries)]

I cannot compare the equality as I have to use a bitwise operator? even though i want to use the 'in' equality check
for cont in continents:
    with open("C:/Users/HarryAdams/PycharmProjects/untitled/" + cont + ".txt") as fileobj:
        countries = fileobj.readlines()
        tempdf = df[(df['Destination']  countries)]
        tempdf.to_csv(cont + ".csv")
        print(tempdf.head())

Sample row of csv:
Keyword,MSV,Rank,Value,Landing Page,Meta,Page,Destination,Destination 2

luxury holidays antigua, 40 , 1 , 8 ,http://www.kuoni.co.uk/antigua/luxury-antigua-holidays,Luxury Antigua Holidays - Kuoni,"Award winning, ATOL protected Antigua luxury holidays. Great range of Antigua all inclusive resorts. Book with Kuoni, receive all inclusive value.",Antigua,Antigua

A: I couldn't test this but it might be worth a try.
Why don't you read in the countries via pandas as well?
And I guess in this case you should use .isin since you are comparing to series.
import pandas as pd

# Create data
df = pd.read_csv('Copy of KEYWORD LIST_ALL.csv')

# Set index
df = df.set_index('Keyword')

for dest, group in df.groupby('destination'):
    group.to_csv(dest + '.csv')

continents = ['Asia','Europe','Africa','North America','South America','Oceania']

directory = "C:/Users/HarryAdams/PycharmProjects/untitled/"

for cont in continents:
    countries = pd.read_table(directory + cont + '.txt')
    df[df.destination.isin(countries[countries.columns[0]])].to_csv(cont + '.csv')


text:
Q: Windows Azure - In-Role Caching, Monitoring I'm attempting to get In-Role Caching up and running.
I'm having difficulty determining if the cache is being used (as we've got a wrapper around it that gracefully returns null if the cache isn't available--but makes it hell to sort out).
I've been going over these articles:
Monitor In-Role Cache
In-Role Cache For Windows Azure
I'd like to use the management console to check on reads/writes or other metrics on the cache as a means of determining if the cache is working properly. But I don't see anywhere to view this data.
The add metric window for the role doesn't include any cache data (though I can see that the cache is configured on the Configure screen).
Any advice? I'm going nuts here.

A: *

*Add diagnostics.wadcfg to your role with cache performance counters you are interested in i.e.
<?xml version="1.0" encoding="utf-8"?>
<DiagnosticMonitorConfiguration configurationChangePollInterval="PT1M" overallQuotaInMB="4096" xmlns="http://schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration">
  <DiagnosticInfrastructureLogs />
  <Directories>
    <CrashDumps container="wad-crash-dumps" />
  </Directories>
  <Logs bufferQuotaInMB="1024" scheduledTransferPeriod="PT1M" scheduledTransferLogLevelFilter="Error" />
  <WindowsEventLog bufferQuotaInMB="1024" scheduledTransferPeriod="PT1M" scheduledTransferLogLevelFilter="Error">
    <DataSource name="Application!*" />
  </WindowsEventLog>
  <PerformanceCounters bufferQuotaInMB="512" scheduledTransferPeriod="PT5M">
    <PerformanceCounterConfiguration counterSpecifier="\Memory\Available MBytes" sampleRate="PT3M" />
    <PerformanceCounterConfiguration counterSpecifier="\Windows Azure Caching:Host\Available Cache Item Percentage" sampleRate="PT3M"/>
    <PerformanceCounterConfiguration counterSpecifier="\Windows Azure Caching:Host\Cache Miss Percentage" sampleRate="PT3M"/>
    <PerformanceCounterConfiguration counterSpecifier="\Windows Azure Caching:Host\Throttled Connections Count" sampleRate="PT3M"/>
    <PerformanceCounterConfiguration counterSpecifier="\Windows Azure Caching:Host\Total Allocated Cache Item Count" sampleRate="PT3M"/>
    <PerformanceCounterConfiguration counterSpecifier="\Windows Azure Caching:Host\Total Cache Misses /sec" sampleRate="PT3M"/>
    <PerformanceCounterConfiguration counterSpecifier="\Windows Azure Caching:Host\Total Client Requests /sec" sampleRate="PT3M"/>
    <PerformanceCounterConfiguration counterSpecifier="\Windows Azure Caching:Host\Total Connections Count" sampleRate="PT3M"/>
    <PerformanceCounterConfiguration counterSpecifier="\Windows Azure Caching:Host\Total Failure Exceptions /sec" sampleRate="PT3M"/>
    <PerformanceCounterConfiguration counterSpecifier="\Windows Azure Caching:Host\Total Get Misses /sec" sampleRate="PT3M"/>
    <PerformanceCounterConfiguration counterSpecifier="\Windows Azure Caching:Host\Total Get Requests /sec" sampleRate="PT3M"/>
    <PerformanceCounterConfiguration counterSpecifier="\Windows Azure Caching:Host\Total GetAndLock Requests /sec" sampleRate="PT3M"/>
    <PerformanceCounterConfiguration counterSpecifier="\Windows Azure Caching:Host\Total Notification Delivered /sec" sampleRate="PT3M"/>
    <PerformanceCounterConfiguration counterSpecifier="\Windows Azure Caching:Host\Total Object Count" sampleRate="PT3M"/>
    <PerformanceCounterConfiguration counterSpecifier="\Windows Azure Caching:Host\Total Objects Returned /sec" sampleRate="PT3M"/>
    <PerformanceCounterConfiguration counterSpecifier="\Windows Azure Caching:Host\Total Read Requests /sec" sampleRate="PT3M"/>
    <PerformanceCounterConfiguration counterSpecifier="\Windows Azure Caching:Host\Total Requests Served /sec" sampleRate="PT3M"/>
    <PerformanceCounterConfiguration counterSpecifier="\Windows Azure Caching:Host\Total Retry Exception /sec" sampleRate="PT3M"/>
    <PerformanceCounterConfiguration counterSpecifier="\Windows Azure Caching:Host\Total Successful GetAndLock Requests /sec" sampleRate="PT3M"/>
    <PerformanceCounterConfiguration counterSpecifier="\Windows Azure Caching:Host\Total Write Operations /sec" sampleRate="PT3M"/>
    <PerformanceCounterConfiguration counterSpecifier="\Windows Azure Caching:Host\Available Cache Item Percentage" sampleRate="PT3M"/>
  </PerformanceCounters>
</DiagnosticMonitorConfiguration>

*Redeploy

*Turn on verbose monitoring level in azure management portal (tab configure)

*Wait an hour or so

*Now your cache performance counters should be available to add under tab monitor (add metrics dialog)

A: I was trying to do the same thing. I've come to the conclusion that the Management Portal does not give you access to the cache performance counters (at lease with Azure SDK 2.0, which I'm using).
The next topic after Monitor, that you were looking at, is In-Role cache troubleshooting. There it suggests you need to add code to your WebRole.cs file, alter diagnostics level etc. I also found a page about Configuring azure Diagnostics which I used to add the various cache performance counters to the deployment package and/or to the running role (using Visual Studio Server Explorer).
At first my cache performance counters such as "\Azure Caching:Host\Total Object Count" didn't log any data. It was only when I remoted onto the instance and ran perfmon.exe that I noticed that the names of the counters were actually of the form: "\Windows Azure Caching:Host\Total Object Count". I notice the Windows bit on the front is never mentioned anywhere in the names of the performance counters! Again, this could be my older SDK.
I now have the in role cache counters turning up in my WADPerformanceCountersTable table within the storage account I specified while configuring the diagnostics.
I hope this helps.


text:
Q: PHP How to create another array from one array I have main array:
$data_cities = Array (

[0] => Array (
    [_type] => _items_city_sorting [item_city_sorting] => Moscow
)
[1] => Array (
    [_type] => _items_city_sorting [item_city_sorting] => Saint-Petersburg
)
[2] => Array (
    [_type] => _items_city_sorting [item_city_sorting] => Sochi
) )

I want to make another array just like:
$cities = array (
[1] => 'Moscow',
[2] => 'Saint-Petersburg',
[3] => 'Sochi' )

The function that I use returns only the last value
  if ( $data_cities ) {
    foreach ( $data_cities as $key => $city ) {
      $cities[ $city->$key+1 ] = $city['item_city_sorting'];
    }
  }

Array ( [1] => Sochi )

What am I doing wrong? Thanks for the help=)
The main array was obtained using Carbon Fields if this is important

A: As you want the number of the key+1 just use this term inside your foreach:
$cities[ $key+1 ] = $city['item_city_sorting'];

A: You can try following inside your foreach:
$cities[] = $city['item_city_sorting'];
 or
array_push($cities,$city['item_city_sorting']);

Add the value dynamically into your city array
For example
if ( $data_cities ) {
 foreach ( $data_cities as $key => $city ) {
  $cities[] = $city['item_city_sorting'];
 }
}


text:
Q: updating the datagridview in form1 with changes in form2 I have done for clicking one the datagridview row cell in one form say form 1 another form say form 2 will open along with selected data grid view data on form1..
I am using winforms...c#
i have done  some operations on  datagrid view data and at the end of the  operations stage the form2 will be closed
    NOTE :upto this i have  finished

i want to update the datagridview in form1 with changes i have done in form2
for that i have done like this..
form 1:
     private void productGridview_Cellclick(object sender, DataGridViewCellEventArgs e)
     {

         if (e.ColumnIndex != productgridview.Columns["productimage"].Index) return;

            if (productgridview.SelectedCells.Count == 0) return;

            int selectedrowindex= productgridview.SelectedCells[0].RowIndex;

            DataGridViewRow selectedRow = productgridview.Rows[selectedrowindex];
              if (img is Image)
               {
                   using (ProductDescriptionForm pf = new ProductDescriptionForm())
                   {

                       pf.picture = img;
                       pf.productname = productname;
                       pf.description = desc;
                       pf.productprice = productprices;
                       pf.categoryname = categoryCombobox.Text;
                       pf.productid = productids;
                       pf.ShowDialog(this);
                   }
               }
      }

and in form2 : I have done like this ...
         public int productid
    {
        get { return _prodid; }
        set { _prodid = value; }

    }
    public Image picture
    {
        get { return pictureBox1.Image; }
        set { pictureBox1.Image = value; }
    }
   like this  some constructors  i have used and then

i  have  deleted one row in datagridview by using below code ...its fine..
      private void btnProdDelete_Click(object sender, EventArgs e)
      {
        using(var context = new TsgEclipseEntities())
        {
              var pd = new product(){ product_Id = productid };
              context.products.Attach(pd);
              context.DeleteObject(pd);
              context.SaveChanges();
              this.Close();   // form2 close
       }

    }

now i want to update the datagridview in form1 how i have  to do that .....
can any one have idea about this ...
many thanks....

A: 1) write a databind method that accepts a product_id parameter to get data in form 1
2) Before form2.close, intialize form 1 class, and call the method by passing the product_id you just updated and open form1.

A: In Form1 create a BindingSource in Form1 use this a the Datasource for the Grid in Form1. Pass the same Binding source to Form2. Use this as the Datasource for your Grid in Form2.
The changes will be seamless.

A: In your Form2 btnProdDelete_Click event before you close the form Set your DialogResult to OK - this.DialogResult = OK;
In your using ProductDescriptionForm pf - after you show the dialog - see if the Result is OK if they hit the X it is cancel,
After ShowDialog you will now be able to access the public property productid
 and  you can do what you want in form 1 with that productid, you need not create an instance of form 1 - it just happens like magic.
A quick easy example of passing data from form2 to form 1


text:
Q: how to bind database field to a drop downs? i'm requesting data from database through a D A L file. I want to data bind and show a drop down menu's single option selected against that of the database. How should i do it?
here's my code:
Pages pg = new Pages();
public static string pgId;

protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            Bind_ddlParentPage();
            Bind_ddlPageModel();
            Bind_ddlArticleModel();
            if (!IsPostBack)
        {
            pgId = Request.QueryString["pageId"];
            if (pgId != null)
            {
                GetData();
            }
        }

         }
   }
public void GetData()
{
        ddlParentPage.SelectedValue = pg.ParentPage;
        //Bind_ddlParentPage();---dropdownlist which is causing problem.
        //I want to set this data:: pg.ParentPage to dropdownlist in another
         page
        ddlPageModel.SelectedValue = pg.PageModel;
        //Bind_ddlPageModel();
        //All the three drop downs have same table for the source,
        'Pages' table and this page is the same page for adding new entry to
        Pages table.

        ddlArticleModel.SelectedValue = pg.ArticleModel;
        //Bind_ddlArticleModel();

}

A: First, you have a duplication in your conditional statement:
if(!IsPostBack) {
...
    if(!IsPostBack) {
    ...
    }
  }

Second, you need to bind the data to the dropdown, then set the selected value. Refer: this post
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            DropDownList1.DataBind(); // get the data into the list you can set it
            DropDownList1.Items.FindByValue("SOMECREDITPROBLEMS").Selected = true;
        }
    }


text:
Q: NSwag - Generate code not compiling because of duplicate property but different types. What does it mean? I get an error on the following code:
    [Newtonsoft.Json.JsonProperty("@id", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
    public string Id { get; set; }

    [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
    public int Id { get; set; }

I do understand the error which is:
"Already contains a definition for id"
But 2 questions,

*

*What does the @ do in the first id(string)

*How to fix it?

This is what was generated by NSwag, I have no access or control of the api which NSwag used to generate the code.


text:
Q: Internal Vrs External Path to Sub-repository I have a repository for an application A which is controlled by mercurial and a library B which is also controlled by mercurial. In the application A's repository it has the sub-repository mapped to library B's repository using the path central repository path ssh://user@1.2.3.4/B. This works well enough for our internal development, but we need access externally, but we can't use the domain name as our router bulks. Is it possible to have the sub-repository defined as something like:
[internal]
B = ssh://user@1.2.3.4/B
[external]
B = ssh://user@domain/B

A: The only method that I was able to find, which sort of works, is to have each developer set the path for the repository. So for the example above, the path for an internal developer would remain unchanged, but the external developers would change their sub-paths to:
ssh://user@1.2.3.4/B = ssh://user@domain/B


text:
Q: Why can some jcmd commands(eg: VM.set_flag) can not be used on all pid? When I want to change the HeapDumpAfterFullGC flag, I use jps  to find the pid of my program.
41123 Jps
5957
41031 Launcher
41032 Main # this is mine

Then I execute jcmd 41032 help
41032:
The following commands are available:
JFR.stop
JFR.start
JFR.dump
JFR.check
VM.native_memory
VM.check_commercial_features
VM.unlock_commercial_features
ManagementAgent.stop
ManagementAgent.start_local
ManagementAgent.start
GC.rotate_log
Thread.print
GC.class_stats
GC.class_histogram
GC.heap_dump
GC.run_finalization
GC.run
VM.uptime
VM.flags
VM.system_properties
VM.command_line
VM.version
help

For more information about a specific command use 'help <command>'.

The VM.set_flags is not listed and jcmd 0 help has:

5957:
The following commands are available:
Compiler.CodeHeap_Analytics
Compiler.codecache
Compiler.codelist
Compiler.directives_add
Compiler.directives_clear
Compiler.directives_print
Compiler.directives_remove
Compiler.queue
GC.class_histogram
GC.class_stats
GC.finalizer_info
GC.heap_dump
GC.heap_info
GC.run
GC.run_finalization
JFR.check
JFR.configure
JFR.dump
JFR.start
JFR.stop
JVMTI.agent_load
JVMTI.data_dump
ManagementAgent.start
ManagementAgent.start_local
ManagementAgent.status
ManagementAgent.stop
Thread.print
VM.class_hierarchy
VM.classloader_stats
VM.classloaders
VM.command_line
VM.dynlibs
VM.flags
VM.info
VM.log
VM.metaspace
VM.native_memory
VM.print_touched_methods
**VM.set_flag**     # this have it
VM.stringtable
VM.symboltable
VM.system_properties
VM.systemdictionary
VM.uptime
VM.version
help

For more information about a specific command use 'help <command>'.
41031:
The following commands are available:
JFR.stop
JFR.start
JFR.dump
JFR.check
VM.native_memory
VM.check_commercial_features
VM.unlock_commercial_features
ManagementAgent.stop
ManagementAgent.start_local
ManagementAgent.start
GC.rotate_log
Thread.print
GC.class_stats
GC.class_histogram
GC.heap_dump
GC.run_finalization
GC.run
VM.uptime
VM.flags
VM.system_properties
VM.command_line
VM.version
help

For more information about a specific command use 'help <command>'.
41032:
The following commands are available:
JFR.stop
JFR.start
JFR.dump
JFR.check
VM.native_memory
VM.check_commercial_features
VM.unlock_commercial_features
ManagementAgent.stop
ManagementAgent.start_local
ManagementAgent.start
GC.rotate_log
Thread.print
GC.class_stats
GC.class_histogram
GC.heap_dump
GC.run_finalization
GC.run
VM.uptime
VM.flags
VM.system_properties
VM.command_line
VM.version
help

For more information about a specific command use 'help <command>'.

I want to know why this happened and how I can use the jcmd to change the flag of JVM.

A: The list of available jcmd commands depends on the version of the target JVM.
VM.set_flag command first appeared in JDK 9.
However, HeapDumpAfterFullGC is a manageable option in JDK 8, too. This means, it is possible to change the flag in runtime, even though it is not listed by jcmd. The easiest way to do this is to use jattach utility:
$ jattach <pid> setflag HeapDumpAfterFullGC 1

Another way to set the flag is JMX: for example, with jconsole.
Find com.sun.management:type=HotSpotDiagnostic MXBean and invoke setVMOption operation:

A: The jcmd command lists the commands the target JVM support.
It depends on the target JVM what commands it does support and implement.
Newer JVMs do support more commands than older JVMs.
For example, on my machine a JDK 8 JVM accepts these commands, about 20:
2237216: (JDK 8 JVM)
The following commands are available:
VM.native_memory
ManagementAgent.stop
ManagementAgent.start_local
ManagementAgent.start
VM.classloader_stats
GC.rotate_log
Thread.print
GC.class_stats
GC.class_histogram
GC.heap_dump
GC.finalizer_info
GC.heap_info
GC.run_finalization
GC.run
VM.uptime
VM.dynlibs
VM.flags
VM.system_properties
VM.command_line
VM.version

And a JDK 14 JVM accepts way more commands, about 46:
2218174:
The following commands are available:
Compiler.CodeHeap_Analytics
Compiler.codecache
Compiler.codelist
Compiler.directives_add
Compiler.directives_clear
Compiler.directives_print
Compiler.directives_remove
Compiler.queue
GC.class_histogram
GC.class_stats
GC.finalizer_info
GC.heap_dump
GC.heap_info
GC.run
GC.run_finalization
JFR.check
JFR.configure
JFR.dump
JFR.start
JFR.stop
JVMTI.agent_load
JVMTI.data_dump
ManagementAgent.start
ManagementAgent.start_local
ManagementAgent.status
ManagementAgent.stop
Thread.print
VM.class_hierarchy
VM.classloader_stats
VM.classloaders
VM.command_line
VM.dynlibs
VM.events
VM.flags
VM.info
VM.log
VM.metaspace
VM.native_memory
VM.print_touched_methods
VM.set_flag
VM.stringtable
VM.symboltable
VM.system_properties
VM.systemdictionary
VM.uptime
VM.version
help

So, in summary. You don't have VM.set_flags, because your running target JVM doesn't support it.
Also, I'm not sure what VM.set_flags will exactly do. As @paulsm4 mentioned, I'm pretty sure changing the 'HeapDumpAfterFullGC' flag after the fact won't change the actual behavior. I would rather search if there is direct flag or JMX option for it.


text:
Q: How to read big file by 100 lines? I have a rather big .txt file (~220Mb) and I need to read it by 100 lines (\n symbol) chunks (for example). How can I do it using php?
Thank you.

A: fopen and fgets. The fgets manual page has an example on reading a file line-by-line without loading it into memory all at once.

A: $fp = open('big_text_file.txt',"r");
if($fp){
    $c = 0;
    $data = array();
    while(!feof($fp)){
        if($c == 100){
            $c = 0;
            // Do whatever it is you want here
            unset($data);
            $data = array();
        }
        $data[] = fgets($fp,4096);
        $c++;
    }
    if($c > 0){
        // Do whatever you need to again
    }
    fclose($fp);
}


text:
Q: VFP font size in command window In the VFP development environment both the command window and any code windows which are open display characters in Courier font, possible 10 pt.  I would like to reduce the size of these characters, to see more lines on the screen.
Have tried going into Tools | Options | IDE and have changed several font specifications (for Desktop, Program files, Code Windows, Procedures), clicked on 'Apply' in an attempt to reduce the size of these character on the screen.  This has not been successful.
How can I reduce the font size used for code when I am editing it, please?

A: Check the Override individual settings checkbox on the Options | IDE tab. Otherwise, if you've previously edited a particular PRG, you'll see the font you used then.
For the Command Window, right-click, Properties to set the font.

A: Most of the time, I use the default, but occasionally I change it by right-clicking within the MODIFY COMMAND window I'm working in, going into "Properties...", and changing the font size.  It only applies when editing that filename, though.  Many years ago I think I tried changing it globally, as you seem to have, and remember it not 'sticking', so henceforth I always changed it on a file-by-file basis when I needed to.

A: I think what you are looking for is under Tools / Options / EDITOR tab, and save whatever defaults you want and set as Default.
Additionally, another thing I have done this in the past and created my own master settings resource file.  By default when you start VFP, a "resource" file is set to ex: C:\Program Files\VFP\blah\FoxUser.dbf  (and the corresponding .fpt file)
What I would do is this.  Use the resource file and make an EMPTY copy of it to a new location, such as the working folder of your project.
use ( sys(2005)) again alias tmpResource
copy structure to MyVFPResource
set resource to MyVFPResource
close tables all

The resource file keeps track of almost every thing you open / work with and retains settings such as window area, position, etc.  Some things I like to have as a "default", such as when editing snippet methods in screen or class designer.  Such as to always have the row/column of a file displayed, have other settings.
An example of common .prg files.  Do a simple MODI COMM MyTest.prg.  Then once a simple .prg file is open, go to Edit, then Properties.  Click on all the settings you want (including font size, line/column, syntax coloring, tabs vs space preferences, etc.  Click the checkbox for "Apply to .PRG files". and click ok.
Now, open your resource file AGAIN so you can see what is stored.
use ( sys(2005)) again alias tmpResource
BROWSE

You will see many rows, but at the bottom will be the most recent entries.  You should see 3 records listed as "WINDMODIFY" which represents the "MODIFY COMMAND" of whatever prg file.  Now, open the "Name" memo field.  One will be listed as .prg, another will be "DEFAULT", and the last will be the actual "mytest.prg" you started with.  Get on the "DEFAULT" version record.  Now you can change the "READONLY" column from FALSE to TRUE (F/T) and it will lock these settings for ALL .prg files.  You can then delete the other rows.
You can apply these same principles to modifying form code snippets.  Open a form, double-click on any method, then EDIT / Properties, do the same, but checkbox for "Apply to method code".
Browse the resource file and look at the "WINDSNIP" rows.  Again, look for "DEFAULT" and mark that readonly as .T. and you can delete the other.  The resource file will literally save every snippet window specific to the form, object, method, etc.
Do the same for visual class file editing too.
Similarly can be done for toolbars and more as you browse and see.  When you are done making all the changes you want, purge out all the other fluff, close the resource file and set it to read-only so no additional garbage gets pulled into it.
If you need to change in the future, make the table editable again, make changes, then readonly the table again.
Then, all you have to do is at VFP start, do
set resource to MyVFPResource


text:
Q: How to search for multiple strings in very large database I want to search for multiple strings in a very large database. These strings are part of different attributes of database table. I have tried string search using LIKE in sql query. But it is taking a lot of time to get results. I have used Oracle database.
Should I use indexing of database? I found that Lucene can be used for it.
I also got some suggestions of using big data concepts. Which approach should I use?

A: The easiest way is:
1.) adding an index to the columns you like to search trough
2.) using oracle text as @lalitKumarB wrote
The most powerful way is:
3.) use an separate search engine (solr, elaticsearch).
But, probably you have to change you application in order to explicit use the search index for searching trough the data,...
I had the same situation some years before. Trying to search text in an big database. After a wile I found out, that database based search will never reach the performance of an dedicate search engine. And: you will have much more search features working out of the box, if you use solr (for example), like spelling correction, "More like this", ...
One option is to hold the data on orcale, searching in solr and return the ID of the document in order to only load the one row form oracle, the is referenced by the ID.
2nd option is to keep oracle as base datapool for your search engine and search in solr (or elasticsearch) in order to return the whole document/row from solr, not only the ID. So you don't need to load the data from the database any more.
The best option depends on your needs.

A: You have the choice between elasticsearch, solr or lucene


text:
Q: How can we call custom hooks? Linter gives me an error saying that I should not call a custom hook in useCallback.
How can I fix this issue?
I just want to call a custom hook that makes a POST to the Web API.
I just want to execute a Submit called from a child comport.
The custom hook needs 3 arguments.
The limitation is that the values used in the arguments are available via the Web API, so I need a little time to get them.

const ParentComponent: FC = () => {

・・・・
・・・・

  const [isLoading, setIsLoading] = React.useState(false);

  const handleSubmit = React.useCallback(async () => {
    setIsLoading(true);

    if (!param1 || !param2 || !param3) {
      setIsLoading(false);
      return;
    }

    try {
      const response = await useCustomHookSample(
        param1,
        param2,
        param3,
      );
      setIsLoading(false);
      //do something
    } catch (error) {
      setIsLoading(false);
      //handle error
    }
  }, [param1, param2, param3,]);

・・・・
・・・・

  return (
    <>
      <ChildrenComponent
        handleSubmit={handleSubmit}
      />
    </>
  );

}

A: Check out the Rules of Hooks. The first rule is they must be called at the top-level of your component function.
For a hook to work, in your situation you'd define it at the top:
const ParentComponent: FC = () => {
  const doHookCallback = await useCustomHookSample();

  const someAsyncEvent = async () => {
    const results = await doHookCallback(param1, param2, param3);
    // ...
  };

  //...

Although, this clearly would require a refactor of your hook which is incorrectly firing it's POST when simply instantiated. The hook should return a callback function when instantiated which then lets you run the API request when needed.
Or just avoid the whole mess entirely and just use fetch hooks via use-http or Axios hooks via use-axios (which requires Axios).


text:
Q: Find how many numbers
How many numbers consist of $4$ digits $a$, $b$, $c$, and $d$ such
  that
$$a\leq b\leq c\leq d$$

a is thousands, b is hundreds, c is tens, and d is unit
What i'm thinking is $6 \times6\times 6\times 6$, but it's wrong.
The multiple choice is :
a) $495$ numbers
b) $385$ numbers
c) $275$ numbers
d) $165$ numbers
e) $55$ numbers
Which one is the answer?

A: Consider the following table.
$$\begin{array}{|c|c|c|c|c|}\hline 9&9&9&9&\color{blue}9\\\hline 8&8&8&8&8\\\hline 7&7&7&7&7\\\hline 6&6&6&6&6\\\hline 5&5&5&5&5\\\hline4 &4&4&4&4\\\hline 3&3&3&3&3\\\hline 2&2&2&2&2\\\hline 1&1&1&1&1\\\hline \color{red}0&0&0&0&0 \\\hline\end{array}$$
We start at the square with the red zero and we want to get to the square with the blue nine.  At each step, we can only walk one step to the right or one step in the upwards direction.  Let $a$, $b$, $c$, and $d$ be the labels of the last squares we stay in the first column, the second column, the third column, and the forth column respectively.
If $R$ denotes a step that we walk to the right and $U$ denotes a step that we walk upwards, then we can identify our walk with a sequence of $4$ $R$s and $9$ $U$s.  For example, $RUUURRUUUURUU$ gives $(a,b,c,d)=(0,3,3,7)$.  Likewise, $UURURUUUUURUR$ gives $(a,b,c,d)=(2,3,8,9)$.
If $a$ is allowed to be $0$, the first step can be anything.  Therefore, the job can be done in
$$\frac{(4+9)!}{4!9!}=\frac{13\cdot 12\cdot 11\cdot 10}{4\cdot 3\cdot 2\cdot 1}=715$$ ways.  If $a$ cannot be $0$, then the first step must be $U$.  Therefore, the job can be done in
$$\frac{(4+8)!}{4!8!}=\frac{12\cdot 11\cdot 10\cdot 9}{4\cdot 3\cdot 2\cdot 1}=495$$
ways.


text:
Q: How to import external modules in a Python package? For example, module m in my package p uses re. I write import re in m.py. Some other module n also uses re. Do I write import re twice or include import re once in my __init__.py?
What's the convention for writing packages that include external modules?

A: Import re in each script (m and n). Then the scripts can be relocated to another package (if e.g. you refactor your code), and it is clearer from within the file what re is / where it is coming from etc.

A: Import a module in every other module that uses it.
Python is intelligent about how that happens under the covers.  You can easily get into a Python form of DLL hell if you rely on indirect imports of modules.  Fortunately the indirect approaches are harder than the direct approaches :) so most people do the right thing somewhat naturally.