text:
Q: How does the Fibonacci exponentiation by squaring algorithm work? This is one of the best algorithms to calculate the nth Fibonacci sequence. It only needs O(log(n)) time to do its job, so it's very efficient. I found it somewhere but don't know how it works!
Can anyone tell me how this algorithm works?
int fib3 (int n) {
    int i = 1, j = 0, k = 0, h = 1, t;
    while (n > 0) {
        if (n % 2) {
            t = j * h;
            j = i * h + j * k + t;
            i = i * k + t;
        }
        t = h * h;
        h = 2 * k * h + t;
        k = k * k + t;
        n /= 2;
    }
    return j;
}

A: It's called the "matrix form" - take a look at Wikipedia
You can compute next Fibonacci number (k+2) by multiplying matrix on a vector of two previous elements (k + 1 and k). Hence, k + 3 can be computed by multiplying matrix on vector of (k + 2 and k + 1). This equals squared matrix multiplied on (k + 1 and k). So on.
Your code simply squares the matrix, taking into account odd powers.

A: Late answer, but an explanation for how this works:
The algorithm is based on Lucas sequence relations for Fibonacci numbers.
https://en.wikipedia.org/wiki/Lucas_sequence#Other_relations
Specifically these equations:
F(m)   = F(m-1) + F(m-2)
F(m+n) = F(m+1) F(n) + F(m) F(n-1)
F(2n)  = F(n) L(n) = F(n) (F(n+1) + F(n-1))
       = F(n)((F(n) + F(n-1)) + F(n-1))
       = F(n) F(n) + 2 F(n) F(n-1)

Initial state:
i = F(-1) = 1
j = F( 0) = 0
k = F( 0) = 0
h = F( 1) = 1

n is treated as the sum of powers of 2: 2^a + 2^b + ...
for each iteration e, let p = 2^i, then
h = F(p)
k = F(p-1)

To advance to the next iteration, h and k are advanced to F(next power of 2):
h' = F(2p) = F(p) F(p+1) + F(p) F(p-1)
   = F(p)(F(p) + F(p-1)) + F(p) F(p-1)
   = F(p) F(p) + F(p) F(p-1) + F(p) F(p-1)
   = F(p) F(p) + 2 F(p) F(p-1)
   = h h + 2 h k

k' = F(2p-1) = F(p + (p-1)) = F(p+1) F(p-1) + F(p) F(p-2)
   = (F(p) + F(p-1)) F(p-1) + F(p) (F(p) - F(p-1))
   = F(p) F(p-1) + F(p-1) F(p-1) + F(p) F(p) - F(p) F(p-1)
   = F(p) F(p) + F(p-1) F(p-1)
   = h h + k k

During the calculation of i and j, let c = current cumulative sum of bits of n:
i = F(c-1)
j = F(c)

To update i and j for 1 bits in n corresponding to p = current power of 2:
i' = F((c-1)+p) = F(c) F(p) + F(c-1) F(p-1)
   = j h + i k

j' = F(c+p) = F(c+1) F(p) + F(c) F(p-1)
   = (F(c)+F(c-1)) F(p) + F(c) F(p-1)
   = F(c) F(p) + F(c-1) F(p) + F(c) F(p-1)
   = j h + i h + j k


text:
Q: Extracting 3D patches from 3D images in both overlapping and nonoverlapping process and recovering the image back I am working with 172x220x156 shaped 3D images. To feed the image into the network for output I need to extract patches of size 32x32x32 from the image and add those back to get the image again.
Since my image dimension are not multiples of patch size thus I have to get overlapping patches.
I want to know how to do that.
I am working in PyTorch, there are some options like unfold and fold but I am not sure how they work.

A: To extract (overlapping-) patches and to reconstruct the input shape we can use the torch.nn.functional.unfold and the inverse operation torch.nn.functional.fold. These methods only process 4D tensors or 2D images, however you can use these methods to process one dimension at a time.
Few notes:

*

*This way requires fold/unfold methods from pytorch, unfortunately I have yet to find a similar method in the TF api.

*We can extract patches in 2 ways, their output is the same. The methods are called extract_patches_3d and extract_patches_3ds where X is the number of dimensions. The latter uses torch.Tensor.unfold() and has less lines of code. (output is the same, except it cannot use dilation)

*The methods extract_patches_Xd and combine_patches_Xd are inverse methods and the combiner reverses the steps from the extracter step by step.

*The lines of code are followed by a comment stating the dimensionality such as (B, C, D, H, W). The following are used:

*

*B: Batch size

*C: Channels

*D: Depth Dimension

*H: Height Dimension

*W: Width Dimension

*x_dim_in: In the extraction method, this is the number input pixels in dimension x. In the combining method, this is the number of number of sliding windows in dimension x.

*x_dim_out: In the extraction method, this is the number of sliding windows in dimension x. In the combining method, this is the number output pixels in dimension x.

*I have a public notebook to try out the code

*The get_dim_blocks() method is the function given on the pytorch docs website to compute the output shape of a convolutional layer.

*Note that if you have overlapping patches and you combine them, the overlapping elements will be summed. If you would like to get the initial input again there is a way.

*

*Create similar sized tensor of ones as the patches with torch.ones_like(patches_tensor).

*Combine the patches into full image with same output shape. (this creates a counter for overlapping elements).

*Divide the Combined image with the Combined ones, this should reverse any double summation of elements.
(3D):
We need to use 2 fold and unfold where we first apply the fold to the D dimension and leave the W and H untouched by setting kernel to 1, padding to 0, stride to 1 and dilation to 1. After we review the tensor and fold over the H and W dimensions. The unfolding happens in reverse, starting with H and W, then D.

def extract_patches_3ds(x, kernel_size, padding=0, stride=1):
    if isinstance(kernel_size, int):
        kernel_size = (kernel_size, kernel_size, kernel_size)
    if isinstance(padding, int):
        padding = (padding, padding, padding, padding, padding, padding)
    if isinstance(stride, int):
        stride = (stride, stride, stride)

    channels = x.shape[1]

    x = torch.nn.functional.pad(x, padding)
    # (B, C, D, H, W)
    x = x.unfold(2, kernel_size[0], stride[0]).unfold(3, kernel_size[1], stride[1]).unfold(4, kernel_size[2], stride[2])
    # (B, C, d_dim_out, h_dim_out, w_dim_out, kernel_size[0], kernel_size[1], kernel_size[2])
    x = x.contiguous().view(-1, channels, kernel_size[0], kernel_size[1], kernel_size[2])
    # (B * d_dim_out * h_dim_out * w_dim_out, C, kernel_size[0], kernel_size[1], kernel_size[2])
    return x

def extract_patches_3d(x, kernel_size, padding=0, stride=1, dilation=1):
    if isinstance(kernel_size, int):
        kernel_size = (kernel_size, kernel_size, kernel_size)
    if isinstance(padding, int):
        padding = (padding, padding, padding)
    if isinstance(stride, int):
        stride = (stride, stride, stride)
    if isinstance(dilation, int):
        dilation = (dilation, dilation, dilation)

    def get_dim_blocks(dim_in, dim_kernel_size, dim_padding = 0, dim_stride = 1, dim_dilation = 1):
        dim_out = (dim_in + 2 * dim_padding - dim_dilation * (dim_kernel_size - 1) - 1) // dim_stride + 1
        return dim_out

    channels = x.shape[1]

    d_dim_in = x.shape[2]
    h_dim_in = x.shape[3]
    w_dim_in = x.shape[4]
    d_dim_out = get_dim_blocks(d_dim_in, kernel_size[0], padding[0], stride[0], dilation[0])
    h_dim_out = get_dim_blocks(h_dim_in, kernel_size[1], padding[1], stride[1], dilation[1])
    w_dim_out = get_dim_blocks(w_dim_in, kernel_size[2], padding[2], stride[2], dilation[2])
    # print(d_dim_in, h_dim_in, w_dim_in, d_dim_out, h_dim_out, w_dim_out)

    # (B, C, D, H, W)
    x = x.view(-1, channels, d_dim_in, h_dim_in * w_dim_in)
    # (B, C, D, H * W)

    x = torch.nn.functional.unfold(x, kernel_size=(kernel_size[0], 1), padding=(padding[0], 0), stride=(stride[0], 1), dilation=(dilation[0], 1))
    # (B, C * kernel_size[0], d_dim_out * H * W)

    x = x.view(-1, channels * kernel_size[0] * d_dim_out, h_dim_in, w_dim_in)
    # (B, C * kernel_size[0] * d_dim_out, H, W)

    x = torch.nn.functional.unfold(x, kernel_size=(kernel_size[1], kernel_size[2]), padding=(padding[1], padding[2]), stride=(stride[1], stride[2]), dilation=(dilation[1], dilation[2]))
    # (B, C * kernel_size[0] * d_dim_out * kernel_size[1] * kernel_size[2], h_dim_out, w_dim_out)

    x = x.view(-1, channels, kernel_size[0], d_dim_out, kernel_size[1], kernel_size[2], h_dim_out, w_dim_out)
    # (B, C, kernel_size[0], d_dim_out, kernel_size[1], kernel_size[2], h_dim_out, w_dim_out)

    x = x.permute(0, 1, 3, 6, 7, 2, 4, 5)
    # (B, C, d_dim_out, h_dim_out, w_dim_out, kernel_size[0], kernel_size[1], kernel_size[2])

    x = x.contiguous().view(-1, channels, kernel_size[0], kernel_size[1], kernel_size[2])
    # (B * d_dim_out * h_dim_out * w_dim_out, C, kernel_size[0], kernel_size[1], kernel_size[2])

    return x

def combine_patches_3d(x, kernel_size, output_shape, padding=0, stride=1, dilation=1):
    if isinstance(kernel_size, int):
        kernel_size = (kernel_size, kernel_size, kernel_size)
    if isinstance(padding, int):
        padding = (padding, padding, padding)
    if isinstance(stride, int):
        stride = (stride, stride, stride)
    if isinstance(dilation, int):
        dilation = (dilation, dilation, dilation)

    def get_dim_blocks(dim_in, dim_kernel_size, dim_padding = 0, dim_stride = 1, dim_dilation = 1):
        dim_out = (dim_in + 2 * dim_padding - dim_dilation * (dim_kernel_size - 1) - 1) // dim_stride + 1
        return dim_out

    channels = x.shape[1]
    d_dim_out, h_dim_out, w_dim_out = output_shape[2:]
    d_dim_in = get_dim_blocks(d_dim_out, kernel_size[0], padding[0], stride[0], dilation[0])
    h_dim_in = get_dim_blocks(h_dim_out, kernel_size[1], padding[1], stride[1], dilation[1])
    w_dim_in = get_dim_blocks(w_dim_out, kernel_size[2], padding[2], stride[2], dilation[2])
    # print(d_dim_in, h_dim_in, w_dim_in, d_dim_out, h_dim_out, w_dim_out)

    x = x.view(-1, channels, d_dim_in, h_dim_in, w_dim_in, kernel_size[0], kernel_size[1], kernel_size[2])
    # (B, C, d_dim_in, h_dim_in, w_dim_in, kernel_size[0], kernel_size[1], kernel_size[2])

    x = x.permute(0, 1, 5, 2, 6, 7, 3, 4)
    # (B, C, kernel_size[0], d_dim_in, kernel_size[1], kernel_size[2], h_dim_in, w_dim_in)

    x = x.contiguous().view(-1, channels * kernel_size[0] * d_dim_in * kernel_size[1] * kernel_size[2], h_dim_in * w_dim_in)
    # (B, C * kernel_size[0] * d_dim_in * kernel_size[1] * kernel_size[2], h_dim_in * w_dim_in)

    x = torch.nn.functional.fold(x, output_size=(h_dim_out, w_dim_out), kernel_size=(kernel_size[1], kernel_size[2]), padding=(padding[1], padding[2]), stride=(stride[1], stride[2]), dilation=(dilation[1], dilation[2]))
    # (B, C * kernel_size[0] * d_dim_in, H, W)

    x = x.view(-1, channels * kernel_size[0], d_dim_in * h_dim_out * w_dim_out)
    # (B, C * kernel_size[0], d_dim_in * H * W)

    x = torch.nn.functional.fold(x, output_size=(d_dim_out, h_dim_out * w_dim_out), kernel_size=(kernel_size[0], 1), padding=(padding[0], 0), stride=(stride[0], 1), dilation=(dilation[0], 1))
    # (B, C, D, H * W)

    x = x.view(-1, channels, d_dim_out, h_dim_out, w_dim_out)
    # (B, C, D, H, W)

    return x

a = torch.arange(1, 129, dtype=torch.float).view(2,2,2,4,4)
print(a.shape)
print(a)
b = extract_patches_3d(a, 2, padding=1, stride=1)
bs = extract_patches_3ds(a, 2, padding=1, stride=1)
print(b.shape)
print(b)
c = combine_patches_3d(b, (2,2,2,4,4), kernel_size=2, padding=1, stride=1)
print(c.shape)
print(c)
ones = torch.ones_like(b)
ones = combine_patches_3d(ones, (2,2,2,4,4), kernel_size=2, padding=1, stride=1)
print(torch.all(a==c))
print(c.shape, ones.shape)
d = c / ones
print(d)
print(torch.all(a==d))

Output (3D)
torch.Size([2, 2, 2, 4, 4])
tensor([[[[[  1.,   2.,   3.,   4.],
           [  5.,   6.,   7.,   8.],
           [  9.,  10.,  11.,  12.],
           [ 13.,  14.,  15.,  16.]],

          [[ 17.,  18.,  19.,  20.],
           [ 21.,  22.,  23.,  24.],
           [ 25.,  26.,  27.,  28.],
           [ 29.,  30.,  31.,  32.]]],

         [[[ 33.,  34.,  35.,  36.],
           [ 37.,  38.,  39.,  40.],
           [ 41.,  42.,  43.,  44.],
           [ 45.,  46.,  47.,  48.]],

          [[ 49.,  50.,  51.,  52.],
           [ 53.,  54.,  55.,  56.],
           [ 57.,  58.,  59.,  60.],
           [ 61.,  62.,  63.,  64.]]]],

        [[[[ 65.,  66.,  67.,  68.],
           [ 69.,  70.,  71.,  72.],
           [ 73.,  74.,  75.,  76.],
           [ 77.,  78.,  79.,  80.]],

          [[ 81.,  82.,  83.,  84.],
           [ 85.,  86.,  87.,  88.],
           [ 89.,  90.,  91.,  92.],
           [ 93.,  94.,  95.,  96.]]],

         [[[ 97.,  98.,  99., 100.],
           [101., 102., 103., 104.],
           [105., 106., 107., 108.],
           [109., 110., 111., 112.]],

          [[113., 114., 115., 116.],
           [117., 118., 119., 120.],
           [121., 122., 123., 124.],
           [125., 126., 127., 128.]]]]])
torch.Size([150, 2, 2, 2, 2])
tensor([[[[[  0.,   0.],
           [  0.,   0.]],

          [[  0.,   0.],
           [  0.,   1.]]],

         [[[  0.,   0.],
           [  0.,   0.]],

          [[  0.,   0.],
           [  1.,   2.]]]],

        [[[[  0.,   0.],
           [  0.,   0.]],

          [[  0.,   0.],
           [  2.,   3.]]],

         [[[  0.,   0.],
           [  0.,   0.]],

          [[  0.,   0.],
           [  3.,   4.]]]],

        [[[[  0.,   0.],
           [  0.,   0.]],

          [[  0.,   0.],
           [  4.,   0.]]],

         [[[  0.,   0.],
           [  0.,   0.]],

          [[  0.,   1.],
           [  0.,   5.]]]],

        ...,

        [[[[124.,   0.],
           [128.,   0.]],

          [[  0.,   0.],
           [  0.,   0.]]],

         [[[  0., 125.],
           [  0.,   0.]],

          [[  0.,   0.],
           [  0.,   0.]]]],

        [[[[125., 126.],
           [  0.,   0.]],

          [[  0.,   0.],
           [  0.,   0.]]],

         [[[126., 127.],
           [  0.,   0.]],

          [[  0.,   0.],
           [  0.,   0.]]]],

        [[[[127., 128.],
           [  0.,   0.]],

          [[  0.,   0.],
           [  0.,   0.]]],

         [[[128.,   0.],
           [  0.,   0.]],

          [[  0.,   0.],
           [  0.,   0.]]]]])
torch.Size([2, 2, 2, 4, 4])
tensor([[[[[   8.,   16.,   24.,   32.],
           [  40.,   48.,   56.,   64.],
           [  72.,   80.,   88.,   96.],
           [ 104.,  112.,  120.,  128.]],

          [[ 136.,  144.,  152.,  160.],
           [ 168.,  176.,  184.,  192.],
           [ 200.,  208.,  216.,  224.],
           [ 232.,  240.,  248.,  256.]]],

         [[[ 264.,  272.,  280.,  288.],
           [ 296.,  304.,  312.,  320.],
           [ 328.,  336.,  344.,  352.],
           [ 360.,  368.,  376.,  384.]],

          [[ 392.,  400.,  408.,  416.],
           [ 424.,  432.,  440.,  448.],
           [ 456.,  464.,  472.,  480.],
           [ 488.,  496.,  504.,  512.]]]],

        [[[[ 520.,  528.,  536.,  544.],
           [ 552.,  560.,  568.,  576.],
           [ 584.,  592.,  600.,  608.],
           [ 616.,  624.,  632.,  640.]],

          [[ 648.,  656.,  664.,  672.],
           [ 680.,  688.,  696.,  704.],
           [ 712.,  720.,  728.,  736.],
           [ 744.,  752.,  760.,  768.]]],

         [[[ 776.,  784.,  792.,  800.],
           [ 808.,  816.,  824.,  832.],
           [ 840.,  848.,  856.,  864.],
           [ 872.,  880.,  888.,  896.]],

          [[ 904.,  912.,  920.,  928.],
           [ 936.,  944.,  952.,  960.],
           [ 968.,  976.,  984.,  992.],
           [1000., 1008., 1016., 1024.]]]]])
tensor(False)
torch.Size([2, 2, 2, 4, 4]) torch.Size([2, 2, 2, 4, 4])
tensor([[[[[  1.,   2.,   3.,   4.],
           [  5.,   6.,   7.,   8.],
           [  9.,  10.,  11.,  12.],
           [ 13.,  14.,  15.,  16.]],

          [[ 17.,  18.,  19.,  20.],
           [ 21.,  22.,  23.,  24.],
           [ 25.,  26.,  27.,  28.],
           [ 29.,  30.,  31.,  32.]]],

         [[[ 33.,  34.,  35.,  36.],
           [ 37.,  38.,  39.,  40.],
           [ 41.,  42.,  43.,  44.],
           [ 45.,  46.,  47.,  48.]],

          [[ 49.,  50.,  51.,  52.],
           [ 53.,  54.,  55.,  56.],
           [ 57.,  58.,  59.,  60.],
           [ 61.,  62.,  63.,  64.]]]],

        [[[[ 65.,  66.,  67.,  68.],
           [ 69.,  70.,  71.,  72.],
           [ 73.,  74.,  75.,  76.],
           [ 77.,  78.,  79.,  80.]],

          [[ 81.,  82.,  83.,  84.],
           [ 85.,  86.,  87.,  88.],
           [ 89.,  90.,  91.,  92.],
           [ 93.,  94.,  95.,  96.]]],

         [[[ 97.,  98.,  99., 100.],
           [101., 102., 103., 104.],
           [105., 106., 107., 108.],
           [109., 110., 111., 112.]],

          [[113., 114., 115., 116.],
           [117., 118., 119., 120.],
           [121., 122., 123., 124.],
           [125., 126., 127., 128.]]]]])
tensor(True)

A: Is all your data exactly 172x220x156? If so, seems like you could just use a for loop and index into the tensor to get 32x32x32 blocks, correct? (possibly hardcoding a few things).
However, I'm not able to totally answer the question because it's not clear how you want to combine the results. To be clear, is this your goal?
1) get a 32x32x32 patch from an image
2) do some arbitrary processing on it
3) save that patch to some result at the correct index
4) repeat
If so, how do you plan on combining the overlapping patches? Sum them? Average them?
However - the indexing:
out_tensor = torch.zeros_like(input)
for i_idx in [0, 32, 64, 96, 128, 140]:
    for j_idx in [0, 32, 64, 96, 128, 160, 188]:
        for k_idx in [0, 32, 64, 96, 124]:
            input = tensor[i_idx, j_idx, k_idx]
            output = your_model(input)
            out_tensor[i_idx, j_idx, k_idx] = output

this isn't optimized at all, but I imagine the bulk of the computation will be the actual neural network, and there's no way around that, so optimization might be pointless.

A: You can use unfold (pytorch docs):
batch_size, n_channels, n_rows, n_cols = 1, 172, 220, 156
x = torch.arange(batch_size*n_channels*n_rows*n_cols).view(batch_size, n_channels, n_rows, n_cols)

kernel_c, kernel_h, kernel_w = 32, 32, 32
step = 32

# Tensor.unfold(dimension, size, step)
windows_unpacked = x.unfold(1, kernel_c, step).unfold(2, kernel_h, step).unfold(3, kernel_w, step)
print(windows_unpacked.shape)
# result: torch.Size([1, 5, 6, 4, 32, 32, 32])

windows = windows_unpacked.permute(1, 2, 3, 0, 4, 5, 6).reshape(-1, kernel_c, kernel_h, kernel_w)
print(windows.shape)
# result: torch.Size([120, 32, 32, 32])

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pumping lemma on a set containing square length strings of 0's I'm a bit confused with the contra-positive form of the pumping lemma to check if a language is regular or not.
Say we are given L = {$0^{k^2}$ | k is a natural number}
example: 0000
000000000
0000000000000000
Show that $L$ is not regular:

*

*Opponent picks k nodes

*I pick $xyz$ where $x = \varepsilon, y = 0^{k^2/2}, z = 0^{k^2/2}$
 so that my chosen string that is in the language $L$ is $0^{k^2}$

*The opponent now splits $y$ up into three parts $uvw$
where $u = 0^{k^2/6}, v = 0^{k^2/6}, w = 0^{k^2/6}$
a new string is made:
new string = $x(uv^iw)z$ where $i$ is going to be the amount of times $v$ will be replicated ('pumped').

*If i then pick $i = 2$ then we have the string $s$:
$s = x(uvvw)z$  $= \varepsilon(0^{k^2/6}0^{k^2/6}0^{k^2/6}0^{k^2/6})0^{k^2/6}$
 $= 0^{7k^2/6}$
Finally $0^{7k^2/6} \neq 0^{k^2}$ therefore $L$ is not regular.
Is this correct??
Thank you


text:
Q: Is document.ready() function necessary while writing code using JSOM I am trying to get list and Add fields into it using JSOM.
In code below I'm using $(function(){}) i.e. $(document).ready() function.

button id="addField"

$(function () {
 $("#addField").click(function () {
    var clientContext = new SP.ClientContext();
    var oWebsite = clientContext.get_web();

    this.oList = oWebsite.get_lists().getByTitle('CustomList');
    this.oField = oList.get_fields().addFieldAsXml('<Field DisplayName=\'Product\' Type=\'Number\' />', true, SP.AddFieldOptions.defaultValue);

    var fieldNumber = clientContext.castTo(oField, SP.FieldNumber);
    fieldNumber.update();

    clientContext.load(oField);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
   });
function onQuerySucceeded() {
    var result = oField.get_title() + ' added.';
    alert(result);
}

function onQueryFailed() {
    alert('Request failed. ' + args.get_message() +
        '\n' + args.get_stackTrace());
}

function onQuerySucceeded() {
    var result = oList.get_title() + ' created.';
    alert(result);
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
        '\n' + args.get_stackTrace());
}
});

So could I use ready function in JSOM code before bind any event.
If we can use $(function()) then give a sample code which would be useful.

A: You can load that, but you'll need to wait until sp.js is loaded properly before using SP.Context. You can 'tee' up the function if you using the SP.SOD.executeFunc('sp.js', 'SP.ClientContext', yourFunction);


text:
Q: how "shell export" behave in makefile there are three files:
test1.sh:
#!/bin/sh
export LD_LIBRARY_PATH=/usr/local/lib1

test2.sh:
#!/bin/sh
echo $LD_LIBRARY_PATH

Makefile:
.PHONY : all
all:
    ./test1.sh && ./test2.sh
    export LD_LIBRARY_PATH=/usr/local/lib1 && ./test2.sh

make result:
./test1.sh && ./test2.sh
/usr/local/lib
export LD_LIBRARY_PATH=/usr/local/lib1 && ./test2.sh
/usr/local/lib1

makefile always create a child process to execute command. what is the difference between first line command and second line of it?

A: This doesn't have anything to do with make; you'd see the same behavior if you ran those commands directly from the shell command line.
When you run a command like ./test1.sh (no matter how it's done) that invokes a new shell.  The new shell has a new copy of the environment of the parent process.  When you modify LD_LIBRARY_PATH inside ./test1.sh you modify that copy.  Then the shell exits, and that modified copy of the environment is destroyed.  Remember it's impossible in a POSIX/UNIX environment to ever modify the environment of your parent process (directly).
In the second example you first set LD_LIBRARY_PATH in the environment of the parent, then you invoke ./test2.sh which makes a copy of the parent's environment, so it inherits the new setting.
If you want to have a script that modifies the environment of the current shell you must use the source operation to run it; this causes the current shell to run the script rather than creating a new shell to run the script:
. ./test1.sh && ./test2.sh

The . shell command is the standard way to source a script instead of running it.


text:
Q: Supporting both SQL Server and Oracle in an EF DB first scenario I'm involved in a project which uses Entity Framework + database-first + SQL Server. There has been a decision that application has to support Oracle as well without changing the code base.
So my idea for a basic prototype is the following: whenever the SQL Server DB changes

*

*migrate changes to Oracle

*generate EDMX files from both DBs

*use T4 to set the connection string and the EDMX which is used with the code base

Is this ok? Is it there a better way to do it?
Thanks.

A: I think this question is more of a matter of taste, than what's right and wrong.
as long as it functions correctly in your testing - you're good.
Although - it is important to remember that EF was not meant to allow changing data sources without modifying code.
Therefore - I think there is a basic problem with the requirement.
I would say - either use OLEDB/ODBC which was meant exactly for that, with all queries in configuration files, or expect to change code with DBMS engine change.
Remember that the data types that exist in the DBMS are different, and for example - the Oracle BLOB is not as the MSSQL binary...
So - I would say two things:
1. If the code pass your tests, and your hapy with the results - the technique you use is working.
2. Fit the technology you use to your requirements.. EF does not fit your requirement as a base technology. ODBC/OLEDB do.


text:
Q: How can I customize the bar graph values? (Charts Framework) I am using the Charts Framework's BarChartView.. I want to customize values (1699,2181..)
The graphic that appears in my application is as follows.

I want to customize the values as shown in the image below.

How can i add background color, corner radius and border on values?
A part of the code is as follows
let chartDataSet = BarChartDataSet(values: dataEntries, label: "")
chartDataSet.colors = [UIColor.gray, UIColor.lightGray]
chartDataSet.drawValuesEnabled = true // Values
let myFont: NSUIFont = UIFont(name: "SFProDisplay-Semibold", size: 12.0)!
chartDataSet.valueFont = myFont

chart.xAxis.valueFormatter = IndexAxisValueFormatter(values: avgValue)
chart.xAxis.labelPosition = .bottom

chart.drawGridBackgroundEnabled = false
chart.xAxis.granularity = 1
chart.animate(xAxisDuration: 1.0, yAxisDuration: 1.0)
chart.leftAxis.axisMinimum = 0
chart.rightAxis.enabled = false

chart.extraRightOffset = 20
chart.extraLeftOffset = 20
chart.extraBottomOffset = 10
chart.extraTopOffset = 10

chart.legend.enabled = false

let chartData = BarChartData()
chartData.addDataSet(chartDataSet)
chart.data = chartData

A: Use BalloonMarker to get this type of design.Create new class called BallonMarker.
open class BalloonMarker: MarkerImage {

    open var color: UIColor
    open var arrowSize = CGSize(width: 15, height: 11)
    open var font: UIFont
    open var textColor: UIColor
    open var insets: UIEdgeInsets
    open var minimumSize = CGSize()
    open var chartWidth = CGFloat()

    fileprivate var label: String?
    fileprivate var _labelSize: CGSize = CGSize()
    fileprivate var _paragraphStyle: NSMutableParagraphStyle?
    fileprivate var _drawAttributes = [NSAttributedStringKey : AnyObject]()

    public init(color: UIColor, font: UIFont, textColor: UIColor, insets: UIEdgeInsets) {
        self.color = color
        self.font = font
        self.textColor = textColor
        self.insets = insets

        _paragraphStyle = NSParagraphStyle.default.mutableCopy() as? NSMutableParagraphStyle
        _paragraphStyle?.alignment = .center
        _paragraphStyle?.lineBreakMode = .byWordWrapping
        super.init()
    }

    open override func offsetForDrawing(atPoint point: CGPoint) -> CGPoint {
        var offset = self.offset
        var size = self.size

        if size.width == 0.0 && image != nil {
            size.width = image!.size.width
        }
        if size.height == 0.0 && image != nil {
            size.height = image!.size.height
        }

        let width = size.width
        let height = size.height
        let padding: CGFloat = 8.0

        var origin = point
        origin.x -= width / 2
        origin.y -= height

        if origin.x + offset.x < 0.0 {
            offset.x = -origin.x + padding
        }
        else if let chart = chartView,
            origin.x + width + offset.x > chart.bounds.size.width
        {
            offset.x = chart.bounds.size.width - origin.x - width - padding
        }

        if origin.y + offset.y < 0 {
            offset.y = height + padding;
        }
        else if let chart = chartView,
            origin.y + height + offset.y > chart.bounds.size.height
        {
            offset.y = chart.bounds.size.height - origin.y - height - padding
        }

        return offset
    }

    open override func draw(context: CGContext, point: CGPoint) {
        guard let label = label else { return }

        let offset = self.offsetForDrawing(atPoint: point)
        let size = self.size

        var rect = CGRect(
            origin: CGPoint(
                x: point.x + offset.x,
                y: point.y + offset.y),
            size: size)
        rect.origin.x -= size.width / 2.0
        rect.origin.y -= size.height

        context.saveGState()

        context.setFillColor(color.cgColor)

        if offset.y > 0 {
            context.beginPath()
            context.move(to: CGPoint(
                x: rect.origin.x,
                y: rect.origin.y + arrowSize.height))
            context.addLine(to: CGPoint(
                x: rect.origin.x + (rect.size.width - arrowSize.width) / 2.0,
                y: rect.origin.y + arrowSize.height))
            //arrow vertex
            context.addLine(to: CGPoint(
                x: point.x,
                y: point.y))
            context.addLine(to: CGPoint(
                x: rect.origin.x + (rect.size.width + arrowSize.width) / 2.0,
                y: rect.origin.y + arrowSize.height))
            context.addLine(to: CGPoint(
                x: rect.origin.x + rect.size.width,
                y: rect.origin.y + arrowSize.height))
            context.addLine(to: CGPoint(
                x: rect.origin.x + rect.size.width,
                y: rect.origin.y + rect.size.height))
            context.addLine(to: CGPoint(
                x: rect.origin.x,
                y: rect.origin.y + rect.size.height))
            context.addLine(to: CGPoint(
                x: rect.origin.x,
                y: rect.origin.y + arrowSize.height))
            context.fillPath()
        }
        else
        {
            context.beginPath()
            context.move(to: CGPoint(
                x: rect.origin.x,
                y: rect.origin.y))
            context.addLine(to: CGPoint(
                x: rect.origin.x + rect.size.width,
                y: rect.origin.y))
            context.addLine(to: CGPoint(
                x: rect.origin.x + rect.size.width,
                y: rect.origin.y + rect.size.height - arrowSize.height))
            context.addLine(to: CGPoint(
                x: rect.origin.x + (rect.size.width + arrowSize.width) / 2.0,
                y: rect.origin.y + rect.size.height - arrowSize.height))
            //arrow vertex
            context.addLine(to: CGPoint(
                x: point.x,
                y: point.y))
            context.addLine(to: CGPoint(
                x: rect.origin.x + (rect.size.width - arrowSize.width) / 2.0,
                y: rect.origin.y + rect.size.height - arrowSize.height))
            context.addLine(to: CGPoint(
                x: rect.origin.x,
                y: rect.origin.y + rect.size.height - arrowSize.height))
            context.addLine(to: CGPoint(
                x: rect.origin.x,
                y: rect.origin.y))
            context.fillPath()
        }

        if offset.y > 0 {
            rect.origin.y += self.insets.top + arrowSize.height
        } else {
            rect.origin.y += self.insets.top
        }

        rect.size.height -= self.insets.top + self.insets.bottom

        UIGraphicsPushContext(context)
        label.draw(in: rect, withAttributes: drawAttributes)
        UIGraphicsPopContext()
        context.restoreGState()
    }

    open override func refreshContent(entry: ChartDataEntry, highlight: Highlight) {
        setLabel(String(entry.y))
    }

    open func setLabel(_ newLabel: String) {
        label = newLabel

        _drawAttributes.removeAll()
        _drawAttributes[.font] = self.font
        _drawAttributes[.paragraphStyle] = _paragraphStyle
        _drawAttributes[.foregroundColor] = self.textColor

        _labelSize = label?.size(withAttributes: _drawAttributes) ?? CGSize.zero

        var size = CGSize()
        size.width = _labelSize.width + self.insets.left + self.insets.right
        size.height = _labelSize.height + self.insets.top + self.insets.bottom
        size.width = max(minimumSize.width, size.width)
        size.height = max(minimumSize.height, size.height)
        self.size = size
    }
}

How to pass values to BallonMarker.
let marker:BalloonMarker = BalloonMarker(color: UIColor.white, font: UIFont(name: "Helvetica", size: 12)!, textColor: .black, insets: UIEdgeInsets(top: 7.0, left: 7.0, bottom: 7.0, right: 7.0))
    marker.minimumSize = CGSize(width: 75.0, height: 50.0)
    chart?.marker = marker


text:
Q: Gearman workers - limiting the amount of jobs a worker will process Afternoon,
We are using Gearman in a production environment, we have a couple of workers running which are processing 100's of thousands of jobs daily (busy workers). We are having a slight memory issue though, the leak is very small, but after a few days it's building up.
On the command line, when I run
gearman --help

It says
...
Worker options:
-c <count> - Number of jobs for worker to run before exiting

This seems like the ideal option, we could set it to 50~k and know that the worker will die off and problem is solved. However looking through the pecl library for gearman I can't see where I can add/configure that.
There is an AddOption method which takes an int - but I can't find any reference in the document or source code to where I can set this.
I don't want to configure my own management system...
Any ideas?

A: GearmanManager allows you to specify the time each worker should live before being restarted (in seconds, not performed tasks).
Otherwise you could just keep track of the number of performed tasks in your worker, and start it with a bash-script in a while-loop. When you reach 50k, just exit() and let the bash script restart your worker.

A: You should probably post some code about how you handle the workers, because adding such a limit is usually trivial. Based on the sample from the manual:
$worker = new GearmanWorker();
$worker->addServer();

$worker->addFunction("reverse", "my_reverse_function");

while ($worker->work());

The worker performs a single operation at a time, so all you need to do is replace the while loop for something else.
for ($i; 50000 > $i; ++$i) { $worker->work(); }

I don't know how you manage to keep the workers alive, but I have found Upstart to work nicely.


text:
Q: C++ alternative to sscanf() I have the following function:
static void cmd_test(char *s)
 {
    int d = maxdepth;
    sscanf(s, "%*s%d", &d);
    root_search(d);
  }

How can I achieve the same output in a C++ way, rather than using sscanf?

A: int d = maxdepth;
sscanf(s, "%*s%d", &d);

Reads a string (which does not store anywhere) and then reads a decimal integer. Using streams it would be:
std::string dont_care;
int d = maxdepth;

std::istringstream stream( s );
stream >> dont_care >> d;


text:
Q: How to get variable value after form submit on simple page? ==
function onCheck()
{
   // It's simple page, not component, partial or controller
   // Therefore this syntax is right (according October docs)
   $this['myvar'] = "Hello";
}
==

<form class="dates" action="" method="POST" data-request="onCheck">
    <input type='text' class='date_inout' name="start" id='start'>
    <input type='text' class='date_inout' name="end" id='end'>
    <input type="submit" value="Подобрать">
</form>

{{ myvar }}

myvar isn't outputing. I need get myvar only after form submit, not onStart or onInit
Thank you in advance!

A: You need output only after ajax then you need to do this
==
function onCheck()
{
   $dates = post('start') . ' - ' . post('end');
   return ['#myvarContsiner' => "Hello " . $dates];
   //         ^ this id
}
==

<form class="dates" action="" method="POST" data-request="onCheck">
    <input type='text' class='date_inout' name="start" id='start'>
    <input type='text' class='date_inout' name="end" id='end'>
    <input type="submit" value="Подобрать">
</form>

Now when you hit submit button it will go to onCheck and return value ['#myvarContsiner' => "Hello " . $dates] so basically "Hello " . $dates will be updated in

 as per matching ID.

and your  will show value as you return it from onCheck
if you have any doubt please comment.


text:
Q: Insert/Update Issue (Same record repeated, no more can be entered) I'm a bit baffled here, and my code is a bit too lengthy to post it all, but I'll provide a logical list of the operations in hand and can provide the code where needed if it helps, but the problem is weird and I don't think it's to do with the code. It's a standard upload form for an article website.

*

*On first load, assign random article_ID

*Check if article_ID already exists. If it does, repeat step 1

*On save (submit), insert article_ID (the only required value [for testing purposes], the rest can be NULL)

*Any of other fields entered are checked for content, and if there is some entered update where article_ID = $article_ID.
It's quite a simple system, make a template of an article with an article_ID where all the other fields can be NULL. The user adds the content piece by piece saving along the way until all the fields are entered so the article can be published.
However, the first time I got it working, an article_ID was assigned and the template inserted. Now I can't insert any other records, and more oddly still if I delete that record and then create a new form instance with a new article_ID and INSERT, it just keeps adding the same record with the old article_ID, even though the form has no session variables with that old article_ID still stored.
Has anyone had something similar?
Database Structure
  `article_ID`            int(10)      NOT NULL,
  `author_ID`             int(5)       NOT NULL,
  `article_title`         varchar(50)  NOT NULL,
  `article_subtitleshort` varchar(120) default NULL,
  `article_subtitlelong`  varchar(180) default NULL,
  `article_category`      varchar(20)  NOT NULL,
  `article_featureimage`  varchar(15)  default NULL,
  `article_icon`          varchar(15)  default NULL,
  `article_publishdate`   varchar(12)  default NULL,
  `article_lastsavedate`  varchar(12)  NOT NULL,
  `article_status`        varchar(11)  NOT NULL default 'unpublished',
  `article_firstimage`    varchar(15)  default NULL,
  `article_intro`         varchar(600) default NULL,
  `article_firsttext`     blob,
  `article_secondimage`   varchar(15)  default NULL,
  `article_secondtext`    blob,
  `article_thirdimage`    varchar(15)  default NULL,
  `article_youtube`       varchar(50)  default NULL,
  `article_gallery`       varchar(10)  default NULL,
  PRIMARY KEY  (`article_ID`)

Relevant Code http://snippi.com/s/57j8i7e

A: I suspect the INSERT is failing because you are inserting a INTs as VARCHARs. Change it as follow - Remove the single quotes passing it through as VARCHAR incorrectly.
Also verify that your SELECT statement will return record as you are using the same logic when you pass the $article_ID i.e. remove the single quotes. Also not necessary to check for the random value.
Please make use of AUTO_INCREMENT for article_ID instead of randomly generating the value.
 mysql_query("INSERT INTO articles (author_ID) VALUES ($author_ID)");

article_ID will be populated with a unique value


text:
Q: How can I get this format of an optimization problem?
How can I reproduce this format of an optimization problem?
Ive been trying to use align but then I can produce the P only on the right side (using \tag). With alignat I couldn't produce the P at all.
This is what I tried:
\documentclass[•]{article}
\usepackage{amsmath}

\begin{document}
\begin{align*}
& \min\limits_{x \in X} && f(x) \tag{P} \\
& \text{subject to} && g(x) \leq \epsilon \nonumber
\end{align*}

\end{document}

A: You may want to switch between numbering equations on the left/right and use a gather to centre content - the alignment in your post seems non-uniform. To achieve some form of alignment around =, I've used boxes via \eqmakebox[<tag>][<align>]{<stuff>}. This sets <stuff> in a box of maximum width across the same <tag> using the appropriate <align>ment; left and right in my case.

\documentclass{article}

\usepackage[leqno]{amsmath}
\usepackage{eqparbox}

% https://tex.stackexchange.com/q/193535/5764
\makeatletter
\newcommand{\leqnomode}{\tagsleft@true}
\newcommand{\reqnomode}{\tagsleft@false}
\makeatother

\begin{document}

\reqnomode

\begin{align}
  f(x) &= ax^2 + bx + c \\
  g(x) &= dx^2 + ex + f
\end{align}

\leqnomode

\begin{gather}
  \eqmakebox[LHS][r]{$\min\ f(x)$}
    \eqmakebox[RHS][l]{$\displaystyle {}= \sum_{j = 1}^n f_j(x_j)$} \tag{P} \\
  \eqmakebox[LHS][r]{$\textup{s.t.}\ g_i(x)$}
    \eqmakebox[RHS][l]{$\displaystyle {}= \sum_{j = 1}^n g_{ij}(x_j) \leq b_i,\ i = 1,\dots,m,$} \nonumber \\
  x \in X = X_1 \times X_2 \times \dots \times X_n, \nonumber
\end{gather}

\reqnomode

\begin{align}
  f(x) &= ax^2 + bx + c \\
  g(x) &= dx^2 + ex + f
\end{align}

\end{document}

A: Is this what you want?

\documentclass{article}
\usepackage{amsmath}

\begin{document}
\begin{equation}
\begin{aligned}
\min_{x \in X}  f(x) &= \sum_{j=1}^{n} f_j(x_j) \\
\text{s.t. } g_i(x)  &= \sum_{j=1}^{n} g_{ij}(x_j)\leq b_i,\ i=1,\dots,m, \\
x\in X               &= X_1\times X_2\times \dots \times X_n.
\end{aligned}
\tag{P}
\end{equation}
\end{document}


text:
Q: OWL/RDF to UML Converter I'm new to the concept of OWL/RDF ontologies and thinking it would useful to be able to convert them to UML so I could then generate class skeletons using my IDE. Assuming this is a reasonable thing to do, can you please recommend an approach?
I'm aware that there are OWL/RDF parsers like this one, but I can't find any that will convert to UML.
EDIT:
Based on the comments let me modify the question:
When starting a new project based on an existing ontology is there a way to easily create skeleton classes as a starting point? I do not need to synchronize changes between the ontology and the classes - it is a one time setup that I expect will take a significant amount of copy and paste which strikes me as the wrong approach.
If I'm not using ontologies correctly, can you please explain what their purpose is (if any) in designing class hierarchies?
Here's an example of what I want to implement (except this is only 1 sensor and I need to implement several):
http://www.w3.org/2005/Incubator/ssn/XGR-ssn-20110628/#Smart_product_example

A: To implement https://github.com/WolfgangFahl/pysotsog/issues/21 I created some conversion code see https://github.com/WolfgangFahl/pysotsog/blob/main/skg/dblp.py. It is currently for the dblp schema at:
https://dblp.org/rdf/schema and a conversion example is at:
plantum online dblp schema
/'
 Wolfgang Fahl 2022-11-19
 updated 2022-11-19

 dblp schema https://dblp.org/rdf/schema
 converted from owl to plantuml
'/
title  dblp schema https://dblp.org/rdf/schema converted from owl to plantuml updated 2022-11-19
hide circle
package foaf {
  class Document {
  }
}
package dblp {
   note top of AmbiguousCreator
  Ambiguous Creator
  Not an actual creator, but an ambiguous proxy for an unknown number of unrelated actual creators. Associated publications do not have their true creators determined yet.
  end note
  class AmbiguousCreator{

  }
  AmbiguousCreator--Creator:possibleActualCreator
  Creator <|-- AmbiguousCreator
  note top of Informal
  Informal
  An informal or other publication.
  end note
  class Informal{

  }
  Publication <|-- Informal
  note top of Creator
  Creator
  A creator of a publication.
  end note
  class Creator{
    primaryCreatorName:string
    homepage:Document
    creatorNote:string
    orcid:anyUri
    creatorName:string
    affiliation:string
    awardWebpage:Document
    primaryAffiliation:string
    primaryHomepage:Document

  }
  Creator--Publication:editorOf
  Creator--AmbiguousCreator:proxyAmbiguousCreator
  Creator--Creator:coCreatorWith
  Creator--Creator:homonymousCreator
  Creator--Publication:authorOf
  Creator--Creator:coEditorWith
  Creator--Publication:creatorOf
  Creator--Creator:coAuthorWith
  Entity <|-- Creator
  note top of Publication
  Publication
  A publication.
  end note
  class Publication{
    primarydocumentPage:Document
    listedOnTocPage:Document
    yearOfEvent:gYear
    publishedBy:string
    isbn:anyUri
    publishersAddress:string
    publicationNote:string
    title:string
    bibtexType:Entry
    publishedInBookChapter:string
    doi:anyUri
    documentPage:Document
    numberOfCreators:integer
    publishedInSeries:string
    publishedInSeriesVolume:string
    publishedIn:string
    pagination:string
    yearOfPublication:gYear
    monthOfPublication:string
    publishedInJournalVolumeIssue:string
    publishedInJournal:string
    thesisAcceptedBySchool:string
    publishedInJournalVolume:string
    publishedInBook:string

  }
  Publication--Creator:createdBy
  Publication--Creator:authoredBy
  Publication--Creator:editedBy
  Publication--Signature:hasSignature
  Publication--Publication:publishedAsPartOf
  Entity <|-- Publication
  note top of Data
  Data
  Research data or artifacts.
  end note
  class Data{

  }
  Publication <|-- Data
  note top of Person
  Person
  An actual person, who is a creator of a publication.
  end note
  class Person{

  }
  Creator <|-- Person
  note top of AuthorSignature
  Author Signaure
  The information that links a publication to an author.
  end note
  class AuthorSignature{

  }
  Signature <|-- AuthorSignature
  note top of Inproceedings
  Inproceedings
  A conference or workshop paper.
  end note
  class Inproceedings{

  }
  Publication <|-- Inproceedings
  note top of Withdrawn
  Withdrawn
  A withdrawn publication item.
  end note
  class Withdrawn{

  }
  Publication <|-- Withdrawn
  note top of EditorSignature
  Editor Signaure
  The information that links a publication to an editor.
  end note
  class EditorSignature{

  }
  Signature <|-- EditorSignature
  note top of Editorship
  Editorship
  An edited publication.
  end note
  class Editorship{

  }
  Publication <|-- Editorship
  note top of Incollection
  Incollection
  A part/chapter in a book or a collection.
  end note
  class Incollection{

  }
  Publication <|-- Incollection
  note top of Reference
  Reference
  A reference work entry.
  end note
  class Reference{

  }
  Publication <|-- Reference
  note top of Group
  Group
  A creator alias used by a group or consortium of persons.
  end note
  class Group{

  }
  Creator <|-- Group
  note top of Signature
  Signature
  The information that links a publication to a creator.
  end note
  class Signature{
    signatureOrcid:anyUri
    signatureDblpName:string
    signatureOrdinal:integer

  }
  Signature--Creator:signatureCreator
  Signature--Publication:signaturePublication
  note top of Book
  Book
  A book or a thesis.
  end note
  class Book{

  }
  Publication <|-- Book
  note top of Entity
  Entity
  A general, identifiable entity in dblp.
  end note
  class Entity{
    identifier:anyUri
    wikipedia:Document
    archivedWebpage:Document
    wikidata:anyUri
    webpage:Document

  }
  Thing <|-- Entity
  note top of Article
  Article
  A journal article.
  end note
  class Article{

  }
  Publication <|-- Article
}

Just create an issue following the links in http://sotsog.bitplan.com if you'd like to get an online version.

*

*https://github.com/WolfgangFahl/pysotsog/blob/main/skg/owl.py

*https://github.com/WolfgangFahl/pysotsog/blob/main/skg/schema.py
have a more generic version as of 2023-01-08

A: My understanding is that the concept of the "semantic web" is still largely in the visionary stage and will not impact developers for some time. The initial applications seem to be centered around knowledge sharing between humans not machines. Hopefully it moves toward machine-to-machine sharing as there doesn't appear to be any interest in that at this time.

A: Check for UML to OWL converter. It converts UML to RDF/OWL, so it does job in opposite direction, but it can be used as a template for your task. The converter is based on MDA approach, so requires knowledge of it (MOF, ODM, Eclipse EMF, ATL), which is worth to have.


text:
Q: Postgres RETURNING clause with join and order I've got this query that updates some rows and returns the updated rows in the RETURNING clause. However, even though I've specified ORDER BY mycolumn in the inner query, the rows returned by RETURNING aren't ordered.
UPDATE mytable SET status = 'A'
FROM
  (
    SELECT id FROM mytable
    WHERE status = 'B'
    ORDER BY mycolumn
    LIMIT 100
    FOR UPDATE
  ) sub
  JOIN jointable j ON j.id = sub.id
WHERE mytable.id = sub.id
RETURNING *

I tried putting an ORDER BY in the outer query, like after the JOIN or after the WHERE, but I get an error in both cases. How can I make it return the rows in the desired order?
(A similar question was answered in Update Returning Order by in postgresql but that doesn't include JOINs, only ORDER.)

A: Use CTE:
WITH updated as(
    UPDATE mytable SET status = 'A'
FROM
  (
    SELECT id FROM mytable
    WHERE status = 'B'
    ORDER BY mycolumn
    LIMIT 100
    FOR UPDATE
  ) sub
  JOIN jointable j ON j.id = sub.id
WHERE mytable.id = sub.id
RETURNING *
)
select *
from updated
ORDER BY mycolumn


text:
Q: Constraint Ambiguity in Xcode 11 At the very beginning I add scrollView and try to add constraints.
Found here instruction. Do THE SAME, but it doesnt work.
Added:
Align leading
Align trailing
Height constrain
Align senter Y to Superview
My xcode scrinshot
It must be enough, isnt it?
So where is mistake?


text:
Q: Editar arquivo de word utilizando c# e replace Estou desenvolvendo uma aplicação em c# que precisa manipular arquivos em word, consigo escrever e ler normalmente mas estou tendo dificuldade em formatar o texto, preciso que seja inserido um array com algumas informações mas o word concatena todo o texto, como eu quebro a linha no word ?
            PTSOCIETARIA.Clear();
            PTSOCIETARIA.Append(". receita estadual     " + SOCIEDADE[0].receitaestadual);
            PTSOCIETARIA.Append("\n");
            PTSOCIETARIA.Append("\n");
            oRng = odoc.Range(ref missing, ref missing);
            FindTextnome = "@ptsocietaria7";
            ReplaceWithNome = PTSOCIETARIA.ToString();
            oRng.Find.Execute(ref FindTextnome, ref missing, ref MatchWholeWordnome, ref missing, ref missing, ref missing, ref Forward, ref missing, ref missing, ref ReplaceWithNome, ref missing, ref missing, ref missing, ref missing, ref missing);
            oApp.Visible = true;

A: Consegui resolver o meu problema inserindo ^p após o texto.


text:
Q: kuberenets pods shows different ulimit open files than the host I have a K8s cluster up and running on Azure VMs.
after getting:

java.io.IOException: Too many open files in system

on one of the pods, I checked the open files limits by calling:

ulimit -a | grep "open files"

on both, the host (via ssh), and got:

open files                      (-n) 1024

and from within the pod (via 'exec' the pod), and got:

bash-4.3# ulimit -a | grep "open files"
open files                      (-n) 1048576

my question is how is it possible to have different values (the pod 'see' higher limit than the underlined host), and also which of the limits counts - will it break if more than 1024 open fd's get opened?
the relevant pod image based from 'alpine-java'.
the host os is: CentOS Linux release 7.4.1708

A: For Ulimit option, you shoud change it from docker's unit file on your vm
    [Service]
    ExecStart=/usr/bin/dockerd \
      --iptables=false \
      --ip-masq=false \
      --host=unix:///var/run/docker.sock \
      --log-level=error \
      --storage-driver=overlay \
      --default-ulimit nofile=70000:70000 \
      --default-ulimit nproc=70000:70000
    Restart=on-failure
    RestartSec=5


text:
Q: Ошибка в доступе к изменениям в mysql на localhost! Здравствуйте.
Подскажите по бд. Создал стандартную базу на локалхосте, добавил пользователя с логином и пассом root root. Спустя некоторое время почему-то мне отказывает в выполнении многих действий: добавление данных в базу, удаление триггеров и прочее.
В чём дело?

A: Не было нужных прав на пользователе.
Вопрос решен.


text:
Q: convert a list containing sublist and tuples into a flat list 'a = [1,2,[12,5,(6,7,9)],[34,56]]
lambda l: [item for sublist in l for item in sublist]
ab = lambda a: [item for sublist in a for item in sublist]
print(ab(a))'
I want output like this [1,2,12,5,6,7,9,34,56]

A: Enjoy:
def convert(lst):
    if all(not isinstance(e, (list, tuple)) for e in lst):
        return lst[:]
    else:
        result = []
        for e in lst:
            if isinstance(e, (list, tuple)):
                converted = convert(e)
                result.extend(converted)
            else:
                result.append(e)
        return result

A: I treat this  as a text processing job.First convert the pass-in list into the string representation, then split the string into small parts each contains a element, finally i use a empty list receive these fresh elements.Here is my code snippt:
def simpleL(complexL):
    a =repr(complexL).split(',')
    c=[]
    for i in a:
        element =i.strip('[()] ')
        if element.isdigit():
            c.append(int(element))
    return c

A: output = []
def uni_lst(lst):
    if type(lst) in [list, tuple]:
        for x in lst:
            if type(x) in [list, tuple]:
                uni_lst(x)
            else:
                output.append(x)
    return output

Above code will make a single list from any type of list or tuple.


text:
Q: Are there reasons to use a redux store when data will only be necessary in a single component? I've got an app I'm building with some data that needs to be accessible in multiple components, so I'm putting it in a redux store.  However, I've got some data that will only be displayed in a single component.  Basically, a user can search for a business, click on the business to see its products, then click on a product to see any user-submitted feedback for that product.  The feedback will only ever be seen in the product component.
I don't really see any reason why I should put this data in the redux store, since I won't need to access it anywhere else, but I'm fairly new to React/Redux so I want to make sure I'm not missing anything.

A: Since you will only be using "user submitted feedback" data within the product component, it's perfectly acceptable to keep this within your local component state.
If you think that there is a chance that other parts of your app may want to use this information in the future, then it may be a good idea to go ahead and keep it in the Redux store. Planning ahead, in other words.
Check out this post from the Redux website, which talks about the issue you're having.

A: The primary appeal of putting data in the redux store is so you can access that data from any connected component that might need it.
If you're not using the data in any other component then I see no reason to put it in the redux store.
I would fetch the data from wherever you're getting it from when the component loads and store it in the state if it can be changed at all or in a const variable if no changes will be done to the data.


text:
Q: Firefox on newly installed Ubuntu 20.10 does not stream videos After a fresh install of Ubuntu 20.10, I was unable to stream video content through Firefox. Firefox showed blank screens or unhelpful messages.

A: Installing a video streaming program, VLC, recognized by Firefox, solved the problem.
Perhaps Ubuntu could include a Firefox friendly audio-visual streaming package in its installation image.


text:
Q: Why do adding jq arguments not change value I'm writing a bash script and came across this problem. When I pass jq --arg flags, it is not updating the value. But when I hard code in the values without the --arg flags, it does.
I have tried this in a script, and have also tried this directly in a terminal in both ways (with and without the argument flags). With does not update the value. Without does update the value.
echo "${JSON}"
[
  {
    "type": "portRule",
    "hostname": "fizz.buzz",
    "protocol": "https",
    "serviceId": "1s1495",
    "sourcePort": 443,
    "targetPort": 80
  },
  {
    "type": "portRule",
    "hostname": "foo.bar",
    "serviceId": "1s1499",
    "sourcePort": 443,
    "targetPort": 8082
  }
]

Works
jq '.[] | select((.hostname=="foo.bar") and (.targetPort==8082)).serviceId = "123"' <<<"${JSON}" | jq -s

Output
[
  {
    "type": "portRule",
    "hostname": "fizz.buzz",
    "protocol": "https",
    "serviceId": "1s1495",
    "sourcePort": 443,
    "targetPort": 80
  },
  {
    "type": "portRule",
    "hostname": "foo.bar",
    "serviceId": "123",
    "sourcePort": 443,
    "targetPort": 8082
  }
]

Does not work
jq --arg host "foo.bar" --arg port "8082" --arg id "123" '.[] | select((.hostname==$host) and (.targetPort==$port)).serviceId = $id' <<<"${JSON}" | jq -s

Output
[
  {
    "type": "portRule",
    "hostname": "fizz.buzz",
    "protocol": "https",
    "serviceId": "1s1495",
    "sourcePort": 443,
    "targetPort": 80
  },
  {
    "type": "portRule",
    "hostname": "foo.bar",
    "serviceId": "1s1499",
    "sourcePort": 443,
    "targetPort": 8082
  }
]

I will note that I am hoping that I can replace even the arguments values with environment variables rather than the strings as my examples shows. But I've tested both ways, same results.
So am I doing something wrong? Or is this a bug with jq (Probably not).
Expected results. It updates the value in the json with --arg flags as it does without and hard coding the strings.

A: Variables passed to jq using --arg are all converted to string, you need to use --argjson to pass integers.
jq --arg host "foo.bar" --argjson port "8082" --arg id "123" '.[] | select((.hostname==$host) and (.targetPort==$port)).serviceId = $id' <<<"${JSON}" | jq -s

As a sidenote, you don't need to call jq twice, just use map.
jq 'map(select(.hostname==$host and .targetPort==$port).serviceId=$id)' --arg host "foo.bar" --argjson port 8082 --arg id "123" <<<"$JSON"


text:
Q: How to change cakephp3 default pagination limit 20 to 100 How to change cakephp3 default pagination limit 20 to 100
Am new to cakephp anyone please guide me, how to set default limit now is 20, but i want 100

A: xxxxxcontroller.php
add code below to your controller
 public $helpers = [
           'Paginator' => ['templates' => 'paginator-templates']
       ];
       public $paginate = [
        'limit' =>100
    ];
    public function index()
    {
            $users = $this->Users->find('all');
            $users=  $this->set('users', $this->paginate());
     }

You can adjust the value of limit to any number you want. Like for the one you wanted change the value of limit to 100
index.ctp
<?= $this->Paginator->first("First");   ?>
  <?= $this->Paginator->prev('< ' . __('Previous')) ?>
  <?= $this->Paginator->numbers();  ?>

           <?= $this->Paginator->next(__('Next') . ' >') ?>
           <?= $this->Paginator->last("Last"); ?>

Showing <?= $this->Paginator->counter() ?>


text:
Q: Using Boost-Regex to parse string into characters and numerals I'd like to use Boost's Regex library to separate a string containing labels and numbers into tokens. For example 'abc1def002g30' would be separated into {'abc','1','def','002','g','30'}. I modified the example given in Boost documentation to come up with this code:
#include <iostream>
#include <boost/regex.hpp>

using namespace std;

int main(int argc,char **argv){
    string s,str;
    int count;
    do{
        count=0;
        if(argc == 1)
        {
            cout << "Enter text to split (or \"quit\" to exit): ";
            getline(cin, s);
            if(s == "quit") break;
        }
        else
            s = "This is a string of tokens";

        boost::regex re("[0-9]+|[a-z]+");
        boost::sregex_token_iterator i(s.begin(), s.end(), re, 0);
        boost::sregex_token_iterator j;
        while(i != j)
        {
            str=*i;
            cout << str << endl;
            count++;
            i++;
        }
        cout << "There were " << count << " tokens found." << endl;

    }while(argc == 1);
    return 0;
}

The number of tokens stored in count is correct. However, *it contains only an empty string so nothing is printed. Any guesses as to what I am doing wrong?
EDIT: as per the fix suggested below, I modified the code and it now works correctly.

A: From the docs on the sregex_token_iterator:
Effects: constructs a regex_token_iterator that will enumerate one string for each regular expression match of the expression re found within the sequence [a,b), using match flags m (see match_flag_type). The string enumerated is the sub-expression submatch for each match found; if submatch is -1, then enumerates all the text sequences that did not match the expression re (that is to performs field splitting)
Since your regex matching all items (unlike the sample code, which only matched the strings), you get empty results.
Try replacing it with a 0.


text:
Q: Slow ReactNative Android startup due to SoLoader We noticed that our ReactNative app takes quite a long time to start up on Android (we tested on a physical device as well as emulators). It pauses on the splash screen.
Digging into it some more we found that "SoLoader" was taking 5-6 seconds to do it's work. We benchmarked it against other RN apps like MatterMost and StandardNotes. All those finish writing similar "SoLoader" logs in less than 200ms.
We are using React Native 0.61.5
08-11 07:14:54.880 23749 23749 D SoLoader: adding application source: com.facebook.soloader.c[root = /data/app/com.myapp.preprod-jMszCFAFS7K4qllOKf0dEw==/lib/arm64 flags = 0]
08-11 07:14:54.880 23749 23749 D SoLoader: adding backup source from : com.facebook.soloader.a[root = /data/data/com.myapp.preprod/lib-main flags = 1]
08-11 07:14:54.880 23749 23749 D SoLoader: Preparing SO source: com.facebook.soloader.c[root = /data/app/com.myapp.preprod-jMszCFAFS7K4qllOKf0dEw==/lib/arm64 flags = 0]
08-11 07:14:54.880 23749 23749 D SoLoader: Preparing SO source: com.facebook.soloader.a[root = /data/data/com.myapp.preprod/lib-main flags = 1]
08-11 07:14:54.977 23749 23749 D SoLoader: libjscexecutor.so not found on /data/data/com.myapp.preprod/lib-main
08-11 07:14:54.977 23749 23749 D SoLoader: libjscexecutor.so found on /data/app/com.myapp.preprod-jMszCFAFS7K4qllOKf0dEw==/lib/arm64
08-11 07:14:54.996 23749 25778 D SoLoader: libreactnativejni.so not found on /data/data/com.myapp.preprod/lib-main
08-11 07:14:54.996 23749 25778 D SoLoader: libreactnativejni.so found on /data/app/com.myapp.preprod-jMszCFAFS7K4qllOKf0dEw==/lib/arm64
08-11 07:14:54.998 23749 25778 D SoLoader: libfb.so not found on /data/data/com.myapp.preprod/lib-main
08-11 07:14:54.998 23749 25778 D SoLoader: libfb.so found on /data/app/com.myapp.preprod-jMszCFAFS7K4qllOKf0dEw==/lib/arm64
08-11 07:14:55.009 23749 25778 D SoLoader: libfb.so not found on /data/data/com.myapp.preprod/lib-main
08-11 07:14:55.010 23749 25778 D SoLoader: libfb.so found on /data/app/com.myapp.preprod-jMszCFAFS7K4qllOKf0dEw==/lib/arm64
08-11 07:14:55.141 23749 25793 D SoLoader: libyoga.so not found on /data/data/com.myapp.preprod/lib-main
08-11 07:14:55.141 23749 25793 D SoLoader: libyoga.so found on /data/app/com.myapp.preprod-jMszCFAFS7K4qllOKf0dEw==/lib/arm64
08-11 07:14:56.758 23749 25792 D SoLoader: libreactnativeblob.so not found on /data/data/com.myapp.preprod/lib-main
08-11 07:14:56.758 23749 25792 D SoLoader: libreactnativeblob.so found on /data/app/com.myapp.preprod-jMszCFAFS7K4qllOKf0dEw==/lib/arm64
08-11 07:14:59.029 23749 25838 D SoLoader: libimagepipeline.so not found on /data/data/com.myapp.preprod/lib-main

Where could we be going wrong and how can we make it faster?


text:
Q: WP_Query by MAX post_id? I am trying to get the latest inserted post_id by an author using wp_query class. I have to use MAX(wp_posts.ID) in the args of the query i use. Is this somehow possible using wp_query class or do i have to use wpdb::get_results()? Any help appreciated.

A: try this
<?php
$new=new WP_Query(array('posts_per_page'=> 1,'order_by'=>'DESC'));
$max_id;
if($new->have_posts()){
while($new->have_posts())
{
     $new->the_post();
     $max_id=the_id();

}
  }
echo $max_id;


text:
Q: Close sliding sidenav by clicking anywhere I've created a website just as a stupid thing in my free time. Basically, me and my uni house do Disney Sundays where we all get together every Sunday and watch a Disney film. I've managed a generator that generates a random Disney film from a list and now I'm trying to sort out a list of the films we've watched...
Anyway, the website is hosted at http://disneysunday.tk and the piece of script for the sidenav is:
In the   tag:
.sidenav { height: 100%; width: 0; position: fixed;z-index: 1; top: 0; left: 0; background-color: rgba(255, 255, 255, 0.8); overflow-x: hidden; transition: 0.5s; padding-top: 60px; }
.sidenav a { padding: 3px 16px 3px 16px; text-decoration: none; font-size: 15px; color: #000000; display: block; transition: 0.3s; }
.sidenav a:hover, .offcanvas a:focus{ color: #72105e; }
.sidenav .closebtn { position: absolute; top: 0; right: 25px; font-size: 36px; margin-left: 50px; }
@media screen and (max-height: 450px) { .sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;} }

and in the body tag:

×
List of films each in an a tag

Everything works right now. However, I would like it so that when I click the button that opens the nav, if I then click anywhere on the page outside of the nav it closes. Or even just the same button. But preferably anywhere on the page!
Thank you for anyone who can help me! And don't worry if you can't because this is just a little side project. :)
Thanks everyone.

A: you can do this by executing a function on the document, and checking the event target's (e.target) attributes every time a click occurs on the document. If the click occurs on an element inside the nav, it should remain visible unless it's the .closebtn. If the click occurs on an element outside of te nav, it should be hidden, unless it's the .openbtn. (an open button is necessary only if you need to be able to bring the sidenav back up)

function openNav() {
document.getElementById("mySidenav").style.width = "250px";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}
/** This is the code you're interested in **/
document.addEventListener('click', function(e) {
  var snav = document.getElementById("mySidenav");
  if (e.target.id !== snav.id && !snav.contains(e.target) && !e.target.className.match('openbtn'))
    closeNav();
}, false);
.sidenav { overflow: hidden; float: right; width: 250px; background: yellow; height: 400px; }
.sidenav a:not(:link) { display: block; }
<button class="openbtn" onclick="openNav()">Films</button>

×
List of films each in an a tag
List of films each in an a tag
List of films each in an a tag
List of films each in an a tag
List of films each in an a tag
List of films each in an a tag


text:
Q: How can I minify css file containing @import url lines I am using grunt-contrib-cssmin to minify my css files but onw of my css files is using @import url lines and above mentioned grunt plugin is unable to minify this css file. I have also tried clean-css and cssjoin tools to solve this problem but nothing has worked until know.
**

*

*Grunt File:

**
grunt.initConfig({
        // Metadata
        pkg: grunt.file.readJSON('package.json'),

        cssmin: {
          minified_css_admin: {
              files: {
                  'public/admin/css/minified-css-admin.min.css'     ['public/admin/prettify/prettify.css','public/admin/css/developer.css']
              }
          }

        }
    });
    // These plugins provide necessary tasks

    grunt.loadNpmTasks('grunt-contrib-cssmin');

    // Default task
    grunt.registerTask('default', ['admin-default']);
    grunt.registerTask('admin-default', ['cssmin:minified_css_admin']);
};

**

*

*Prettify.css

**
@import url('bootstrap.min.css');
@import url('bootstrap-responsive.min.css');
@import url('uniform.tp.css');
@import url('jquery.ui.css');
@import url('colorpicker.css');
@import url('colorbox.css');
@import url('jquery.jgrowl.css');
@import url('jquery.alerts.css');
@import url('animate.min.css');
@import url('animate.delay.css');
@import url('font-awesome.css');
@import url('jquery.tagsinput.css');
@import url('ui.spinner.css');
@import url('jquery.chosen.css');
@import url('fullcalendar.css');
@import url('font-awesome-ie7.css');
@import url('../fonts/roboto.css');

/***** RESET BROWSER STYLES *****/
/********************************/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
    background: transparent;
    border: 0;
    margin: 0;
    padding: 0;
    vertical-align: baseline;
}

A: As per https://github.com/gruntjs/grunt-contrib-cssmin/issues/75 cssmin requires that you set the root directory in order for it to retain relative @import URLs.
   cssmin: {
        options: {
            report: 'min',
            root: '../../webroot',
       }
   }


text:
Q: Best setup to work with amazon AWS I have a website which gets backup from different social media services and then stores the data on server and then that is displayed on my website. content includes, videos, images, and text data.
Currently i am using an EC2 instance with RDS and EBS. Data is stored in EBS Volumes, But as the amount of the data is big enough more than 1 TB and that is increasing. Every time my EBS volume gets filled i attach another volume.
Then i added S3 to my Setup. Cron jobs runs and stores data on S3 and the EC2 instance displays data from the S3. I am using PHP SDK for this purpose.
The problem which i am facing is that the S3 is very slow in my current setup.
Please suggest whether my setup is good or i need some change in my setup and the other way how can i speedup S3. or i should opt some other way to my setup.
EC2 instance is large reserved instance running CentOS.
I have listened some about the S3fs that mount S3 bucket to Ec2 as a volume. Is this a good choice, as when i mounted S3 Bucket to Ec2 instance the transfer rate was very slow.
I am new to the AWS. My users does not access files directly from S3, but they access through my website which is running on EC2 Instance.

A: RDS is a good choice for storing metadata such as tags, comments and other relevant information about your multimedia files. S3 is good for storing static content such as Video, Audio and Pictures. I think your approach with RDS and S3 is good enough.
EBS backed instances are good for persistence. If you store your metadata on RDS and static content on S3, the only reason why you should use EBS backed EC2 instances is that you have some configuration files which are unversioned right now. If that's not the case, assuming that your configuration is checked into version control and can be pulled on-demand for a fresh instance every time, then you might want to ditch EBS volumes in favor of ephemeral storage. That may give you some performance boost, nothing significant though.
Regarding your concern with S3's latency, yes, S3 is slow. While all your writes may happen directly to S3, I would highly recommend that you set up Amazon CloudFront for your S3 buckets and let your website consume multimedia content from the CloudFront. CloudFront is a Content Delivery Network (CDN) which works with disk volumes (EBS backed or ephemeral) as well as with S3. Setting it up would take not more than a few minutes. CloudFront also supports streaming media files over RTMP. You may need a library like GPAC for hinting multimedia files to make them streamable if not being done already. You might then want to consider creating one distribution for Video/Audio files for streaming and another distribution for Images, Javascript, Stylesheets and other text files.
Hope this helps.

A: For faster getting and uploading files from Amazon S3 I use batch() found here.
Also you can use cloudfront for faster getting files. I think 9gag uses cloudfront also..


text:
Q: OpenGL Polygon Rendering inconsistency I am using opengl simple commands for demonstration purpose in my project. Well, my project is similar to mesh a rectangle region into a set of small convex polygons. First, I tried to render the rectangle region in unfilled mode using the following code.
void draw_boundary_unfilled(const double line_width,const double red, const double      green, const double blue) const
    {
        glLineWidth(line_width);
        glColor3d(red,green,blue);

        glPolygonMode(GL_FRONT,GL_LINE);
        glBegin(GL_POLYGON);
        for (unsigned i = 0; i < Polygon::size(); ++i)
        {
            const Point& pi = Polygon::vertex(i);
            glVertex2f(pi.x(), pi.y());
        }
        glEnd();
}

Note: the "Polygon" is a container in which I stored the vertices of either the rectangle or convex polygons.
It worked well with the rectangle region. After I did the mesh thing, I tried to use the same code for rendering each small convex polygons within the rectangle. It showed me, however, a whole filled rectangle region in which I had no way to tell edges of each convex polygon . It seemed to be an inconsistency. Any idea what is the problem?


text:
Q: Map is not visible, google is not defined I need to make a buffer/a circle around any point clicked on the marker. The code which I followed was https://www.codeproject.com/Articles/587199/Draw-Cirlce-Around-Marker-in-Google-Map. I have referred the previously asked questions relating to these but could not find satisfactory answer.  I request all those who can answer to please share since this will help a lot. Thanks in advance. I have added the script file which is showing the error.

A: You're getting that 'Uncaught ReferenceError: google is not defined' because of this statement
var currentlatlng = new google.maps.LatLng(23.06368, 72.53135);

At the time of executing this ^ line of code, google is still not yet defined. I suggest to put that statement inside of your loadMap() function.
Check this working example: http://jsbin.com/lukexag/4/edit?html,css,js,output
Here is the code snippet:

var map;
var circle;
var marker;
var currentlatlng;

function loadMap() {
    setLatLongValue();
    currentlatlng = new google.maps.LatLng(23.06368, 72.53135);
    map = new google.maps.Map(document.getElementById('map'), {
        zoom: 16,
        center: currentlatlng,
        mapTypeId: 'terrain',
        mapTypeControl: true,
        navigationControl: true
    });

    var marker = new google.maps.Marker({
        position: currentlatlng,
        draggable: true,
        map: map
    });

    marker.addListener('click', function(event) {
      drawCircle(event.latLng);
    });

    setLatLongValue();
    drawCircle();
}

function setLatLongValue() {
    // jQuery('#txtPointA1').val(currentlatlng.lat()); //#txtPointA1
    // jQuery('#txtPointA2').val(currentlatlng.lng());
}

function drawCircle() {

    var radius = 200;

    if (jQuery('#txtPointB1').val() !== '' && !isNaN(jQuery('#txtPointB1').val()) && parseInt(jQuery('#txtPointB1').val()) > 0) {
        radius = parseInt(jQuery('#txtPointB1').val());
    }
    jQuery('#txtPointB1').val(radius.toString());

    var options = {
        strokeColor: '#800000',
        strokeOpacity: 1.0,
        strokeWeight: 1,
        fillColor: '#C64D45',
        fillOpacity: 0.5,
        map: map,
        center: currentlatlng,
        radius: radius
    };

    circle = new google.maps.Circle(options);
}
#map {
  width: 500px;
  height: 500px;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Sample</title>

Update: Radius is now working


text:
Q: Non-ambiguous wording for 'Backend' When discussing a general and abstract project idea I often use the terms frontend and backend for GUI and well.. backend.
Often however, some people misunderstand frontend as the part of GUI used by 'customers' and backend as a seperat GUI for administrative personell etc.
I think I get where they come from (CMS or DMS probably use backend in that sense) but I am struggling with making a point when halve the people don't understand what I'm saying.
Is this a more common problem in German speaking countries? Is it my fault? Does anyone else have these problems?
Are there any synonyms for backend that mean the real backend (data access layer, non-gui functionalities etc.) and not the CMS/DMS backend which I could use?

A: The term "backend" is not offcially defined, so there is no "real" backend. For example, in my current working context, I would call the database a backend component (even if it does run on the same machine, maybe embedded in the program's process), but not a "data access layer".
So my suggestion is

*

*whenever you use the word backend, give a clear definition of what you mean in the specific context

*or, name the backend component you are talking of more specifically (the database, the web service, a non-gui library, a background monitor, a network service, and so on )

A: This is because "backend" can mean a lot of things. Without context it has no meaning.
For instance:
In a CMS it is not uncommon to actually call the administrative interface "the backend". Try a search for "Wordpres backend." and you'll see what I mean.
Wikipedia list of front and back ends

A: In the current state-of-the-art english, "backend" is not defined on the context of systems engineering, therefore, no synonyms or antonyms.
In the current state-of-the-art systems engineering "backend" is generally understood as everything that a user does not directly interact with. In another words, it's all that infrastructure only reached by servers. So a web server is front end because a user might write a HTTP request in Fiddler (although highly unlike) and a database server might also be front-end because a user might sniff the network and catch a "SELECT * FROM myTable" going to 192.168.0.4, somewhere he can call a pipe or something else.
In other scenarios "backend" is also a gigantic stack composed of many layers such as caching, security, OR mapping and etc... not only a "business-layer" and "database-layer"...
But if you put a gun in my head and you know... i would use the "Hidden-Stack" or maybe "Server-Side"... they are not perfect... but theres a gun in my head...


text:
Q: Why doesn't it cause an error when I set the length of a dim as zero I think the follwoing code will cause error, but it works well in android, why?
int[] myID=new int[0];

A: That just creates a zero-length array. That's absolutely fine - nothing wrong with it at all. It's an array with no elements. How else would you implement (say) a method which needs to return an array of "matching names" or something similar, but where there are no matches?
You'll get an error if you try to set or fetch any values in the array, but that's a different matter:
int[] empty = new int[0]; // This is fine
int firstElement = empty[0]; // This will throw an exception

The answer is not to do that...


text:
Q: Which account is the top level user account in Windows 7? In Windows 7, which account is higher than the administrator account?
In addition, how we can turn off the pop up dialog boxes which ask for admin permission to run, causing the whole screen to go off for 0.5 seconds?

A: You need to disable UAC to prevent the popup. Additionally , SYSTEM account has higher privileges than Administrator account in Windows in the sense that many system level modifications can only be done through SYSTEM account like making system calls, memory management ,etc. You will need administrator rights but essentially they will run under the context of SYSTEM account.


text:
Q: Set v-model to be a key in array (v-model.key="someArray") I'm doing a filter page and I need to store the filter name and the filter value,
for that purpose, I have a structure like that:

data: {
  attributes: { checkboxes: [], strings: { keys: [], values: [] }, ...

and the HTML would look like that (btw I'm using Laravel Blade too but that's not relevant here):
...
@if ($atribut->type == 'checkbox')
   tag }}"> {{ $nom }} <input v-model="attributes.checkboxes" class="badgebox" id="{{ $atribut->tag }}" type="checkbox" value="{{ $atribut->id }}">✓

@endif
@if ($atribut->type == 'string')
  @php $nom = obj_array_find(DB::table('literals')->get(), $atribut->nom, 'id')->cat @endphp
  <input type="hidden" v-model="attributes.strings.keys" value="{{ $atribut->id }}">
  {!! Form::text($atribut->tag, null, ['class' => 'form-control', 'placeholder' => $nom, 'v-model' => 'attributes.strings.values']) !!}

@endif
...

The question is, is it possible to have a something like that:
<input type="hidden" v-model.key="attributes.strings" value="{{ $atribut->id }}">
{!! Form::text($atribut->tag, null, ['class' => 'form-control', 'placeholder' => $nom, 'v-model.value' => 'attributes.strings]) !!}

A: To answer your specific question, v-model will bind to one key value pair, you don't need to assign the Key.
The way you structured your input binding The Input box will bind the object to your value field and you'll see [Object object] in the input box.
I created this jsfiddle that shows you how to bind to the model.  I assumed your data is modeled in this list format below.
attributes: [
    {checkboxes: [1], strings: { keys: [1], values: ['tomato'] }},
    {checkboxes: [2], strings: { keys: [2], values: ['potato'] }}
]

I also offered you a json object to watch the data update for each of these two keys.  This will help you in debugging where you are actually trying to go.
JSFiddle doesn't have a way to render laravel blade, so here is the blade version:
<input v-for="attribute in attributes" type="hidden" v-model="attribute.strings.values" value="1">
{!! Form::text('bam', null, ['v-for' => 'attribute in attributes', 'class' => 'form-control', 'placeholder' => 'boom',
        'v-model' => 'attribute.strings.values']) !!}

If, as you mention at the beginning of your question, you are looking to create a filter (I assume an autocomplete type object?), this wouldn't be the way to do it.
Hope this helps.

A: Sorry for my bad explanation guys but i finally found a solution,
what I meant was that i needed to know in a big list of inputs, which value was asociated to each input and the best way to do it is this one:
v-model="{{ 'filtres.transaccions["'.$atribut->tag.'"]' }}"

(in case you render with blade)
data: {
  filtres: {
    transaccions: {}
  }
}

because this way you get this:
this.filtres.transaccions.someInputKey: SomeInputValue

In which the key would be given by the $atribut->tag and the value of course would be given by the input itself


text:
Q: Difference between $center and $centerSphere in Mongo? Currently, we are using $centerSphere to find nearby cities. One example is that for the locality Bee Cave in Texas, USA, $centerSphere correctly found the only city Austin in a radius of 30 kilometers (As per documentation, it was converted in radians). Now, for the city Lautoka in Fiji (Lat: -17.6169618, Long: 177.4504609) it is giving the error "Spherical distance would require (unimplemented) wrapping". This is question one: what does this error mean?
We tried implementing the same by using $center. I'm aware we need to give distance in miles rather than radians. After implementing, for Bee Cave, I got US cities that were thousands or hundreds of miles away. One example is Albuquerque. I'm unable to understand why these cities are coming even after following Mongo documentation properly.
I'm using the query (for Bee Cave, TX)
db.places.find{
   "geo": {
      $geoWithin: { $center: [ [ -97.9524, 30.3061 ] , 18.64 ] }
   }
}

A: $centerSphere can't handle large distances, especially if it has to wrap around the poles, see this JIRA ticket.
Regarding $geoWithin it does not accept the distance in miles, but rather  the circle's radius as measured in the units used by the coordinate system, so latitude and longitude as per the documentation. That results in a very large bounding box that does include Albuquerque

You use $near instead that allows to specify a radius in meters. For example if you use this as your test data:
db.places.insert( {
   name: "Bee Cave, Texas",
   location: { type: "Point", coordinates: [ -97.9524, 30.3061 ]  }
} );
db.places.insert( {
   name: "Austin, Texas",
   location: { type: "Point", coordinates: [ -97.654724, 30.210768 ]  }
} );
db.places.insert( {
   name: "Albuquerque",
   location: { type: "Point", coordinates: [ -106.621216, 35.113281 ]  }
} );

db.places.createIndex( { location: "2dsphere" } )

You can write the following query using the factor 1609.344 to convert miles to meter
db.places.find(
   {
     location:
       { $near:
          {
            $geometry: { type: "Point",  coordinates: [-97.9524, 30.3061 ] },
            $maxDistance: 20*1609.344
          }
       }
   }
)

This query returns both Bee Cave,TX and Austin, TX:
{
   "_id":ObjectId("5a7190124f0cd7075d349bbc"),
   "name":"Bee Cave, Texas",
   "location":{
      "type":"Point",
      "coordinates":[
         -97.9524,
         30.3061
      ]
   }
}{
   "_id":ObjectId("5a7190124f0cd7075d349bbd"),
   "name":"Austin, Texas",
   "location":{
      "type":"Point",
      "coordinates":[
         -97.654724,
         30.210768
      ]
   }
}


text:
Q: How to execute if statement using Jython import org.python.util.PythonInterpreter;
public class JythonTest {
public static void main(String[] args) {
    PythonInterpreter interp = new PythonInterpreter();
    interp.exec("if 2 > 1:");
    interp.exec("   print('in if statement!'");
}
}

I need to be able to execute Python code from a Java program, so decided to try out Jython, but I'm unfamiliar with it. I tried executing the above code, but got the error: "Exception in thread "main" SyntaxError: ("mismatched input '' expecting INDENT", ('', 1, 9, 'if 2 > 1:\n'))". Any ideas what this means or how I can otherwise execute an if statement using the PythonInterpreter?

A: Conditionals must be entered as a single string and you have an extra parenthesis:
import org.python.util.PythonInterpreter;

public class JythonTest {
    public static void main(String[] args) {
        PythonInterpreter interp = new PythonInterpreter();
        interp.exec("if 2 > 1: print 'in if statement!'");
    }
}

A: Rather than executing a script line by line with strings you can invoke the interpreter to run a file. All you have to do is provide a file path to your python file, in this example place script.py in the src folder.
script.py
if 2 > 1:
    print 'in if statement'

JythonTest.java
import org.python.util.PythonInterpreter;

public class JythonTest {
    public static void main(String[] args) {
        PythonInterpreter interp = new PythonInterpreter();
        interp.execfile("src/script.py");
    }
}


text:
Q: Как сделать так, чтобы текст был справа? Надо, чтобы текст (Человек 1, город Алматы) был справа от картинки. Как это сделать?

A: Если необходимо сделать слева картинку а справа текст, советую использовать следующий html код:

Человек 1

        Город Алматы

И задаем свойства css с помощью flex:
.wrapper {
    display: flex;
    align-items: center;
}

.image img {
    height: 500px;
    width: 500px;
}

.text {
    padding-left: 15px;
}

Пример на JSFiddle


text:
Q: Why does RxNetty use threadpools? Recently I saw io.reactivex.netty.client.PoolExhaustedException. Isn't netty supposed to run using O(1) number of threads? isn't it advertised as the async, non-blocking, using event-loop client?
if it uses thread pools then why do i need it? I can just create my own pool in 3 lines of code and use it to do blocking connections.

A: That exception is for "connection" pool exhausted and not thread pool


text:
Q: Inserting into a HTML div tag from a javascript function I have searched online for a solution to my problem, but I can't seem to fix it.
I've tried also using a validator, but still nothing gives. Sorry if you think that this is a repeated question. I just can't seem to find anything. Here's what I did:
    <!DOCTYPE html>

 <title></title>

User Information:

 <button onclick="getUserInfo()">Begin</button>

Hello

A: Change

Hello

to

Hello

It might be the issue here.


text:
Q: Probability of guessing the colors of a deck of cards correctly 10 years ago when I was about 15 I sat down with a deck of shuffled cards and tried to guess if the next card in the deck would be red or black. In sequence I guessed 36 cards correctly as red or black, at that point my older bother came in and took told me what I was doing was stupid and I stopped being able to guess correctly. I would love to know what the probability of guessing 36 cards correctly in sequence is? Thank you

A: If you're aiming to guess the first 36 cards right with as high a probability as possible, then the best you can do is to choose some sequence of guesses with 18 reds and 18 blacks, and all those sequences are equally likely.
Each of them has probability
$\frac{(26\times 25\times 24\times\dots\times9)^2}{52\times51\times50\times\dots\times17}$
$=\frac{26!\times26!\times16!}{52!\times8!\times8!}$
$\approx 2.595\times 10^{-11}$.
So, the chances are about 1 in 40 billion.
(Assuming the pack of cards is shuffled)
It's easier than guessing 36 coin-tosses correctly, which would have probability $2^{-36}$ which is about 1 in 70 billion.

A: If you just guess red or black with a 50/50 chance, without taking into account that memory of the previous cards can make a guess more accurate, then the probability of guessing 36 cards in a row correctly is:
$$\left(\frac 12\right)^{36}$$
For comparison, if all 7.125 billion people in the world were to attempt this, the probability that anyone in the world would succeed is
$$\left(\frac 12\right)^{36} ~~\times~~ 7.125 \times 10^9 = 10.4\%$$
Which makes your story somewhat unbelievable.


text:
Q: Mixing two vectors: [a a] and [b b] to [a b a b] How can I mix two given vectors to a new one, which holds their values in an alternating order.
(f [a a] [b b]) ; > [a b a b]

This comes to my mind:
(flatten (map vector [:a1 :a2] [:b1 :b2]))

But maybe there's an easier way.

A: You can use interleave:
(interleave [:a :a] [:b :b])

A: Another alternative:
(apply into (map vector [:a1 :a2] [:b1 :b2]))

interleave is the way to go though.

A: You can use destructuring:
((fn [[a1 a2] [b1 b2]] [a1 b1 a2 b2]) [1 2] [3 4])
;[1 3 2 4]


text:
Q: Variable URL Reference in Google Sheets I am working on a dashboard for work that has a bunch of information, including unique links for each of our clients. I am trying to write a script that will open the url in a new window when a button is clicked. However, I need that URL to change based on the client that we have selected.
Here is the code I have written. It's bad, like really bad, but I am stuck on how I should do this.
var SPREADSHEET_NAME = "Database";
var SEARCH_COL_IDX = 0;
var RETURN_COL_IDX = 0;

function openLink() {

  var ss        = SpreadsheetApp.getActiveSpreadsheet();
  var formSS    = ss.getSheetByName("Dashboard"); //Form Sheet

  var str       = formSS.getRange("B2").getValue();
  var values    = ss.getSheetByName("Database").getDataRange().getValues();
  for (var i = 0; i < values.length; i++) {
    var row = values[i];
    if (row[0] == str) {

      var html = "<script> window.open(ss.getValue(row[1]));</script>";
  var ui = HtmlService.createHtmlOutput(html)
  SpreadsheetApp.getUi().showModelessDialog(ui,"Loading");

  }
 }
}

Here is a link to a Google Sheet that shows at a very basic level how I want this function to work. Dropdown in B2 on the Dashboard, when I select a "link" and press the button, the URL associated with the option I selected in B2 (that is in the database tab) will open.
https://docs.google.com/spreadsheets/d/1edKkHluCk3o0x96sQ7cw-cHcMBUnXzaOiPoywJA6Dyc/edit?usp=sharing

A: I believe your goal as follows.

*

*You want to open new window when the script of openService is run.

*You want to retrieve the value from the cell "B2" of "Dashboard", and want to open the URL from "Database" using the retrieved value.

Modification points:

*

*Unfortunately, "<script> window.open(ss.getValue(row[1]));</script>" cannot be directly run. In this case, I would like to propose to set the URL to window.open(URL) in the script.

*The flow of the modified script is as follows.

*

*Retrieve the value from cell "B2" of "Dashboard".

*Retrieve the values from "Database".

*Create an object for searching the URL.

*Retrieve the URL using the object and open new window.

When above flow is reflected to your script, it becomes as follows.
Modified script:
function openService() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // 1. Retrieve the value from cell "B2" of "Dashboard".
  var formSS = ss.getSheetByName("Dashboard");
  var str = formSS.getRange("B2").getValue();

  // 2. Retrieve the values from "Database".
  var [, ...values] = ss.getSheetByName("Database").getDataRange().getValues()

  // 3. Create an object for searching the URL.
  var obj = values.reduce((o, [a, b]) => Object.assign(o, {[a]: b}), {});

  // 4. Open new window.
  if (obj[str]) {
    var html = `<script>window.open("${obj[str]}"); google.script.host.close();</script>`;
    var ui = HtmlService.createHtmlOutput(html)
    SpreadsheetApp.getUi().showModelessDialog(ui,"Loading");
  }
}

Note:

*

*In this modification, after the new windows was opened, the dialog is closed using google.script.host.close(). If you don't want to close the dialog, please remove it.

*Please use this script with enabling V8.

References:

*

*reduce()

*Window.open()


text:
Q: How to list all the files of a specific extension in a folder in VS Code? How to list all the files of a specific extension in a folder in VS Code?
Let us suppose I have a folder with a deep subfolders structure. In that structure there are a lot of files of different extensions like: .html, .ts, .scss. Now I want to get a list of all the files with the .html extension. How can I do that?
Preferably I want not to see the subfolders structure. Just as when I search for a specific word I can limit file types to a specific extension in a specific folder - in this case I am given a list of files, with which I can easily work without a need to expand directories or read through the different from what I need extensions.
Partial solution for the problem is to figure out what patterns one is looking for in the files, then it is possible to use the in files search. E.g. ./pathToMyFolder/**/*.html. But I just need to open each .html file and I do not have a pattern to look for. And expanding each subdirectory and traversing it makes things really messy and cumbersome for me. Also, there are files with other extensions and filtering them out also takes time.

A: *

*Open the file picker - Ctrl + P

*Type *.<desired extension> (i.e *.cs)


text:
Q: How to write Xpath expressions to distinguish between results? I am new to xpath expression. Need help on a issue
    Consider the following Document :

By Bec
Great Support

In this I have to find the text inside  tags separately.
Following is my xpath expression:
//tbody//td//strong/text();

It evaluates output as expected:
Bec
Great Support

How can I write xpath expressions to distinguish between the results i.e Becand Great Support

A: It's rather unclear what you're trying to do, but the following should succeed in selecting them separately:
//tbody/tr/td[1]/strong

and
//tbody/tr/td[2]/strong

Note that the text() you had at the end is most likely not needed in this case.

A: Not sure this is what you're looking for... anyway, assuming you're asking to retrieve a node based on its text you can look up for text content by doing something like:
//tbody//td//strong/text()[.="Bec"]

PS
in [.=""] the dot is an alias for text() self::node() (thanks JLRishe for pointing out the mistake).

A: Not sure I understand 100%, but if you're trying to get the text of the first and the second strong tags, you can use position (1 based index)
//tbody/td[position()=1]/strong/text() //first text

//tbody/td[position()=2]/strong/text() //second text

This solution only applies to the current sample though, where your strong tags are inside either the first or second td tag.


text:
Q: Why do objects changed in function change what they point to in memory, but sometimes create a new memory object? I was reading on this blog about how if an object or array were changed inside of a function, the value in memory that was pointed to would be changed as well, the same as if it were changed outside the function.
var a = [1,2,3],
    b = a;

b[0] = 5;
console.log(a); // [5, 2, 3]

would result in the same as
var a = [1,2,3],
    b = a;

var arrayFunction = function(arr){
   arr[0] = 10;
};

var arr = arrayFunction(b);

console.log(a, b, arr) // [10, 2, 3], [10, 2, 3], [10, 2, 3];

Yet what I can't understand is why reassigning multiple array values within the function does not change the values outside of it:
var a = [1,2,3],
    b = a;

var arrayFunction = function(arr){
   arr = ["a", "b", "c"];
   return arr;
};

var result = arrayFunction(b);
console.log(result) //["a", "b", "c"]
console.log(a, b);  //[1, 2, 3], [1, 2, 3]

Why does this not change the pointed to value in memory like in the first example?
Probably a better job of writing out the examples on the JSBIN

A: This is because objects in javascript aren't really passed by reference. I've seen it referred to as "passed by copied reference", or "passed by handle" - both of which do a better job of describing what's really happening.
In this example:
var b = [1, 2, 3];
var arrayFunction = function(arr) {
   arr = ["a", "b", "c"];
};
arrayFunction(b);

The object reference itself is passed by value. You're not actually changing the value of the b variable. However, your function argument (arr) and the b variable are initially pointing to the same object - so if you change one, you can reference the object through either and see the change.
When you reassign arr to point to a different object though, the b variable is still pointing to the old object, and does not change.

A: Remember that, within the function, arr is not the actual array; arr is a reference that points to the array.
So when you say arr[0], you're retrieving the array, and then getting or updating an item in it.
But when you say arr = ["a","b","c"], you are creating a new object (on the right side) and then turning arr into a reference that points to the new object.

A: In Javascript a variable merely points to an array; so if you copy the variable you get two variables pointing to the same array:
var a = [1,2,3];
var b = a;

Changing an element of the array with a[0] = 99 will be observable with both variables because there is just one array and both a and b are pointing to it.
When you write instead
a = [5, 6, 7];

you are setting a to point to another different array.
Javascript never makes a copy of an array unless you ask it explicitly (e.g. with b = a.slice()).
Actually the very same happens with any value (objects for example). With numbers and string  the same logic is also valid, but it's hard to notice the difference between a copy and sharing the same object because numbers and strings cannot be changed (the're "immutable").
In other languages like C and C++ instead variables contain the value, not a pointer; so when making an assignment for example objects are copied from one variable to the other and if you want a pointer you've to ask explicitly for it.