text:
Q: How to fix 'No rule to make target `project-name'. Stop.' I'm trying to build my qt project after macOS 10.15 Catalina update. Always get en error:
:-1: error: No rule to make target 'AircraftAlgorithmPack'.  Stop.
And recommendations:
make: *** No rule to make target 'AircraftAlgorithmPack'.  Stop.
The platform SDK has been changed from version 10.14 to version 10.15.
This requires a fresh build. Please wipe the build directory completely,
including any .qmake.stash and .qmake.cache files generated by qmake.
/Users/arseniyspiridonov/Qt/5.13.1/clang_64/mkspecs/features/mac/sdk.mk:22: *** ^.  Stop.
19:01:49: The process "/usr/bin/make" exited with code 2.
Error while building/deploying project AircraftAlgorithmPack (kit: Desktop Qt 5.13.1 clang 64bit)
When executing step "qmake"

I've already checked that my SDK version is 10.15.
I've tried to clean project, to delete build directory, to rerun qmake,  to make context change in make file (from 10.14 to 10.15), to write some mantras not to check SDK version. All advices from google.
Nothing happens.

A: Make sure to erase all .qmake.stash files - they might also be located in your project's folder. Completely delete your build directory. The .qmake.stash files are hidden from Finder, so you might need to use the command shell to locate them.


text:
Q: Can Javascript access the DOM of an Ajax text/html response? I'm trying to use Ajax to fetch an HTML page and then pull out a div by it's ID, and insert that DIV into the current page. So the current page loads (via Ajax) a second page, pulls the div out of the Ajax response and inserts into the current page. However I am at a loss as unless the response is text/xml, I cannot use any DOM functions on it... can I?

A: Jquery (or other libraries??) will basically do all this for you. I highly recommend looking into this and not reinventing the wheel.
For query it would probably like:
// Make a call to url, with data
$.ajax(
  { url: $url,
    data: $data,
    dataType: 'xml',
    callback: function(returnData) {
      // Jquery find <mytag attribute="foo">...</mytag> and store it in mydata
      var mydata = $(returnData).find('mytag[attribute=foo]');
      // Insert into current page to somewhere with class="after-me"
      $('.after-me').html(mydata);
   }
});

I may have the syntax wrong. But here is the docs: http://docs.jquery.com/Ajax/jQuery.ajax#options

A: Yes you can.  Here you will find a resource for how to parse XML responses.
If you are loading it into the DOM tree that already exists (innerHTML), you should be able to call the standard DOM traversal functions you are used to.

A: Don't worry about validity, since you are doing this dynamically using javascript, you can fill hidden element's innerHTML with your response data and then use any DOM/jQuery functions you wish

A: script tags will fail on any browser by any method.. so to access current page's dom apply the "eval" function on the script text which you currently requested.
i mean, if you have html like:

some html

and you got the script text on server side like
content.innerHTML = "foo";

use the eval function on ajax response
function onXmlHttpAnswer()
{
   if(xmlHttp.readyState==4 && xmlHttp.status==200)eval(xmlHttp.responseText);
}

A: In order to use jQuery to extract only a portion of an HTML document loaded via $.load() do this:
$('#dynamic').load('content.html #desiredElement');

.load will actually load the entire document, but the selector will force load to only return the selected portion of that document.

A: Try this out. This worked for me.
$.ajax({
    url: 'http://www.example.com',
    type: "GET",
    crossDomain: true,
    dataType: 'html',
    success: function (responseHTMLData) {
        $($(responseHTMLData).find('.yourClassName')).each(function() {
            console.log($(this).attr('href'));
        });
    }
});

A: $.ajax({
  type: "POST",
  url : "yourURL"
  data : $("#yourFormID").serialize(),
  async: true,
  success : function(resp) {
    // resp contains data in html form you want to find data in
    // some Error
    var errorData = $(resp).find('span.error').text();
    // errorData would have value "some Error"
  }
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: using $.ajax in kendoui datasource of Grid I'm trying to use jquery ajax call for datasource update in my kendoui Grid.
The sample of code (getting from docs):

update: function(options) {
      // make JSONP request to http://demos.telerik.com/kendo-ui/service/products/update
      jQuery.ajax({
        url: AjaxSave,
        dataType: "json", // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
        success: function(result) {
          options.success(result);
        },
        error: function(result) {
          options.error(result);
        }
      });
    }

But I'm getting the following error after Update clicking:
Error: Only json dataType can be used for update operation.

...o](n,e[o]):n[o]=e[o]}else{if("json"!==l)throw Error("Only json
dataType can be u...

What I'm doing wrong?

A: Syntactically, it appears correct. I've known this to occur at one point when there was incompatibility between the installed jQuery version and the Kendo version used.
You may want to cross check your jQuery/Kendo version compatibility, and update/rollback if necessary.


text:
Q: Two random numbers sticking together I'm trying to write a function that changes 3 coordinates and 3 velocities in a loop using random numbers.
Although he generated numbers seem random enough. The two last values never drift apart, while the first one does go its own way.
This is the function, I will also link the excel workbook, so you can see it in action
(it's a animated colorbox using RGB and sliders for the values. Just run the 'color' sub
Function variate(ByRef x_origin As Double, ByRef y_origin As Double, ByRef offset_x As Double, ByRef offset_y As Double, Optional ByRef z_origin As Double, Optional ByRef offset_z As Double, Optional xyz_bounds) As Variant
'this function adds random number to each of the origins
'the offset is the 'drift' the object has (or velocity)
'calculate a random number
'if the number is going in the same direction, speed up
'otherwise slow down
Dim new_origin_x As Double
Dim new_origin_y As Double
Dim new_origin_z As Double
Dim velocity_x As Double
Dim velocity_y As Double
Dim velocity_z As Double
Dim speed_x As Double
Dim speed_y As Double
Dim speed_z As Double
Dim random_number_x As Double
Dim random_number_y As Double
Dim random_number_z As Double
Dim random_speed_x As Double
Dim random_speed_y As Double
Dim random_speed_z As Double
'calculate a random with the seed and make it between -0.5 and 0.5
    Randomize
    random_number_x = Rnd(Range("x_fact").Value) - 0.5
    Randomize
    random_number_y = Rnd(Range("y_fact").Value) - 0.5
    Randomize
    random_number_z = Rnd(Range("z_fact").Value) - 0.5
    'for the speed
    Randomize
    random_speed_x = Rnd(1) - 0.5
    Randomize
    random_speed_y = Rnd(1) - 0.5
    Randomize
    random_speed_z = Rnd(1) - 0.5
'see how much there is a speed up
'what point would we be at with the current speed
'that is the distance travelled in time, but the time is 1 'unit' ...
'and let's add some randohohomnessss
    speed_x = offset_x + (random_speed_x / Range("x_rem").Value)
    speed_y = offset_y + (random_speed_y / Range("y_rem").Value)
    speed_z = offset_z + (random_speed_z / Range("z_rem").Value)
 'so new origin is new_origin_x = x_origin + offset_x
 'but than we've travelled at the same speed, with directional changes
 'we're probably not even moving
 'so add some randomness to act as 'live'
    new_origin_x = x_origin + offset_x + (random_number_x / Range("x_fact").Value)
    new_origin_y = y_origin + offset_y + (random_number_y / Range("y_fact").Value)
    new_origin_z = y_origin + offset_z + (random_number_z / Range("z_fact").Value)
'variate = [{new_origin_x;new_origin_y};{speed_x;speed_y}]
'variate = [{new_origin_x;new_origin_z};{speed_x;speed_z}]
'see if boundaries are requested and if so, not met
'should be: going to meet at the current speed
 If Not IsMissing(xyz_bounds) Then
   Dim distant_from_bounds_x
   Dim distant_from_bounds_y
   Dim distant_from_bounds_z
   Dim future_pos_x
   Dim previous_dist_x
   Dim previous_dist_y
   Dim previous_dist_z
   future_pos_x = new_origin_x + 3 * speed_x
   Dim future_pos_y
   future_pos_y = new_origin_y + 3 * speed_y
   Dim future_pos_z
   future_pos_z = new_origin_z + 3 * speed_z
   distant_from_bounds_x = xyz_bounds / 2 - Abs(future_pos_x - xyz_bounds / 2)
   distant_from_bounds_y = xyz_bounds / 2 - Abs(future_pos_y - xyz_bounds / 2)
   distant_from_bounds_z = xyz_bounds / 2 - Abs(future_pos_z - xyz_bounds / 2)
   previous_dist_x = xyz_bounds / 2 - Abs((x_origin + 3 * speed_x) - xyz_bounds / 2)
   previous_dist_y = xyz_bounds / 2 - Abs((y_origin + 3 * speed_y) - xyz_bounds / 2)
   previous_dist_z = xyz_bounds / 2 - Abs((z_origin + 3 * speed_z) - xyz_bounds / 2)
   'slow down
   If (distant_from_bounds_x < 10) And (distant_from_bounds_x - previous_dist_x < 0) Then
        speed_x = speed_x - speed_x / 3
        If Abs(speed_x) < 1.5 Then speed_x = -speed_x * 2.9
   End If
   If distant_from_bounds_y < 10 And (distant_from_bounds_y - previous_dist_y < 0) Then
        speed_y = speed_y - speed_y / 3
        If Abs(speed_y) < 1.5 Then speed_y = -speed_y * 2.9
   End If
   If distant_from_bounds_z < 10 And (distant_from_bounds_z - previous_dist_z < 0) Then
        speed_z = speed_z - speed_z / 3
       If Abs(speed_z) < 1.5 Then speed_z = -speed_z * 2.9
    End If
    'speedlimits
    If Abs(speed_x) > 9 Then speed_x = speed_x - Abs(speed_x / 4)
    If Abs(speed_y) > 9 Then speed_y = speed_y - Abs(speed_y / 4)
    If Abs(speed_z) > 9 Then speed_z = speed_z - Abs(speed_z / 4)
 End If
'return the values and the new velocity to add some more stuff

x_origin = new_origin_x
y_origin = new_origin_y
z_origin = new_origin_z
offset_x = speed_x
offset_y = speed_y
offset_z = speed_z

End Function

Any suggestions would be greatly appreciated !

A: If you can excuse my abrasiveness, you are misusing the generator:
1) At the beginning of your function, include the line
  Rnd(-1)

That is how you seed the generator.
2) Remove all your Randomize calls as they are ruining the statistical properties of the generator. I think that is the cause of your problems. You can have one Randomize call directly after Rnd(-1) above, but I think it's nice to have the same sequence generated for tractability.
3) There is no need to have a parameter in your Rnd() calls (other than the first step), as the default behaviour is to return a number in the range [0, 1). In fact this could be causing your problems, since a negative parameter value re-seeds the generator!
4) Investigate the effects of doing the above. But be aware that the VBA random sequence is a linear congruential generator of the form next = ((c * prev) mod b) + a where a, b and c are constants, prev is the previous random number and next the generated one. (As a final flourish, the integer values next and prev are scaled to floating point numbers). You can see that there is possible autocorrelation in the sequence since when prev is small, the modulus will have no effect. You can but hope that the engineers at Microsoft have assigned a large value to c to circumvent this effect. This autocorrelation can cause "sticking" when using random numbers in a multidimensional situation.
(4) could therefore be causing your problem, and if it is, you need to switch to another generator. Let me know and we can make some suggestions on that front.


text:
Q: ${BASH_SOURCE[1]} equivalent in zsh? I am trying to get the directory of the sourced script, and an important requirement is that sourcing can be nested, and the deepest script is sourced with something like source <(cat file), so the directory should be taken for the second deepest file, which is easy to do in Bash with ${BASH_SOURCE[1]}. Any idea how to do the same in Zsh?
UPDATE:
(From my comment below) The difference between ${BASH_SOURCE[0]} and ${BASH_SOURCE[1]} matters a lot in this case, because the script is sourced with <(...), and ${BASH_SOURCE[0]} doesn't point to a real file, but to a temporary file descriptor instead, which is why I need to get the second deepest file in the source chain.

A: You can use the funcfiletrace parameter defined by the zsh/parameter module.

funcfiletrace
This array contains the absolute line numbers and corresponding file names for the point where the current function, sourced file, or (if EVAL_LINENO is set) eval command was called.
The array is of the same length as funcsourcetrace and functrace, but differs from funcsourcetrace in that the line and file are the point of call, not the point of definition, and differs from functrace in that all values are absolute line numbers in files, rather than relative to the start of a function, if any.

Use the last element of this array.
Example
Consider the following files structure:
foo
└── bar
    ├── baz
    │   └── baz.zsh
    └── foo.zsh

and files content:
foo.zsh
file="$(print -P ${(%):-%x})"
dir="${file:h}"

echo "foo file: $file"
echo "foo directory: $dir"

source <(cat "$dir/baz/baz.zsh")

baz.zsh
zmodload zsh/parameter

file="$funcfiletrace[$#funcfiletrace]"
dir="${file:h}"

echo "foo file from bar: $file"
echo "foo directory from bar: $dir"

Result
% zsh foo/bar/foo.zsh
foo file: foo/bar/foo.zsh
foo directory: foo/bar
foo file from bar: foo/bar/foo.zsh:7
foo directory from bar: foo/bar


text:
Q: Set baremetal server maximum port speed execption Follow the answer
How to set 10G and 20G network interface speeds on SoftLayer
How to set 10G and 20G network interface speeds on SoftLayer
to set maximum speed for baremetal server with following code:
var sess = session.New(userName, apiKey, endpoint)

order := datatypes.Container_Product_Order{
    ComplexType: sl.String("SoftLayer_Container_Product_Order_Hardware_Server_Upgrade"),
    Hardware: []datatypes.Hardware{
        {
            Id : sl.Int(SERVER_ID),
        },
    },
    Prices: []datatypes.Product_Item_Price{
        {Id : sl.Int(35666)},  // Port maximum speed to "1 Gbps Dual Public & Private Network Uplinks (Unbonded)""
    },
    Properties: []datatypes.Container_Product_Order_Property {
        {
            Name: sl.String("MAINTENANCE_WINDOW"),
            Value: sl.String("2018-08-21T14:00:00+08:00"),
        },
        {
            Name: sl.String("orderOrigin"),
            Value: sl.String("control"),
        },
        {
            Name: sl.String("MAINTENANCE_WINDOW_ID"),
            Value: sl.String("189467"),
        },
    },
}

service := services.GetProductOrderService(sess)
resp, err := service.VerifyOrder(&order)
if err != nil{
    fmt.Println(err)
}else{
    fmt.Printf("Set speed status: %v \n",resp)
}

The price ID was got from HardwareServerService.GetUpgradeItemPrices().
The VerifyOrder function return error:

SoftLayer_Exception_Order_InvalidContainer: Invalid container specified: SoftLayer_Container_Product_Order. Ordering a server or service requires a specific container type, not the generic base order container. (HTTP 500)

What's wrong in the Container_Product_Order object?

A: If you add sess.Debug := true after creation of the session you will be able to retrieve logs from go-client, on this case the client is sending SoftLayer_Container_Product_Order instead of SoftLayer_Container_Product_Order_Hardware_Server_Upgrade:
2018/08/21 18:44:50 [DEBUG] Request URL:  POST https://api.service.softlayer.com/rest/v3/SoftLayer_Product_Order/verifyOrder.json
2018/08/21 18:44:50 [DEBUG] Parameters:  {"parameters":[{"complexType":"SoftLayer_Container_Product_Order","hardware":[{"id":11112222333}],"prices":[{"id":35666}],"properties":[{"name":"MAINTENANCE_WINDOW","value":"2018-08-21T14:00:00+08:00"},{"name":"orderOrigin","value":"control"},{"name":"MAINTENANCE_WINDOW_ID","value":"189467"}]}]}

So I recommend to modify the order skeleton in order to upgrade the baremetal, try with the following:
order := datatypes.Container_Product_Order_Hardware_Server_Upgrade{
        Container_Product_Order_Hardware_Server: datatypes.Container_Product_Order_Hardware_Server{
            Container_Product_Order: datatypes.Container_Product_Order{
                Hardware: []datatypes.Hardware{
                    {
                        Id: sl.Int(SERVER_ID),
                    },
                },
                Prices: []datatypes.Product_Item_Price{
                    {Id: sl.Int(35666)}, // Port maximum speed to "1 Gbps Dual Public & Private Network Uplinks (Unbonded)""
                },
                Properties: []datatypes.Container_Product_Order_Property{
                    {
                        Name:  sl.String("MAINTENANCE_WINDOW"),
                        Value: sl.String("2018-08-21T14:00:00+08:00"),
                    },
                    {
                        Name:  sl.String("orderOrigin"),
                        Value: sl.String("control"),
                    },
                    {
                        Name:  sl.String("MAINTENANCE_WINDOW_ID"),
                        Value: sl.String("189467"),
                    },
                },
            },
        },
    }


text:
Q: Scraping a table using the rvest package I'm totally new to web scraping and I'm exploring the potentialities of the rvest library in R.
I'm trying to scrape a table on wellbeing in Italian provinces from the following website,
install.packages('rvest')

library('rvest')

url <- 'http://www.ilsole24ore.com/speciali/qvita_2017_dati/home.shtml'

webpage <- read_html(url)

but I'm unable to identify the XPath of the table.

A: Even with the following, you have quite a bit of work to do. The HTML is in terrible shape.
library(rvest)
library(stringi)
library(tidyverse)

read_html("http://www.ilsole24ore.com/speciali/qvita_2017_dati/home.shtml") %>%  # get the main site
  html_node(xpath=".//script[contains(., 'goToDefaultPage')]") %>%               # find the <script> block that dynamically loads the page
  html_text() %>%
  stri_match_first_regex("goToDefaultPage\\('(.*)'\\)") %>%                      # extract the page link
  .[,2] %>%
  sprintf("http://www.ilsole24ore.com/speciali/qvita_2017_dati/%s", .) %>%       # prepend the URL prefix
  read_html() -> actual_page                                                     # get the dynamic page

tab <- html_nodes(actual_page, xpath=".//table")[[2]]                            # find the actual data table

Once you do ^^ you have an HTML <table>. It's in terrible, awful, pathetic shape and that site shld rly be ashamed of how it abuses HTML.
Go ahead and try html_table(). It's so bad it breaks httr.
We need to attack it by row and will need a helper function soas to not have the R code look horrible:
`%|0%` <- function(x, y) { if (length(x) == 0) y else x }

^^ will help us fill in NULL-like content with a blank "".
Now, we go row-by-row, extracting the <td> values we need. This does not get all of them since I don't need this data and it needs cleaning as we'll see in a bit;
html_nodes(tab, "tr") %>%
  map_df(~{
    list(
      posizione = html_text(html_nodes(.x, xpath=".//td[2]"), trim=TRUE) %|0% "",
      diff_pos = html_text(html_nodes(.x, xpath=".//td[5]"), trim=TRUE) %|0% "",
      provincia = html_text(html_nodes(.x, xpath=".//td[8]"), trim=TRUE) %|0% "",
      punti = html_text(html_nodes(.x, xpath=".//td[11]"), trim=TRUE) %|0% "",
      box1 = html_text(html_nodes(.x, xpath=".//td[14]"), trim=TRUE) %|0% "",
      box2 = html_text(html_nodes(.x, xpath=".//td[17]"), trim=TRUE) %|0% "",
      box3 = html_text(html_nodes(.x, xpath=".//td[20]"), trim=TRUE) %|0% ""
    )
  })
## # A tibble: 113 x 7
##     posizione             diff_pos            provincia                 punti  box1  box2  box3
##         <chr>                <chr>                <chr>                 <chr> <chr> <chr> <chr>
##  1            Lavoro e Innovazione                      Giustizia e Sicurezza
##  2 Diff. pos.
##  3          1                    3              Belluno                   583
##  4          2                   -1                Aosta                   578     9    63    22
##  5          3                    2              Sondrio                   574     4    75     1
##  6          4                    3              Bolzano                   572     2     4     7
##  7          5                   -2               Trento                   567     8    11    15
##  8          6                    4              Trieste                   563     6    10     2
##  9          7                    9 Verbano-Cusio-Ossola                   548    18    73    25
## 10          8                   -6               Milano                   544     1     2    10
## # ... with 103 more rows

As you can see, it misses some things and has some junk in the header, but you're further along than you were before.


text:
Q: What is wrong with my attempts to mock a simple C++ method with googlemock? As per Patterns for unit testing a C++ method that makes a standard library call, I'm test-driving development of a network-abstracting class. In order to unit test code that makes standard C library calls (which I can't mock) to handle BSD sockets, I've defined an interface ISocket from which both my real implementation CSocket and mock MockSocket inherit.
Now I write my first unit test for the Network class, which uses an ISocket for the heavy lifting:
#include "gmock/gmock.h"
#include "gtest/gtest.h"
// C standard library includes omitted
#include "MockSocket.h"
#include "Network.h"

using ::testing::Return;
namespace JrStream {
  class NetworkTest : public ::testing::Test {
  protected:
    Network net;
    ISocket * socket_ptr;

    virtual void SetUp() {
      socket_ptr = new MockSocket();
    }
  };

  TEST_F(NetworkTest, InitCallsSocket) {
    EXPECT_CALL((MockSocket)*socket_ptr, Socket(AF_INET, SOCK_STREAM, 0))
        .Times(1)
        .WillOnce(Return(5)); //fake file descriptor

    ASSERT_TRUE(net.init(socket_ptr));
  }
} // namespace
// gtest boilerplate main() omitted

But I get this error on compilation:
g++ -g -Wall -Lgtest-1.5.0/lib -Igmock-1.5.0/include -Igtest-1.5.0/include -I.. -I../../Debug/src -c -o NetworkTest.o NetworkTest.cc
NetworkTest.cc: In member function 'virtual void JrStream::NetworkTest_InitCallsSocket_Test::TestBody()':
NetworkTest.cc:35: error: no matching function for call to 'JrStream::MockSocket::MockSocket(JrStream::ISocket&)'
MockSocket.h:16: note: candidates are: JrStream::MockSocket::MockSocket()
MockSocket.h:16: note:                 JrStream::MockSocket::MockSocket(const JrStream::MockSocket&)

And here is what my interface and mock look like:
namespace JrStream {
  class ISocket {
    virtual int Socket(int domain, int type, int protocol) = 0;
  };
}

#include "gmock/gmock.h"
#include "ISocket.h"
namespace JrStream {
  class MockSocket: public JrStream::ISocket {
    MOCK_METHOD3(Socket, int(int domain, int type, int protocol));
  };
}

Any ideas what I'm doing wrong here?

A: Looks like you're invoking the copy constructor for MockSocket  somewhere in TestBody without a cast.

A: I finally got it sorted. What was tripping me up is that I wanted to use a pointer, but googlemock works with classes. Here's what works:
#include "gmock/gmock.h"
#include "gtest/gtest.h"
// C standard library includes omitted
#include "MockSocket.h"
#include "Network.h"

using ::testing::Return;
namespace JrStream {
  class NetworkTest : public ::testing::Test {
  protected:
    Network net;
    MockSocket sock;
  };

  TEST_F(NetworkTest, InitCallsSocket) {
    EXPECT_CALL(sock, Socket(AF_INET, SOCK_STREAM, 0))
        .Times(1)
        .WillOnce(Return(5)); //fake file descriptor

    ASSERT_TRUE(net.init(&sock));
  }
} // namespace
// gtest boilerplate main() omitted

This is well and good, but I wonder how to make this work if I really needed my pointers. Sounds like an exercise for the reader. ;)

A: How about:
TEST_F(NetworkTest, InitCallsSocket) {
EXPECT_CALL(*((MockSocket)*socket_ptr), Socket(AF_INET, SOCK_STREAM, 0))
    .Times(1)
    .WillOnce(Return(5)); //fake file descriptor

ASSERT_TRUE(net.init(socket_ptr));

}
(Disclaimer - I did not check if it compiles...)


text:
Q: Can we use TFS 2013 Release Management for SharePoint 2013 projects? Can we use TFS 2013 Release Management for SharePoint 2013 projects? I have googled on these lines and couldn't find any links. I have not worked with Release Management, so no idea if that handles SharePoint deployments as well. Do we have any ready made deployment tools for SharePoint? If we have, do they integrate with TFS ? If Release Management supports SP deployments also,has any team used it in real time or at least for evaluation? Our team is planning to use RM for SP deployments. So any ideas will be of great help for us.

A: It really depends on what solution do you build (farm solutions or SharePoint apps) and what is your staging or testing environment (SharePoint on-premises or O365). Here is some link that could help:

*

*SharePoint 2013 Continues Integration with TFS 2013 Release and Build Management

*ALM for SharePoint Apps: Configuring a TFS Build Server with Team Foundation Service

*SP2010 Continuous Integration. A bit old but very interesting.


text:
Q: Adding HTML string to DOMDocument in PHP I have a DOMDocument object and I want to manipulate text nodes and return them to the object as a HTML string. For example:
$dom=new DomDocument();
$dom->loadHTML('This is [b]BBC[/b]');

// $node is a text node
$html=parseBBC($node->nodeValue);
$frag=$dom->createDocumentFragment();
$frag->appendXML($html);
$node->parentNode->replaceChild($frag,$node);

echo $dom->saveHTML();

Expected output:
This is BBC

Actual output:
empty string

Edit:
$dom=new DomDocument();
$dom->loadHTML('This is[br]BBC');
$xpath=new DOMXPath($dom);

$r=$xpath->query('//text()');
foreach($r as $el){
  $str=trim(str_replace('[br]',"\n",$el->nodeValue));
  $str='
'.preg_replace('/(\n|\r)+/','

',$str).'
';
  $frag=$dom->createDocumentFragment();
  $frag->appendXML($str);
  $el->parentNode->replaceChild($frag,$el);
}

echo $dom->saveHTML();


text:
Q: App crashes with kotlin.UninitializedPropertyAccessException when I get value from Spinner My app works without errors and updates the field in the firestore when I hard-coded the value that needs to be updated. However, when I the following code to get the value from the spinner to update a field in the firestore, the app crashes.
I am using kotlin and viewBinding.
Following is the error in the Logcat

--------- beginning of crash 2021-06-07 14:00:12.155 23175-23175/com.trad E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.trad, PID: 23175
kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized
    at com.trad.ui.adapters.OrderStatusListAdapter.access$getBinding$p(OrderStatusListAdapter.kt:32)
    at com.trad.ui.adapters.OrderStatusListAdapter$onBindViewHolder$1.onClick(OrderStatusListAdapter.kt:84)
    at android.view.View.performClick(View.java:8160)
    at android.widget.TextView.performClick(TextView.java:16222)
    at android.view.View.performClickInternal(View.java:8137)
    at android.view.View.access$3700(View.java:888)
    at android.view.View$PerformClick.run(View.java:30236)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:246)
    at android.app.ActivityThread.main(ActivityThread.java:8512)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)

2021-06-07 14:00:12.234 23175-23175/com.trad I/Process: Sending
signal. PID: 23175 SIG: 9

Following is the OrderStatusListAdapter.kt class
The error that is pointing at line number 32 and 84 are mentioned as a comment in the code.
open class OrderStatusListAdapter(         //LINE # 32 MENTIONED IN THE ERROR
        private val context: Context,
        private var list: ArrayList<OrderStatus>,

        ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        lateinit var newOrderStatus: Spinner
        private lateinit var binding: OrderStatusLayoutBinding

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {

            return MyViewHolder(
                LayoutInflater.from(context).inflate(
                    R.layout.order_status_layout,
                    parent,
                    false
                )
            )
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            val model = list[position]

            if (holder is MyViewHolder) {

                GlideLoader(context).loadProductPicture(
                    model.image,
                    holder.itemView.iv_order_status_item_image
                )

                val dateFormat = "dd MMM yyyy HH:mm"

                val formatter = SimpleDateFormat(dateFormat, Locale.getDefault())

                val calendar: Calendar = Calendar.getInstance()
                calendar.timeInMillis = model.order_datetime

                val orderDateTime = formatter.format(calendar.time)
                holder.itemView.tv_order_status_order_date.text = orderDateTime

                holder.itemView.tv_order_status_item_name.text = model.items[0].title
                holder.itemView.tv_order_status_item_price.text = "$${model.total_amount}"
 model.order_datetime.toString()
                holder.itemView.tv_order_status.text = model.order_status
                holder.itemView.tv_order_status_order_id.text = model.id

                holder.itemView.btn_order_status_change_status.setOnClickListener {

    binding.spnOrderChangeStatus.onItemSelectedListener = // LINE 84 MENTIONED IN THE ERROR
                        object : AdapterView.OnItemSelectedListener {
                            override fun onItemSelected(
                                parent: AdapterView<*>?,
                                view: View?,
                                position: Int,
                                id: Long
                            ) {
                                Toast.makeText(
                                    context,
                                    "Selected value is ${
                                        parent?.getItemAtPosition(position).toString()
                                    }",
                                    Toast.LENGTH_SHORT
                                ).show()

                                val newstat = parent?.getItemAtPosition(position).toString()
                                FirestoreClass().updateOrderStatus(model.id, newstat)

                            }

                            override fun onNothingSelected(parent: AdapterView<*>?) {

                            }
                        }
                }

                holder.itemView.ib_order_status_delete_product.visibility = View.GONE

                holder.itemView.setOnClickListener {
                    val intent = Intent(context, SoldProductDetailsActivity::class.java)
                    intent.putExtra(Constants.EXTRA_SOLD_PRODUCT_DETAILS, model)
                    context.startActivity(intent)
                }

            }

        }

        override fun getItemCount(): Int {
            return list.size
        }

        class MyViewHolder(view: View) : RecyclerView.ViewHolder(view)
    }

A: The crash has occurred, because the binding is not initialized. Change the ViewHolder constructors:
class MyViewHolder(private val binding : OrderStatusLayoutBinding) : RecyclerView.ViewHolder(binding.root)

Also change onCreateViewHolder method
 return ViewHolder(OrderStatusLayoutBinding.inflate(LayoutInflater.from(parent.context), parent,false))

A:
kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized

Means that you tried to use the binding property before it being initialized.
binding should be declared in the place where you define the layout; and this is typically in onCreateViewHolder() callback at which you defined the default inflater without using data binding, to fix that:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {

    val inflater = LayoutInflater.from(parent.context)

    // initialize the binding either use:
    binding = DataBindingUtil.inflate(inflater, R.layout.order_status_layout, parent, false)
    // or use:
    // binding = OrderStatusLayoutBinding.inflate(inflater)

    return MyViewHolder(binding)
}

The second issue: you accept a View as constructor parameter in MyViewHolder while it should accept the item binding type which is OrderStatusLayoutBinding

class MyViewHolder(view: View) : RecyclerView.ViewHolder(view)

To fix that:
class MyViewHolder(binding: OrderStatusLayoutBinding) : RecyclerView.ViewHolder(binding.root)

UPDATE

I got the error Unresolved reference: DataBindingUtil alsoDataBindingUtil and inflater in binding = DataBindingUtil.inflate(inflater, R.layout.order_status_layout, parent, false) are red.

You need to enable dataBinding in build.gradle (Module level) and this requires to have kotlin-kapt plugin:
plugins {
    …
    id 'kotlin-kapt'
}
android {
    …
    buildFeatures {
        dataBinding true
    }
}


text:
Q: Creating model effect to new view using Storyboard with a UIActionSheet I'm updating an app with more options when they click the add button. Before, when they clicked it, a certain screen came up with a model transition. This I could easily do from the .storyboard file, but since the UIActionSheet does not show up in the .storyboard file, I have no way to link it to the other scene. How do I do this?
This is the code I have right now:
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 1:
            //  where somehow I need to get to the next scene using storyboard
            break;

        default:
            break;
    }
}

This may not matter, but I'm using a UITableView within a TabBar when the action sheet is called.

A: You can call performSegueWithIdentifier:sender:.
You might want to make sure the action sheet is being dismissed first.


text:
Q: How to plot a marker around eye region according to face landmarks of mediapipe Python The question is how to find the eye coordinate using the multipipe library and place a marker at the left,right, top, and bottom of each of the eyes using cv2 library.  as shown in the image below.

One of alternate suggestion is given below. I save this as my and other future reference
This is the continuation from this OP
Image taken from this link

A: This can be achieve via mp.solutions.face_mesh.FaceMesh
First get the face bb
results = face_mesh.process(cv2.cvtColor(image_input , cv2.COLOR_BGR2RGB))

Then for each eye region of interest, get the pixel position using the _normalized_to_pixel_coordinates
eye_r = _normalized_to_pixel_coordinates()

The full code is as below
import cv2
import mediapipe as mp

from mediapipe.python.solutions.drawing_utils import _normalized_to_pixel_coordinates

dframe = cv2.imread("detect_face/person.png")

image_input = cv2.cvtColor(dframe, cv2.COLOR_BGR2RGB)

face_mesh = mp.solutions.face_mesh.FaceMesh(static_image_mode=True, max_num_faces=2,
                                         min_detection_confidence=0.5)
image_rows, image_cols, _ = dframe.shape
results = face_mesh.process(cv2.cvtColor(image_input , cv2.COLOR_BGR2RGB))

fl=results.multi_face_landmarks[0]

##

for txt,cor in zip(['L','R','T','B'],[263, 362,386,374]):
    eye_r = _normalized_to_pixel_coordinates(fl.landmark[cor].x,fl.landmark[cor].y,
                                             image_cols,image_rows)
    cv2.putText(image_input, txt, eye_r,cv2.FONT_HERSHEY_SIMPLEX, 0.3, (0, 0, 255), 2)

for txt,cor in zip(['l','r','t','b'],[133,33,159,145]):
    eye_r = _normalized_to_pixel_coordinates(fl.landmark[cor].x,fl.landmark[cor].y,
                                             image_cols,image_rows)
    cv2.putText(image_input, txt, eye_r,cv2.FONT_HERSHEY_SIMPLEX, 0.3, (0, 0, 255), 2)

cv2.imwrite('test.png', image_input)

Which output


text:
Q: Which DS record will a validator choose when there are multiple valid DS records? If there are multiple DS records with each using a different but RFC-compliant algorithm and digest type, is there any way to predict how real world validators will select one?
I've tried to, for example, to review what the default behavior BIND would be, but I'm not familiar enough to know where to start to understand how it would resolve.
Example:
A zone has the following valid DS record algorithm and digest types:

Algorithm
Digest type

13
2

7
2

8
4

How does a validator choose which DS record to use?


text:
Q: wordpress, ajax = no go I asked a similar question with good advise to help me, but i have run into another problem with the same code. What I am looking to do is simply click a button on a users profile and change the default "0", meaning they're not banned, to a "1". Before I was using a hook and a "do_action" with no problems, now I am trying to use ajax. I will start by posting my code.
FUNCTION
add_action( 'wp_ajax_remove_account', 'remove_account' );
function remove_account() {
    global $wpdb;
    global $current_user;
    $author = get_queried_object();
    $uid = $author->ID;
    $user = $current_user->ID;
    $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->users SET removed = '%d' WHERE ID = '%d'", '1', $user ));
    wp_die();
}

AJAX
jQuery(document).ready(function($) {
    $('.wordpress-ajax-form').on('submit', function(e) {
    e.preventDefault();
    var $form = $(this);
    $.post($form.attr('action'), $form.serialize(), function(data) {
    }, 'json');
}); });

FORM
<form class="wordpress-ajax-form" method="post" action="<?php echo        AJAX_URL; ?>" >
<input type="hidden" name="action" value="remove_account" >

<button id="msgbutton">Remove Account</button>
</form>

The above will work fine, however if I change
$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->users SET removed = '%d' WHERE ID = '%d'", '1', $user ));

to
$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->users SET removed = '%d' WHERE ID = '%d'", '1', $uid ));

to get the user id of the profile I'm looking at, it doesn't work.
I added
$author = get_queried_object();
echo $author->ID;`

to my header and it gave me back the user id of the profile i was looking at so I know that code works. Any help is appreciated.


text:
Q: Redirect WindowsMessages received by the parrent window to the related ChildWindow I'm trying to wrap the winapi into my own classes like CWindow, CButton, CListBox, etc. So every class has its own CALLBACK memberfunction and therefore I subclassed every child windowcontrol to make them use their own callback. Sadly I figured out that not all windowmessages are sent to my subclassed callback function. For example some child controls like the ListBox control don't receive the WM_COMMAND messages.
Now I'm searching for a way to redirect all windowmessages which relate to a child window to the childwindo's callback. Cause my code is  a bit too long I created a short example code for a parentwindow class and a childcontrol class (not completed). The goal is to redirect all windowmessages which the parentwindow receive to the related childcontrol callback.
class CWindow {  //Parent Window example
private:
    HWND hParrent;
public:
    CWindow(){
        hParrent = CreateWindowExA(...); //with WS_CLIPCHILDREN style
    }
    static LRESULT CALLBACK ParentCallback(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam){
        if (IsWindow((HWND)lParam) && hWnd != (HWND)lParam)
            return SendMessageA((HWND)lParam, message, wParam, lParam); //Seems lParam often stores the child HWND. So idea is to redirect the messages to the childWindow. Avoid selfcalls with "hWnd != (HWND)lParam" cause after SendMessageA lparam and hwnd is the same... but currently this idea seems not working
        else{
            switch (message){} //do something
            return DefWindowProcA(hWnd, message, wParam, lParam);
        }
    }
    //some other member functions
};

class CButton { //Child WindowControl example
private:
    HWND hChild;
    WNDPROC oldWndProc;
public:
    CButton(){
        hChild = CreateWindowExA(...); //with WS_CHILD and WS_CLIPSIBLINGS styles
        oldWndProc = (WNDPROC)SetWindowLongPtrA(hChild, GWLP_WNDPROC, (LONG_PTR)ChildCallback);
    }
    static LRESULT CALLBACK ChildCallback(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam){
        switch(message){}  //do something
        if (oldWndProc != NULL)
            return CallWindowProcA(oldWndProc, hWnd, message, wParam, lParam);
        else
        return DefWindowProcA(hWnd, message, wParam, lParam);
    }
    //some other member functions
};


text:
Q: Getting a new nested resource's parent id for a form I have a resource, Decision, that belongs_to Group. Group has_many decisions. I want a group's primary key (id) to be saved on integer field group_id on every decision that's saved in the database. I'm doing it this way and it works, but it seems like a really stilted way to do it. Is there a more direct or "Railsy" way to do it?
To start, my controller action/view has a group instance variable and I link to a form this way:
<%= link_to "New decision", new_group_decision_path(@group) %>

..so that my form is on /groups/:group_id/decisions/new
My new method under DecisionsController creates a new @decision for the form and passes it the :group_id I got from params.
def new
  @decision = Decision.new(group_id: params[:group_id]
end

I then pull that @decision.group_id in the form in new.html.erb and put it in a hidden_field so that the decision gets created with a group_id. Do I need to pass that group_id via params, then an instance variable, then via hidden field or is there a more direct way? Thanks!

A: Firstly, change your new action, to make it more "railsey"... Some slight changes to your controller
before_action :set_group, only: [:new, :create] # or other actions that do not apply here

def new
    @decision = @group.decisions.build # or new
end

def create
    @decision = @group.decisions.create(decision_params)
end

private
    def set_group
        @group=Group.find(params[:group_id])
    end

    def decision_params
        params.require(:decision).permit(:list,:of,:permitted,:params)
    end

So, you don't need to pass hidden fields or other means to clarify the group: It's already in the url...


text:
Q: Ubuntu 13.04 Teamviewer 8 cant connect I have 64bit Teamviever 8 ver 8.0.17147 wine-1.5.19 installed on a Ubuntu 13.04 desktop and I can launch the app and make connections out to other computers without any problems.
When I try connecting to my Ubuntu client from any of my other windows machines with a teamviewer client or my android client, it just hangs at connecting and never connects.
I have tried both the 32bit and 64bit clients and they both will not allow an inbound connection.
Any help would be great...
Thanks
CJ

A: I figured it it -
I removed teamviewer completely and then dowloaded it again but this time I did a manual install from a terminal window instead of letting the Ubuntu Software Center do the install and now its working great...

A: If you have two monitors, you can't use twinview. When I changed from 2 X displays to 1 X display with twinview, teamviewr stopped working for incoming connections.  Changing back to 2 X displays with no twinview fixed the problem.


text:
Q: Dividing a column value by unique number of multiple columns in R I need to obtain the value in the Area and Prm columns by dividing the values by the unique number of columns (YEAR  DIV  POL  ST  CTY   CR  PL  YID  LID DATE).
Is there a function in R to achieve this?
Thanks in advance.
Table:

Tag  YEAR  DIV  POL  ST  CTY   CR  PL  YID  LID DATE    Area PRm  SEP1  SEP2
S25  2005  7    3068 15  205   11  44  4    2   9042004 799  4504 326.9 296.6
S1   2005  7    4077 15  205   11  90  4    2   9202004 300  3000 316.1 309.2
S16  2005  7    4077 15  205   11  90  4    2   9202004 300  3000 391.2 201.5
S2   2005  7    4077 15  205   11  90  4    2   9202004 300  3000 271.2 311.5
S28  2005  7    3180 15  205   11  44  5    6   9202004 651  1747 251.2 382.5

Output:

Tag  YEAR  DIV  POL  ST  CTY   CR  PL  YID  LID DATE    Area PRm  SEP1  SEP2
S25  2005  7    3068 15  205   11  44  4    2   9042004 799  4504 326.9 296.6
S1   2005  7    4077 15  205   11  90  4    2   9202004 100  1000 316.1 309.2
S16  2005  7    4077 15  205   11  90  4    2   9202004 100  1000 391.2 201.5
S2   2005  7    4077 15  205   11  90  4    2   9202004 100  1000 271.2 311.5
S28  2005  7    3180 15  205   11  44  5    6   9202004 651  1747 251.2 382.5

The difference in Table and Output is in the 2,3 and 4 rows in Area and PRm columns.
The values in the Area and Prm column (300 and 3000) was divided by 3 (because YEAR  DIV  POL  ST  CTY   CR  PL  YID  LID DATE columns are identical in rows 2,3 and 4). SO the values in the Area and PRm columns are divided by 3 (300 / 3 = 100 in Area column and 3000 / 3 = 1000 in PRm column in 2,3 and 4th rows in the output table.
     S1   2005  7    4077 15  205   11  90  4    2   9202004 100  1000 316.1 309.2
    S16  2005  7    4077 15  205   11  90  4    2   9202004 100  1000 391.2 201.5
    S2   2005  7    4077 15  205   11  90  4    2   9202004 100  1000 271.2 311.5

A: with dplyr :
df1 %>% add_count(YEAR,DIV,POL,ST,CTY,CR,PL,YID,LID,DATE) %>%
  mutate(Area = Area /n) %>%
  select(-n)

output
# # A tibble: 5 x 15
#     Tag  YEAR   DIV   POL    ST   CTY    CR    PL   YID   LID    DATE  Area   PRm  SEP1  SEP2
#   <chr> <int> <int> <int> <int> <int> <int> <int> <int> <int>   <int> <dbl> <int> <dbl> <dbl>
# 1   S25  2005     7  3068    15   205    11    44     4     2 9042004   799  4504 326.9 296.6
# 2    S1  2005     7  4077    15   205    11    90     4     2 9202004   100  3000 316.1 309.2
# 3   S16  2005     7  4077    15   205    11    90     4     2 9202004   100  3000 391.2 201.5
# 4    S2  2005     7  4077    15   205    11    90     4     2 9202004   100  3000 271.2 311.5
# 5   S28  2005     7  3180    15   205    11    44     5     6 9202004   651  1747 251.2 382.5

data
df1 <- read.table(text="Tag  YEAR  DIV  POL  ST  CTY   CR  PL  YID  LID DATE    Area PRm  SEP1  SEP2
S25  2005  7    3068 15  205   11  44  4    2   9042004 799  4504 326.9 296.6
                  S1   2005  7    4077 15  205   11  90  4    2   9202004 300  3000 316.1 309.2
                  S16  2005  7    4077 15  205   11  90  4    2   9202004 300  3000 391.2 201.5
                  S2   2005  7    4077 15  205   11  90  4    2   9202004 300  3000 271.2 311.5
                  S28  2005  7    3180 15  205   11  44  5    6   9202004 651  1747 251.2 382.5",header=T,stringsAsFactors=F)


text:
Q: PHP: Undefined offset in urldecode / explode Trying to deconstruct a function I'm receiving a warning notice on that is used to retrieve CSV data from a database.
The function is called from index.php file, and may be formatted as
$masterRecords = $qb->genResultsTable($qid, $config[27]);
$config[27] is set dynamically, but to help understand; it is a period-delimited list of whole numbers. e.g. "3.4.5.6.7.8.9.25.141.137.83"
$qid is a whole number - e.g. "63".
The function works, but I'd like to see if I can get rid of the php Notice.
Getting notices for every item passed through the loop :
Notice: Undefined offset: 106 in /vagrant/public/arc/inc/lib.php on line 522

Call Stack:
1   0.0028  417156  {main}()    ../index.php:0
2   1.2886  473280  qb->genResultsTable()   ../index.php:66

The function:
public function genResultsTable($qid, $clist) {
  $url = "{$this->qb_ssl}{$this->db_id}?act=API_GenResultsTable&ticket={$this->ticket}&apptoken={$this->app_token}&qid={$qid}&clist={$clist}&slist={$clist}&options=csv";
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cjFile);
  curl_setopt($ch, CURLOPT_COOKIEFILE, $this->ckfile);
  //  curl_setopt($ch, CURLOPT_HEADER, true);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
  curl_setopt($ch, CURLOPT_COOKIE, "TICKET=" . urlencode($this->ticket));
  $r = curl_exec($ch);
  $r = preg_replace_callback('/([\'"])([^"]+)\1/', 'call_back', $r);
  preg_match_all('/(.*)\r\n/', $r, $matchs);
  $fields = explode('.', $clist);
  $count = count($matchs[0]);
  $arrs = array();
  for ($i = 1; $i < $count; $i++) {
    $explode_arr = explode(',', $matchs[0][$i]);
    $arr = array();
    foreach ($fields as $key => $field) {
  // vv THIS BELOW LINE IS THE LINE THAT IS INDICATED IN ERROR vv
      $arr[$field] = urldecode($explode_arr[$key]);
    }
    $arrs[] = $arr;
  }
  return $arrs;
}

function call_back($matches) {
  return urlencode($matches[0]);
}

A: In order to make @HamZa's answer more clear, basically the reason why you are getting a notice is because you are accessing an array with an index that does not exist, or is not set...
Ideally, each time you use the [ ] with a variable key, it's good idea to test if the key index/key exists for that array.
So, simply prepend doSomeThing($arr[$x]) with
if(isset($arr[$x])){
     doSomeThing($arr[$x])
}

This will prevent invalid array access and the notice should go away.


text:
Q: How to provide a feedback to UI in a async method? I have been developing a windows forms project where I have a 10 tasks to do, and I would like to do this in a async way.
These tasks will star when the user click in a button and I call a async method to do this.  In my code, I already have a list of parameters for these processes.
My questions is:

A) How transform my code to run all process in parallel? (I would like to implement async/await)
B) How to provide a feedback to my UI application?

The code bellow is what I have tried:
My button to call a method to start processes
private void button1_Click(object sender, EventArgs e)
{
    // almost 15 process
    foreach (var process in Processes)
    {
        // call a async method to process
        ProcessObject(process);
    }
}

The method to simulate my process getting a parameter
private async void ProcessObject(ProcessViewModel process)
{
    // this is my loop scope, which I need to run in parallel
    {
       // my code is here

       // increment the progress of this process
       process.Progress++;

       // feedback to UI (accessing the UI controls)
       UpdateRow(process);
    }
}

I tried this, but I am not sure if it is the right way to update my UI (a grid).
private void UpdateRow(ProcessViewModel process)
{
    dataGridView1.Rows[process.Index - 1].Cells[1].Value = process.Progress;
    dataGridView1.Refresh();
}

A: First of all, say no to async void methods (Event handlers are exceptions) because exceptions thrown inside it will not be noticed. Instead use async Task and await it.
private async void button1_Click(object sender, EventArgs e)// <--Note the async modifier
{
    // almost 15 process
    foreach (var process in Processes)
    {
        // call a async method to process
        await ProcessObject(process);
    }
}

private async Task ProcessObject(ProcessViewModel process)// <--Note the return type
{
    // my code is here with some loops
    await Task.Run(()=>
    {
        //Will be run in ThreadPool thread
        //Do whatever cpu bound work here
    });

    //At this point code runs in UI thread
    process.Progress++;

    // feedback to UI
    UpdateRow(process);
}

However, this will start only one task at a time, once that is done it will start next. If you want to start all of them at once you can start them and use Task.WhenAll to await it.
private async void button1_Click(object sender, EventArgs e)// <--Note the async modifier
{
     var tasks = Processes.Select(ProcessObject).ToList();
     await Task.WhenAll(tasks);
}

A: Sriram covered how to do the async/await in his answer, however I wanted to show you another way to update the progress on the UI thread using his answer as a base.
.NET 4.5 added the IProgress<T> interface and the Progress<T> class. The built in Progress class captures the synchronization context, just like async/await does, then when you go to report your progress it uses that context to make its callback (the UI thread in your case).
private async void button1_Click(object sender, EventArgs e)
{
     var progress = new Progress<ProcessViewModel>(UpdateRow); //This makes a callback to UpdateRow when progress is reported.

     var tasks = Processes.Select(process => ProcessObject(process, progress)).ToList();
     await Task.WhenAll(tasks);
}

private async Task ProcessObject(ProcessViewModel process, IProgress<ProcessViewModel> progress)
{
    // my code is here with some loops
    await Task.Run(()=>
    {
        //Will be run in ThreadPool thread
        //Do whatever cpu bound work here

        //Still in the thread pool thread
        process.Progress++;

        // feedback to UI, calls UpdateRow on the UI thread.
        progress.Report(process);
    });
}


text:
Q: Adding any control to an existing C# Windows form corrupts the display I'm using Visual Studio 2022 Community Edition w/ .Net 4.8 but the same behavior presents itself with Visual Studio 2019 Professional w/ .Net 4.6.1
What is happening is that I can clone a new Feature branch from Git to my local system and when I launch it everything is fine. The main application form presents itself just fine and I can get to all of the buttons, dropdown lists, file selectors just fine. The minute that I had any new control to the form when I subsequently launch the application the form is cut in half and I can't get to any of the controls and maximizing the form doesn't help either. When I inspect the designer code things have been drastically moved around in the post modification file as compared to the original. I've included sample information--
Original Form Display

Post Modification Form Display

Designer Code Compare Sample

A team member can take the same code base and add controls without any problems. Additionally he took my codebase which runs fine on his system compiled it and sent me the executable and when I launched that executable I had the problems with form display that my solution exhibits.
One final not thinking it was my laptop I got a brand new laptop and I'm still seeing the issue. I also created an AWS EC2 Instance and tried it there with the same behavior.
We're all stumped here none of us has ever seen behavior like this. We're hoping that someone in the Community has seen this sort of thing before and can shed some light on the issue.
Thanks,
Bill


text:
Q: Count number of times a widget is being set on all sidebars in Wordpress? I have Widget X loaded in three different sidebars in the widgets area of Wordpress.
Is there any way I can count the number of times this widget has been loaded in all of the sidebars currently visible?
In my case, after checking I should get "3".
Thanks

A: You can use jquery.
$(".sidebar").length;

A: You should be able to do what you want using the answer in this post:
wordpress count widgets and by counting the widget in multiple sidebars instead of one.


text:
Q: suma de datos de un 4 array sin repertir buenas quiero sumar 4 datos si esta en el array  a b c d pero si ya sume una vez ya no volver a sumar mira en  a = 36 datos, b = 28, c=7, d=3; son las personas que tienen un monto; si sumo en una interacion y el codigo repite no debo sumar en otra interacion
 las iteraciones serian las siguientes
sumar un datos:
a+b+c+d
a+b+c
a+c+d
b+c+d
d+a+b
a+b
a+c
a+d
b+c
b+d
c+d
supongamos que tengo 5 empleados

empleado 1 tendria q salir = 27
empleado 2 =4
empledo 3 = 21
Empleado 4 = 2
Empleado 5 = 1
pero me sale asi:
empleado 1 = 27
empleado1 = 21
empleado 1 =15
empleado 1 = 11
y asi quiero obviar si ya se sumo
for (int i = 0; i < list0706a.size(); i++) {

            double suma = 0;

            for (int j = 0; j < list0706b.size(); j++) {
                if (list0706b.get(j).getCODIGO() == list0706a.get(i).getCODIGO()) {
                    for (int a = 0; a < list0706c.size(); a++) {
                        if (list0706c.get(a).getCODIGO() == list0706b.get(j).getCODIGO()) {
                            for (int d = 0; d < list0706d.size(); d++) {
                                if (list0706d.get(d).getCODIGO() == list0706c.get(a).getCODIGO()) {
                                    //Encontre =  1234;
                                    suma = (listh0706a.get(i).getRESULTADO()
                                            + listh0706b.get(j).getRESULTADO()
                                            + listh0706c.get(a).getRESULTADO()
                                            + listh0706d.get(d).getRESULTADO());
                                    pw.println(String.valueOf("0" + list0706d.get(i).getCODIGO_DOC()
                                            + "|" + list0706d.get(i).getCEDULA() + "|"
                                            + "0706" + "|"
                                            + df.format(suma) + "|"
                                            + df.format(suma) + "|"));
                                }

                            }

                        }
                    }

                }
            }
        }

asi hice el for pero cuando continuo lo suma los anterioresja

A: Lo primero es que el código es muy confuso. Lo segundo es que, a menos que exista algo que no sepa o vea, este código es extremadamente ineficiente.
Veo que estas empleando 4 listas de un objeto con dos atributos ( codigo y resultado)
Estas listas se llaman:

*

*list0706a

*list0706b

*list0706c

*list0706d

Si las listas están ordenadas ( el primer registro en todas las listas pertenecen al mismo empleado, el segundo al segundo, etc y luego el tamaño de todas las listas son del mismo tamaño)
puedes solucionarlo con un simple bucle
for (int i = 0; i < list0706a.size(); i++) {
  suma = (listh0706a.get(i).getRESULTADO()
         + listh0706b.get(i).getRESULTADO()
         + listh0706c.get(i).getRESULTADO()
         + listh0706d.get(i).getRESULTADO());
  pw.println(String.valueOf("0" + list0706d.get(i).getCODIGO_DOC()
             + "|" + list0706d.get(i).getCEDULA() + "|"
             + "0706" + "|"
             + df.format(suma) + "|"
             + df.format(suma) + "|"));
}

y así pasas de un código de coste n^4 a coste n.

Si las listas están desordenadas optaria por un hashmap (cambia employee por tu objeto)
  Map<Employee, Integer> map = new HashMap<Employee, Integer>();
    for(int i=0;i<list0706a.size();i++)
    {
        if(map.containsKey(list0706a.get(i)))
        {
            map.put(list0706a.get(i),map.get(list0706a.get(i)+list0706a.get(i).getRESULTADO()));
        }
        else
        {
            map.put(list0706a.get(i),map.get(list0706a.get(i).getRESULTADO()));
        }
    }
    for(int i=0;i<list0706b.size();i++)
    {
        if(map.containsKey(list0706b.get(i)))
        {
            map.put(list0706b.get(i),map.get(list0706b.get(i)+list0706b.get(i).getRESULTADO()));
        }
        else
        {
            map.put(list0706b.get(i),map.get(list0706b.get(i).getRESULTADO()));
        }
    }
    for(int i=0;i<list0706c.size();i++)
    {
        if(map.containsKey(list0706c.get(i)))
        {
            map.put(list0706c.get(i),map.get(list0706c.get(i)+list0706c.get(i).getRESULTADO()));
        }
        else
        {
            map.put(list0706c.get(i),map.get(list0706c.get(i).getRESULTADO()));
        }
    }
    for(int i=0;i<list0706d.size();i++)
    {
        if(map.containsKey(list0706d.get(i)))
        {
            map.put(list0706d.get(i),map.get(list0706d.get(i)+list0706d.get(i).getRESULTADO()));
        }
        else
        {
            map.put(list0706d.get(i),map.get(list0706d.get(i).getRESULTADO()));
        }
    }

    for(PlayerModel i=0:map.keySet())
    {
        pw.println(String.valueOf("0" + i.getCODIGO_DOC()
                + "|" + i.getCEDULA() + "|"
                + "0706" + "|"
                + df.format(map.get(i)) + "|"
                + df.format(map.get(i)) + "|"));
    }
}

Y aun así este codigo no me gusta nada ya que ademas de que es costoso de comprender, su coste es de 5N

Recomiendo que encuentres, si es posible, alguna forma de que no recibieses 4 listas distintas. Planteate al objeto employee ( o como se llame) añadirle parametros por cada valor posible que puede tener o cambiar getRESULTADO para que devuelva una lista de entero/doubles


text:
Q: How to display image in a row from database? I want to retrieve the image from the database and want to display it in a row like if there is 20 images in a database then it should get display in 5 rows containing 4 images in each row...
My code is working properly but i am facing problem in image path as i hv stored the image-name in database and image inside admin/uploads folder.... like uploads folder is inside the admin folder... adminfolder/uploadsfolder/file-name
here in my code i am getting problem in tracing the image path.....
I am Facing problem in this line..
// my all images is in admin/uploads folder
echo "	";

Here is my full code
<?php
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('dogs_db') or die(mysql_error());

$sql = "SELECT file_name FROM dogsinfo";
$res = mysql_query($sql) or die(mysql_error());
echo "

";
while($fetch = mysql_fetch_assoc($res)) {
$path[] = $fetch['file_name'];
}

for($i=0;$i<count($path);$i++){

if($i%4 == 0){
echo "
";
}
// I am Facing Problem here ...
// my all images is in admin/uploads folder

echo "	";

}
echo "

";
?>

Please help me to sort out this....

A: How are within the admin/uploads folder, you must put in the src of the img tag.
<?php
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('dogs_db') or die(mysql_error());

$sql = "SELECT file_name FROM dogsinfo";
$res = mysql_query($sql) or die(mysql_error());
echo "

";
while($fetch = mysql_fetch_assoc($res)) {
$path[] = $fetch['file_name'];
}

for($i=0;$i<count($path);$i++){

if($i%4 == 0){
echo "
";
}
// I am Facing Problem here ...
// my all images is in admin/uploads folder

echo "	";

}
echo "

";
?>


text:
Q: Why this doesn't show 1.50 as output     #include <stdio.h>
    #define f(n) (2-(1/n))

    int main() {

 printf("when n =2, %.2f\n", f(2));
         return 0;
}

Answer is 0.00.Why the output isn't 1.50

A: Since f(n) is a macro. You must write the argument as a float or a double.
#include <stdio.h>
#define f(n) (2-(1/(n)))

int main()
{
    printf("when n =2, %.2f\n", f(2.0));

    return 0;
}

Or make the macro work with floats or doubles.
#include <stdio.h>
#define f(n) (2.0-(1.0/(n)))

int main()
{
    printf("when n =2, %.2f\n", f(2));

    return 0;
}


text:
Q: nginx wildcard subdomain ssl rewrite Have a wildcard dns subdomain record. Using domain-only validation SSL certificate.
Need to set nginx rewrite rules in that way:
http://site.com   => https://site.com

http://*.site.com => http://*.site.com

I guess it is something like this
server {
    listen  80;
    server_name site.com *.site.com;
    if ($host ~* "^([^.]+(\.[^.]+)*)\.site.com$"){
        set $subd $1;
        rewrite ^(.*)$ http://$subd.site.com$1 permanent;
        break;
    }
    if ($host ~* "^site.com$"){
        rewrite ^(.*)$ https://site.com$1 permanent;
        break;
    }
    #rewrite    ^ https://$server_name$request_uri? permanent;
    charset utf-8;
}

server {

    listen   443;

    server_name  site.com;
    ssl On;
    ssl_certificate     /root/site.com.crt;
    ssl_certificate_key /root/site.com.key;

    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:8888;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /var/www/site$fastcgi_script_name;
        fastcgi_param  QUERY_STRING     $args;
        include fastcgi_params;
    }

    location / {
        root   /var/www/site;
        index  index.php index.html;
        if ($host !~ ^(site.com)$ ) {
            return 444;
        }
        try_files $uri $uri/ /index.php?$args;
    }
}

It loops infinitely. What is the correct way to get this working ?

A: You should rewrite your server block into two parts.
First part only for domain "site.com" and following redirection to https
Second part, for all other domains, "*.site.com"
server {
    listen  80;
    server_name site.com;
    rewrite ^(.*)$ https://site.com$1 permanent;
}

server {
    listen  80;
    server_name *.site.com;
    #etc... rewrites not necessary
}

So, your nginx.conf would be:

server {
    listen  80;
    server_name site.com;
    rewrite ^(.*)$ https://site.com$1 permanent;
}
server {
    listen  80;
    server_name *.site.com;
    charset utf-8;
    # etc ...
}

server {

    listen   443;

    server_name  site.com;
    ssl On;
    ssl_certificate     /root/site.com.crt;
    ssl_certificate_key /root/site.com.key;

    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:8888;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /var/www/site$fastcgi_script_name;
        fastcgi_param  QUERY_STRING     $args;
        include fastcgi_params;
    }

    location / {
        root   /var/www/site;
        index  index.php index.html;
        if ($host !~ ^(site.com)$ ) {
            return 444;
        }
        try_files $uri $uri/ /index.php?$args;
    }
}


text:
Q: Apache Camel: How to use "done" files to identify records written into a file is over and it can be moved As the title suggests, I want to move a file into a different folder after I am done writing DB records to to it.
I have already looked into several questions related to this: Apache camel file with doneFileName
But my problem is a little different since I am using split, stream and parallelProcessing for getting the DB records and writing to a file. I am not able to know when and how to create the done file along with the parallelProcessing. Here is the code snippet:
My route to fetch records and write it to a file:
from(<ROUTE_FETCH_RECORDS_AND_WRITE>)
        .setHeader(Exchange.FILE_PATH, constant("<path to temp folder>"))
        .setHeader(Exchange.FILE_NAME, constant("<filename>.txt"))
        .setBody(constant("<sql to fetch records>&outputType=StreamList))
        .to("jdbc:<endpoint>)
        .split(body(), <aggregation>).streaming().parallelProcessing()
            .<some processors>
            .aggregate(header(Exchange.FILE_NAME), (o, n) -> {
                <file aggregation>
                return o;
            }).completionInterval(<some time interval>)
                .toD("file://<to the temp file>")
            .end()
        .end()
        .to("file:"+<path to temp folder>+"?doneFileName=${file:header."+Exchange.FILE_NAME+"}.done"); //this line is just for trying out done filename

In my aggregation strategy for the splitter I have code that basically counts records processed and prepares the response that would be sent back to the caller.
And in my other aggregate outside I have code for aggregating the db rows and post that writing into the file.
And here is the file listener for moving the file:
from("file://<path to temp folder>?delete=true&include=<filename>.*.TXT&doneFileName=done")
.to(file://<final filename with path>?fileExist=Append);

Doing something like this is giving me this error:
     Caused by: [org.apache.camel.component.file.GenericFileOperationFailedException - Cannot store file: <folder-path>/filename.TXT] org.apache.camel.component.file.GenericFileOperationFailedException: Cannot store file: <folder-path>/filename.TXT
    at org.apache.camel.component.file.FileOperations.storeFile(FileOperations.java:292)[209:org.apache.camel.camel-core:2.16.2]
    at org.apache.camel.component.file.GenericFileProducer.writeFile(GenericFileProducer.java:277)[209:org.apache.camel.camel-core:2.16.2]
    at org.apache.camel.component.file.GenericFileProducer.processExchange(GenericFileProducer.java:165)[209:org.apache.camel.camel-core:2.16.2]
    at org.apache.camel.component.file.GenericFileProducer.process(GenericFileProducer.java:79)[209:org.apache.camel.camel-core:2.16.2]
    at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)[209:org.apache.camel.camel-core:2.16.2]
    at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:141)[209:org.apache.camel.camel-core:2.16.2]
    at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)[209:org.apache.camel.camel-core:2.16.2]
    at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:460)[209:org.apache.camel.camel-core:2.16.2]
    at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:190)[209:org.apache.camel.camel-core:2.16.2]
    at org.apache.camel.processor.Pipeline.process(Pipeline.java:121)[209:org.apache.camel.camel-core:2.16.2]
    at org.apache.camel.processor.Pipeline.process(Pipeline.java:83)[209:org.apache.camel.camel-core:2.16.2]
    at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:190)[209:org.apache.camel.camel-core:2.16.2]
    at org.apache.camel.component.seda.SedaConsumer.sendToConsumers(SedaConsumer.java:298)[209:org.apache.camel.camel-core:2.16.2]
    at org.apache.camel.component.seda.SedaConsumer.doRun(SedaConsumer.java:207)[209:org.apache.camel.camel-core:2.16.2]
    at org.apache.camel.component.seda.SedaConsumer.run(SedaConsumer.java:154)[209:org.apache.camel.camel-core:2.16.2]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)[:1.8.0_144]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)[:1.8.0_144]
    at java.lang.Thread.run(Thread.java:748)[:1.8.0_144]
Caused by: org.apache.camel.InvalidPayloadException: No body available of type: java.io.InputStream but has value: Total number of records discovered: 5

What am I doing wrong? Any inputs will help.
PS: Newly introduced to Apache Camel

A: I would guess that the error comes from .toD("file://<to the temp file>") trying to write a file, but finds the wrong type of body (String Total number of records discovered: 5 instead of InputStream.
I don't understand why you have one file-destinations inside the splitter and one outside of it.
As @claus-ibsen suggested try to remove this extra .aggregate(...) in your route. To split and re-aggregate it is sufficient to reference the aggregation strategy in the splitter. Claus also pointed to an example in the Camel docs
from(<ROUTE_FETCH_RECORDS_AND_WRITE>)
    .setHeader(Exchange.FILE_PATH, constant("<path to temp folder>"))
    .setHeader(Exchange.FILE_NAME, constant("<filename>.txt"))
    .setBody(constant("<sql to fetch records>&outputType=StreamList))
    .to("jdbc:<endpoint>)
    .split(body(), <aggregationStrategy>)
        .streaming().parallelProcessing()
        // the processors below get individual parts
        .<some processors>
    .end()
    // The end statement above ends split-and-aggregate. From here
    // you get the re-aggregated result of the splitter.
    // So you can simply write it to a file and also write the done-file
    .to(...);

However, if you need to control the aggregation sizes, you have to combine splitter and aggregator. That would look somehow like this
from(<ROUTE_FETCH_RECORDS_AND_WRITE>)
    .setHeader(Exchange.FILE_PATH, constant("<path to temp folder>"))
    .setHeader(Exchange.FILE_NAME, constant("<filename>.txt"))
    .setBody(constant("<sql to fetch records>&outputType=StreamList))
    .to("jdbc:<endpoint>)
    // No aggregationStrategy here so it is a standard splitter
    .split(body())
        .streaming().parallelProcessing()
        // the processors below get individual parts
        .<some processors>
    .end()
    // The end statement above ends split. From here
    // you still got individual records from the splitter.
    .to(seda:aggregate);

// new route to do the controlled aggregation
from("seda:aggregate")
    // constant(true) is the correlation predicate => collect all messages in 1 aggregation
    .aggregate(constant(true), new YourAggregationStrategy())
        .completionSize(500)
    // not sure if this 'end' is needed
    .end()
    // write files with 500 aggregated records here
    .to("...");


text:
Q: How do I use savepoints in SQL Workbench/J with Redshift? Is it possible to recreate the following in redshift sql workbench?
create table test as
select top 10 * from core_data;
savepoint sv;
delete from test
where name like 'A%';
savepoint sv2;
delete from test
where name like 'B%';
rollback to sv;

A: Redshift doesn't support Rollback to Savepoints at all by any means. Hence you can't do with workbench as well.
See here list of all the unsupported PostgreSQL functions by Redshift. It includes savepoints as well.
If you execute rollback to savepoint query to Redshift like,
rollback to savepointexample;

You will see following error.

ERROR:  SQL command "rollback to savepoint sv3;" not supported.


text:
Q: Powershell select entire row with already opened excel worksheet I'm writing a little GUI to ease working on some excel documents. It has a button that starts this function to open excel file and select required row.
Function open_bible_file
{

$Excel = New-Object -ComObject excel.application

$Excel.WindowState= "xlMaximized"

$Excel.visible = $true

$WorkBook = $Excel.Workbooks.Open($SCOMBibleFile)

$Worksheet = $Workbook.WorkSheets.item("(1) Alerts")

$worksheet.activate()

$Range = $Worksheet.Cells.Item($excelrow,1).EntireRow

[void]$Range.Select()
}

}

It opens the file and selects the row as it should. But when I use this button again it just opens excel one more time and again selects another row. When I've tried to do another button to just select rows It does not know anything about already opened worksheets. How can I get around it?

A: The code should check if Excel is already running and if so, if the workbook (file $SCOMBibleFile) is present. If that is the case, re-activate Excel, otherwise start a new instance.
This should work:
function open_bible_file {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true, Position = 0)]
        [string]$Path,

        [Parameter(Mandatory = $false, Position = 1)]
        [int]$RowToSelect = 1
    )

    $WorkBook = $null
    # check if Excel is already open
    try {
        # Note: this only gets the excel instances that were started
        #       by the same user that runs this powershell function.
        $Excel = [Runtime.Interopservices.Marshal]::GetActiveObject('Excel.Application')
        # test if the $Path workbook is present in this Excel instance
        foreach ($wb in $Excel.Workbooks) {
            if ($wb.FullName -match [regex]::Escape($Path)) {
                $WorkBook = $wb
                break
             }
        }
    }
    catch {
        # Excel wasn't opened yet, create a new instance
        $Excel = New-Object -ComObject Excel.Application
    }

    if (!($Excel))    { Write-Error "Error opening Excel"; return }

    if (!($WorkBook)) {
        $WorkBook = $Excel.Workbooks.Open($Path)
    }

    # see https://learn.microsoft.com/en-us/office/vba/api/excel.xlwindowstate
    $xlMaximized = -4137

    $Excel.Visible = $true
    $Excel.WindowState = $xlMaximized
    $Excel.ActiveWindow.Activate()

    $Worksheet = $Workbook.WorkSheets.item("(1) Alerts")
    $worksheet.activate()
    $Range = $Worksheet.Cells.Item($RowToSelect, 1).EntireRow
    [void]$Range.Select()
}

$SCOMBibleFile = '<PATH TO YOUR .xlsx FILE>'
open_bible_file -Path $SCOMBibleFile -RowToSelect 3

As you can see, I have changed the open_bible_file function to take parameters. The first (-Path) is where you give it the filename to open. The second (-RowToSelect) is the row number you want selected.
Hope this helps


text:
Q: Sockets - Simple C# Server and JAVA Android Client I'm trying for sometime now and I cant figure it out why this is not working.
CLIENT:
public class MainActivity extends AppCompatActivity {

private Socket socket;
public static final int PORT = 6000;
public static final String server_IP = "192.168.2.30";
public String mensagem = null;
public String mensagem_final = null;

Button btn_conetar;
TextView txt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn_conetar = (Button) findViewById(R.id.btn_conetar);
    txt = (TextView) findViewById(R.id.txt);

    Thread t = new Thread() {
        public void run() {
            try {
                while(!isInterrupted())
                {
                    Thread.sleep(1000);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            txt.setText(mensagem_final);
                        }
                    });
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    t.start();

}
public void onClick(View view)
{
    new Thread((new ClientThread())).start();
    //Intent i = new Intent(MainActivity.this,Main2Activity.class);
   // startActivity(i);
}

//Thread que inicia o socket
class ClientThread implements Runnable
{
    @Override
    public void run() {
        try
        {
            InetAddress serveradress = InetAddress.getByName(server_IP);
            Log.e("TCP","A conetar...");
            socket = new Socket(serveradress,PORT);

            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while((mensagem = in.readLine()) != null)
            {
                mensagem_final += mensagem;
            }

            if(in.readLine() == null)
            {
                Log.e("TCP","Nao tem mensagens");
            }
            Log.e("MSG",mensagem);

            socket.close();
        }
        catch (UnknownHostException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }

    }
}

}
Server:
    Servidor servidor = new Servidor();
    servidor.serverthread();

class Servidor
{

   public void serverthread()
    {
        Thread serverthread = new Thread(server);
        serverthread.Start();
    }

    public void server()
    {

            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            TcpListener tcplistener = new TcpListener(IPAddress.Any, 6000);
            tcplistener.Start();

            TcpClient tcpclient = tcplistener.AcceptTcpClient();

            byte[] data = new byte[1024];
            NetworkStream ns = tcpclient.GetStream();

            string welcome = "Ola";
            data = Encoding.ASCII.GetBytes(welcome);
            ns.Write(data, 0, data.Length);

    }
}

Any idea why I cant receive the string "Ola" in my android application? It doesnt give me any error, it just doesnt do anything.
My internet's default adress is 192.168.2.1.
Good links are also welcome.


text:
Q: Is pgAdmin adding query time overhead? I just wrote a long question about what I did to optimize a rather simple query that takes much longer than I wish it would. I kept querying with pgAdmin. And then I made the query simpler and simpler until I ended up querying for the primary key of a newly created table with just 1 row in it.
create table perf_test (id bigint primary key);

and then queried:
select
  count(t.id)
from
  perf_test t
where
  t.id = 1
;

and the message output is:
Successfully run. Total query runtime: 66 msec.
1 rows affected.

I need to optimize a query that usually takes around 30-40ms when issued from my application. How can I experiment and measure the performance if the execution time in pgAdmin is already much higher for the simplest of all queries?

A: Yes, pgAdmin adds a lot of latency overhead.  I'm surprised you could even get it as low as 66msec.
The answer is pretty easy, don't use pgAdmin for things like this.
To try to figure out why a query is slow, you should use EXPLAIN (ANALYZE, BUFFERS) on the query.  pgAdmin does provide a way to do that, but IME it is strictly worse than just doing it through psql, or by using auto_explain to capture the plan into the log files.

A: You are looking at the wrong metric.

Total query runtime: 66 msec.

This resume in pgAdmin includes network latency and client overhead. Use EXPLAIN (ANALYZE, BUFFERS) for a detailed query plan, and EXPLAIN (ANALYZE, TIMING OFF) for minimum timing. The client does not matter for this metric at all, you get times from the server without network latency and client overhead.
See:

*

*Get execution time of PostgreSQL query


text:
Q: How to calculate difference of condition close and current close for all occurences of the condition con = ta.barssince(ta.rsi(close, 14) > 20) == 1

var flag = false

if ta.barssince(ta.ema(close, 50) > ta.ema(close, 200)) == 1
    flag := true

if ta.barssince(ta.ema(close, 50) < ta.ema(close, 200)) == 1
    flag := false

var labels = array.new_label()
var conCloses = array.new_float()

if con
    array.unshift(labels, label.new(bar_index, close, ""))
    array.unshift(conClose, close)

if flag[1]
    var txt = 0.
    for conClose in conCloses
        txt := close - conClose

    for label in labels
        label.set_text(label, str.tostring(txt))

afterFlag = flag[1] and not flag

if afterFlag
    array.clear(labels)
    array.clear(conCloses)

I want to calculate the difference of the close of when the condition is met with the current close for all the occurence of the condition, and display it with a label. I tried using the same logic with the previous question I asked but only find myself struggling. Help would be appreciated.
Inserted a pic of what I'm trying to achieve.

A: If you would like the values to be updated on every tick you should set the label's text in the global scope, otherwise, the text will be updated only on the flag[1] occurrence and real-time price would be ignored.
The second for..in structure with labels in your script is using only the last value of the txt as it is executed after all iterations of the previous  loop. You can use indexing in the for [index, element]..in structure to set the label's text:
//@version=5
indicator("myScript", overlay = true)

con = ta.barssince(ta.rsi(close, 14) > 20) == 1

var flag = false

if ta.barssince(ta.ema(close, 50) > ta.ema(close, 200)) == 1
    flag := true

if ta.barssince(ta.ema(close, 50) < ta.ema(close, 200)) == 1
    flag := false

var labels = array.new_label()
var conCloses = array.new_float()

if con
    array.unshift(labels, label.new(bar_index, close, "", color = color.new(color.blue, 80), style = label.style_label_up))
    array.unshift(conCloses, close)

var txt = 0.
for [i, conClose] in conCloses
    txt := conClose - close
    label.set_text(array.get(labels, i), str.tostring(txt))


text:
Q: Nativescript text around another text How can I make text to be around other text or image? I need something like this:
Label1 Label1 Label2
Label1 Label1 Label1
...

Label1 is all around Label 2...
Here is what I tried:
<FlexboxLayout width="100%" row="1">

</FlexboxLayout>

But It not looking good...

A: I don't think that is supported out of the box yet, but if you are interested you could use the native solution for iOS / Android.


text:
Q: SSRS: Row not repeating on every page I have set up a simple tablix with two rows.  The upper row has a value that I want repeated on every page, and the lower row contains a subreport.
I have tried setting the static row group RepeatOnNewPage to true and I have tried creating a table, putting the upper value in the header and setting headers to repeat on every page.  Neither of these have worked; the upper row value will only show on the first page.

A: I decided to pass the value in the upper row down as a parameter into the subreport.  It now shows up on every page.


text:
Q: Why do I get a referer to the HAL Browser instead of a JSON+HAL response by issuing a request to the root URL? I am using Spring Boot 1.4.0.RELEASE with spring-data-rest-hal-browser, spring-boot-starter-hateoas, spring-boot-starter-data-rest and a couple of other dependencies.
When I call
curl -H "Authorization: Basic YWRtaW46YWRtaW4xMjM=" -G http://localhost:8080/api/v1 -v

on my console, I get the following response:
* Adding handle: conn: 0x66a9e0
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x66a9e0) send_pipe: 1, recv_pipe: 0
* About to connect() to localhost port 8080 (#0)
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /api/v1 HTTP/1.1
> User-Agent: curl/7.33.0
> Host: localhost:8080
> Accept: */*
> Authorization: Basic YWRtaW46YWRtaW4xMjM=
>
< HTTP/1.1 302
< Set-Cookie: JSESSIONID=3DC642CBC288E944471DF289B11FBED4;path=/;HttpOnly
< X-Application-Context: application:dev
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< Location: http://localhost:8080/api/v1/browser/index.html#/api/v1
< Content-Language: de-DE
< Content-Length: 0
< Date: Wed, 17 Aug 2016 06:11:47 GMT

But I was expecting to get a json object with all discovered resources. At least one, because I have currently one repository:
@RepositoryRestResource(path = "billing-services", collectionResourceRel = "billing-services", collectionResourceDescription = @Description("Mandantendaten"))
    public interface BillingServiceRepository extends CrudRepository<BillingService, Long> {
}

Any hints?
Thank you,
Christian

A: There's a bug in the version of Spring Data REST that Spring Boot 1.4.0 uses. It's already been fixed in the latest Spring Data REST and Spring Boot snapshots.
You can try it out either by using Spring Boot 1.4.1.BUILD-SNAPSHOT or by using Spring Boot 1.4.0.RELEASE and overriding the spring-data-releasetrain.version property to have the value Hopper-BUILD-SNAPSHOT. In both cases the snapshots are available from https://repo.spring.io/libs-snapshot.


text:
Q: Setting up Suexec on apache on Godaddy Virtual private hosting I have recently purchased Godaddy VPS (Virtual Private Server) with their custom control panel and CentOS 5.4
From their control panel I am able to add domains to the server with their own user and directory.
Example:- Domain: Dummy.com
          User to control the domain "dummy.com": dummyuser
          Directory for the user : "/home/dummyuser/public_html/"
I was installing wordpress on the domain "dummy.com", but the wordpress installer was unable to write the config file to the directory. After some research I realised that this was because of the fact that apache was the user/owner running the apache webserver and it fetched the files from "dummyuser"'s diretory to execute them as the user "apache" instead of the owner of the file.
However I overcame the problem of writing to the directory by chmod 777 on the directory so apache was able to write to that directory. But now, here was another problem. "Apache" became the owner of the files it wrote or uploaded to the "dummyuser" directory which meant that "dummyuser" can not edit/delete/update files created in its own directory by "apache". So this was a real mess. But I deleted the files by using the chown -R username /home/username command to change the files owners/groups.
I want to install suexec so that each user such as "dummyuser" is able to execute its own scripts under its own username using Apache Webserver. This will allow "dummyuser" to write to its own directory without a problem and also will be the owner of the files it writes to the directory.
I have tried all the links out there, every forum and every place, but I have failed to install suexec. I understand that some of you may get frustrated by just reading this really long explanation but I hope that you also can understand how frustrated I am right now that I actually wrote this whole question after trying to install suexec for last 6 days.
I am able to use ssh. I am looking for someone to post a step by step guide to installing suexec and I want to configure it for "/home/[user]/public_html" directory where user is the username for the domain user.CentOS 5.4 is Operating System being used (with apache, mysql preinstalled).
If you know other ways to tackle this problem, then please do suggest them (I will really appreciate it).
Please do not copy and paste the instructions from other sites because I have tried about 20 different ways to install suexec but all of them failed.
I really need an a though response with step by step [working] instructions.
Thanks

A: It require you to be a experienced linux administrator to following the link
http://httpd.apache.org/docs/1.3/suexec.html#install
Otherwise, I strongly recommend you to ask GoDaddy support to do the job for you. Submit a support ticket there.


text:
Q: Entity Framework converts Contains to SQL LIKE or CHARINDEX I am using an OData endpoint to retrieve data from a SQL Database. I have a C# controller where Entity Framework converts the query to SQL. I need to use the SQL CONTAINS as I am going against a Full Text Catalogue. However, Entity Framework seems to be converting the CONTAINS to LIKE or CHARINDEX. This makes the search very slow and defeats the purpose of having a Full Text Catalogue. Is there a way around this?
C# Controller:
    [EnableQuery(AllowedQueryOptions = All)]
    [ProducesResponseType(typeof(IQueryable<Events>), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status403Forbidden)]
    [MapToApiVersion("1.0")]
    [ODataRoute("LogEvents")]
    public IQueryable<Events> GetEvents()
    {
        return _dbContext.Events.AsNoTracking();
    }

Example Query:
http://localhost:4000/api/Events?$filter=(contains(tolower(message),'cache'))

From the trace logs I noticed that Entity Framework executes the following commands:
Microsoft.EntityFrameworkCore.Database.Command|YJ|17244|13|Creating DbCommand for 'ExecuteReader'
Microsoft.EntityFrameworkCore.Database.Command|YJ|17244|13|Opening connection to database 'LocalDB' on server 'sql-dev'
Microsoft.EntityFrameworkCore.Database.Command|YJ|17244|13|Opened connection to database 'LocalDB' on server 'sql-dev'
Microsoft.EntityFrameworkCore.Database.Command|YJ|17244|13|Executing DbCommand

WHERE ((@__TypedProperty_0 LIKE N'') OR (CHARINDEX(@__TypedProperty_0, LOWER([l].[Message])) > 0))


text:
Q: Kinetic Energy and Inductor energy violates conservation of energy? Suppose we have an ideal LC circuit (no resistance) and an open switch where the capacitor has an initial voltage $V_o$. Initially, the energy stored in the capacitor at $t=0$ is $\frac{1}{2}CV_o^2$ and the energy in the magnetic field of the inductor is zero because no current is flowing. Now at time $t=0+dt$ we close the switch and current slowly begins to build up. When the current is a maximum, the energy stored in the magnetic field of the inductor is $\frac{1}{2}LI^2$ but now the energy stored in the capacitor is zero. Thus we must have that $\frac{1}{2}LI^2=\frac{1}{2}CV_o^2$ because no energy is dissipated since there is no resistance.
But there seems to be something very wrong here at a fundamental level. The charge (the electrons) traveling through the inductor at the instant that the current is a maximum have a non-zero kinetic energy (denote this kinetic energy $K_{charge}$). They have to have non-zero kinetic energy since they constitute a current. But if they do  posses this energy in addition to the magnetic field energy $\frac{1}{2}LI^2$, then the total energy at the moment the current is a maximum will equal $E_{tot}=\frac{1}{2}LI^2+K_{charge} >E_{initial}=1/2CV_o^2$. So its seems we have created energy in this process?
The only way I can work around this issue is to assume that the kinetic energy is already somehow factored into the magnetic field energy but I am not sure.
Any help on this issue would be most appreciated!

A: Kinetic energy of electrons due to electric current $I$ in an inductor is much smaller than magnetic energy $\frac{1}{2}LI^2$ (provided the inductor has large enough $L$, which is usually the case).
So yes, strictly speaking total energy stored in the capacitor is transformed into magnetic energy and kinetic energy of current-carrying charges, but the latter energy is so small compared to magnetic energy it is customary to ignore it.


text:
Q: Trying to create a button that handles an upload and a web share api function at the same time I am trying to create a single button in my React app that allows me to upload an image, and then using the web share api, share the uploaded image to whatever the user wants to...
My issue is, I cannot seem to execute the two one after the other.
Upload first, share second.
I have tried maybe using a setTimeout, or a setInterval, or waiting for a state to equal true, but I cant seem to figure it out.
Here is my code:

import { useRef, useState } from "react";
import { toBlob } from "html-to-image";
import Button from '@mui/material/Button';
import { styled } from '@mui/material/styles';

import IconButton from '@mui/material/IconButton';
import PhotoCamera from '@mui/icons-material/PhotoCamera';
import Stack from '@mui/material/Stack';

import '../styles/styles.css'

export default function Model() {

  const [image, setImage] = useState(null);

  const handleUpload = (e) => {
    const file = e.target.files[0];
    const reader = new FileReader();
    reader.onloadend = () => {
      setImage(reader.result);
    }
    reader.readAsDataURL(file);
  }

  const handleShare = async () => {
    console.log=("share clicked")
    const base64url = image
    const blob = await (await fetch(base64url)).blob();
    const file = new File([blob], 'fileName.png', { type: blob.type });
    navigator.share({
      title: 'Test Title',
      text: ' Experience',
      files: [file],
    })
  }

  const ColorButton = styled(Button)(({ theme }) => ({
    borderRadius: 50,
    border: '4px solid',
    borderColor: '#F0B152',
    backgroundColor: '#000000',
    color: 'white',
  }));

  return (

        <Button variant="contained" component="label">
          Upload
          <input hidden accept="image/*" multiple type="file" onChange={handleUpload} onClick={handleShare}/>
        </Button>

  );
}

A: You can move the handleShare function inside an useEffect hook and add image as a dependency. So that every time the setImage function is executed the useEffect hook will trigger the handleShare function.
import { useEffect, useState } from "react";
import Button from "@mui/material/Button";

export default function App() {
  const [image, setImage] = useState(null);

  useEffect(() => {
    if (image) {
      const handleShare = async () => {
        const base64url = image;
        const blob = await (await fetch(base64url)).blob();
        const file = new File([blob], "fileName.png", { type: blob.type });
        navigator.share({
          title: "Test Title",
          text: " Experience",
          files: [file]
        });
      };

      handleShare();
    }
  }, [image]);

  const handleUpload = (e) => {
    const file = e.target.files[0];
    const reader = new FileReader();
    reader.onloadend = () => {
      setImage(reader.result);
    };
    reader.readAsDataURL(file);
  };

  return (

      <Button variant="contained" component="label">
        Upload
        <input
          hidden
          accept="image/*"
          multiple
          type="file"
          onChange={handleUpload}
        />
      </Button>

  );
}