text:
Q: Height of div is not being overwritten by jquery I have 2 divs that are being resized horizontally using jquery ui resizable. The top div is being resized why using the option "alsoreverseresize" on the div underneath it. Both divs have predefined heights. Once top div is resized the bottom div takes the remaining height but is being reset to its original height in a split second.
the code i am using to recalculate the height is shownbelow:
        var th =  $("#defaultPolicies").height();
        var sh = $("#sidebar").height() - (54 + 100 + th);
        $("#userPolicies").css('height', sh + "px");

(digits 54 and 100 are static paddings)
HTML :

                                    <input class="searchBox dark" type="text" name="searchHelp" id="searchHelp" value="" placeholder="Search policies...">

                        Add Policy

                            <heading class="half">Default Policies </heading>

On | Off

                            <heading class="half">Custom Policies </heading>

Drag elements to create policy

                            <heading>Apply policy to:</heading>

Websites

Applications

File Types

Exceptions

                            <heading>Set limit by:</heading>

Bandwidth Limit

Time Limit

Hits Limit

                            <heading>Notify:</heading>

Breacher

Adminstrator

                            <heading>Other:</heading>

Policy Expiry

Logging

anyone know why the height isnt being overwritten?
Thanks

A: Try using the height attribute,
$('#userPolicies').height(sh);


text:
Q: Send data from one form to another I made a secondary form named Form2 for my application in which the user can specify a Picture, Color and Text.
Now, on this Form2, after the user presses OK button, I want to send the the particulars to Form 1 and open it up.
For eg: If the user sets the color=Red, Picture=Img.gif, Text=Hi on Form2,
then the TextBox on Form1 should display Hi in red color and a picture in the PicBox in Form1.
How is the data sent form one form to another?

A: You can do it exactly the same way you would assign values from any class to any other class.
e.g.:
var form1=new Form1();
form1.SetProps(Red,img.gif,"Hi");

Where Form1 obviously needs something like:
public void SetProps(color c, ...)

You get the point.
A better way of doing that, specifically with forms is having a constructor in form2 which receives the arguments from Form1, and calling it before closing Form1:
i.e. in Form2:
var form1 = new Form1(Red,img.gif,"Hi");
this.Close();
form1.Show();

(don't get me on the syntax..)

A: This could be done in several ways. One of them could be to pass an object as parameter in the constructor of Form2. This object could be a class with some properties to store the values collected by Form2. As the object will be passed as reference from the application to Form2, the application will have available this values as soon as Form2 updates them.
Another way could be to add some public properties to Form2 to store the values collected by Form2. As Form2 is created and referenced by the application, the application should have access to those properties as long as it keeps referenced Form2.
Once the application have the values from From2, it can pass then to the another form easily.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to aggregate string column by choosing 1 of several values I have a dataset that I want to aggregate based on a string column.  Dataset is basically:
system      status
-------------------
PRE1-SYS1   SUCCESS
PRE1-SYS2   SUCCESS
PRE2-SYS1   RUNNING
PRE2-SYS2   SUCCESS
PRE3-SYS1   SUCCESS
PRE3-SYS2   <blank>

Basically, I want this to become:
system      status
-------------------
PRE1    SUCCESS
PRE2    RUNNING
PRE3    RUNNING

I have the sql needed to trim down the system values to PRE1, and PRE2, but I'm not sure how to aggregate the string function so that a system is:

*

*only SUCCESS, then status is SUCCESS

*only nulls, then status is PENDING

*any other combination, then RUNNING (SUCCESS/RUNNING, SUCCESS/null, RUNNING/null)

I've looked at LISTAGG but I don't think it applies.

A: Here is an SQL query you could use:
select   regexp_substr(system, '^[^-]*') as prefix,
         case
            when count(status) = 0 then 'PENDING'
            when count(*) = count(case when status = 'SUCCESS' then 1 end) then 'SUCCESS'
            else 'RUNNING'
         end as status
from     mytable
group by regexp_substr(system, '^[^-]*')

A: with
     inputs ( system, status ) as (
       select 'PRE1-SYS1', 'SUCCESS' from dual union all
       select 'PRE1-SYS2', 'SUCCESS' from dual union all
       select 'PRE2-SYS1', 'RUNNING' from dual union all
       select 'PRE2-SYS2', 'SUCCESS' from dual union all
       select 'PRE3-SYS1', 'SUCCESS' from dual union all
       select 'PRE3-SYS2',  ''       from dual
     ),
     prep ( system, flag ) as (
       select substr(system, 1, instr(system, '-') - 1),
              case status when 'SUCCESS' then 0
                          when 'RUNNING' then 1 else 2 end
       from   inputs
     )
select system,
       case when min(flag) = 2 then 'PENDING'
            when max(flag) = 0 then 'SUCCESS'
            else                    'RUNNING' end as status
from prep
group by system
order by system;

Output:
SYSTEM    STATUS
--------- -------
PRE1      SUCCESS
PRE2      RUNNING
PRE3      RUNNING

A: I would approach it by ranking the responses.  For example set a value to the most desired to the least desired results:
SUCCESS = 1
RUNNING = 2
<blank> = 3
PENDING = 3

Then select a min based on that.
select xval = case status when 'Success' then 1
                          when 'Running' then 2
                          when 'Pending' then 3
                                         else 3
                          end

Use a nested sub select on the value you get here so you only get one record per system.
    select System, Min(Xval)
then display the 1 as Success
             the 2 as Running
             and 3 as Pending

It is hard to do in text format, easier to do with numbers.  The numbers you assign to the string are important because they determine when you have multiple values which single one you return in your final query.

A: Another alternative.  Practically, this ends up being very similar to @trincot's solution, I'm just separating the logic for getting the counts from the logic that interprets those counts.  If your logic gets more complicated in the future, this may be a bit more flexible.
with
     inputs ( system, status ) as (
       select 'PRE1-SYS1', 'SUCCESS' from dual union all
       select 'PRE1-SYS2', 'SUCCESS' from dual union all
       select 'PRE2-SYS1', 'RUNNING' from dual union all
       select 'PRE2-SYS2', 'SUCCESS' from dual union all
       select 'PRE3-SYS1', 'SUCCESS' from dual union all
       select 'PRE3-SYS2',  ''       from dual
     ),
     /* The cnts CTE counts how many rows relate to a SYSTEM,
        how many of those are SUCCESS, and how many are NULL.
      */
     cnts( system, num_rows, num_success, num_null ) as (
       select substr(system,1,instr(system, '-')-1) system,
              count(*),
              sum(case when status = 'SUCCESS' then 1 else 0 end),
              sum(case when status is null then 1 else 0 end)
        from inputs
       group by substr(system,1,instr(system, '-')-1)
     )
/* Using the counts from the CTE, we can implement whatever logic we
   want
 */
select system,
       (case when num_rows = num_success then 'SUCCESS'
             when num_rows = num_null then 'PENDING'
             else 'RUNNING'
         end) status
  from cnts


text:
Q: Сортировка двумерного масива Есть двумерный массив полученный после распарсивания страницы
$reit[1][0]='text1';
$reit[1][1]='text2';
$reit[1][2]='text3';
$reit[1][3]='text4';

$reit[2][0]='7';
$reit[2][1]='1';
$reit[2][2]='1';
$reit[2][3]='2';

Задача отсортировать, массив по второму столбцу... пробовал через array_multisort ничего не получается...
В конце должно получится:
$reit[1][0]='text1';
$reit[1][1]='text4';
$reit[1][2]='text2';
$reit[1][3]='text1';

$reit[2][0]='7';
$reit[2][1]='2';
$reit[2][2]='1';
$reit[2][3]='1';

A: вот код
array_multisort($reit[2],SORT_DESC,$reit[1]);

выводит вот ето.
array(2) { [1]=> array(4) { [0]=> string(5) "text1" [1]=> string(5) "text4" [2]=> string(5) "text2" [3]=> string(5) "text3" } [2]=> array(4) { [0]=> string(1) "7" [1]=> string(1) "2" [2]=> string(1) "1" [3]=> string(1) "1" } }

вам так надо? потому как у вас в вопросе ошибочка походу  так как ненахожу элемента text3  в массиве $reit[1]
A: Вроде то что вам нужно
http://www.php.net/manual/ru/function.krsort.php#55577


text:
Q: Speeding up pan-sharpening with OTB plugin for QGIS (orfeo-toolbox) I use QGIS 3.6.1 with the plugin orfeo-toolbox to create a pan-sharped Landsat 8 image. I use the BundleToPerfectSensor function because calling the Pansharpening function results to the error: Inputs are not occupy the same physical space!
The problem is that execution with default parameters is extremely slow - more than 2 hours and 30 minutes (even after adding memory to the OTB plugin - 1024 mb).
How long does it take to you to create a pan-sharp Landsat 8 image using the QGIS OTB plugin?
Do you use the default settings?
My logs:

Processing algorithm…
Algorithm 'BundleToPerfectSensor' starting…
Input parameters:
{ 'inp' : 'G:/!DELETE/testing_pansharp/LC08_L1TP_160017_20180716_20180730_01_T1/LC08_L1TP_160017_20180716_20180730_01_T1_B8.TIF',
'inxs' : 'G:/!DELETE/testing_pansharp/LC08_L1TP_160017_20180716_20180730_01_T1/RGB.tif',
'out' : 'G:/!DELETE/testing_pansharp/LC08_L1TP_160017_20180716_20180730_01_T1/PAN_full.tif',
'elev.dem' : '',
'elev.geoid' : '',
'elev.default' : 0,
'mode' : 'default',
'method' : 'bayes',
'method.bayes.lambda' : 0.9999,
'method.bayes.s' : 1,
'lms' : 4,
'interpolator' : 'nn',
'fv' : 0,
'outputpixeltype' : 1
}
2019-10-17 17:20:57 (INFO): No kwl metadata found in file G:/!DELETE/testing_pansharp/LC08_L1TP_160017_20180716_20180730_01_T1/RGB.tif
2019-10-17 17:20:57 (INFO): No kwl metadata found in file G:/!DELETE/testing_pansharp/LC08_L1TP_160017_20180716_20180730_01_T1/LC08_L1TP_160017_20180716_20180730_01_T1_B8.TIF
2019-10-17 17:20:57 (INFO): Default RAM limit for OTB is 1024 MB
2019-10-17 17:20:57 (INFO): GDAL maximum cache size is 812 MB
2019-10-17 17:20:57 (INFO): OTB will use at most 8 threads
2019-10-17 17:20:57 (INFO): Reproject XS onto Pan...
2019-10-17 17:20:57 (INFO): Elevation management: setting default height above ellipsoid to 0 meters
2019-10-17 17:20:57 (INFO): Fusion of XS and Pan...
2019-10-17 17:20:57 (INFO): Bayesian fusion algorithm
2019-10-17 17:20:57 (INFO): Estimated memory for full processing: 12196.3MB (avail.: 1024 MB), optimal image partitioning: 12 blocks
2019-10-17 17:20:57 (INFO): File G:/!DELETE/testing_pansharp/LC08_L1TP_160017_20180716_20180730_01_T1/PAN_full.tif will be written in 13 blocks of 16361x1270 pixels

2019-10-17 17:32:17 (INFO): Estimation will be performed in 11 blocks of 16361x1501 pixels
2019-10-17 20:04:20 (INFO): Estimated memory for full processing: 10136.5MB (avail.: 1024 MB), optimal image partitioning: 10 blocks
2019-10-17 20:04:20 (INFO): Estimation will be performed in 11 blocks of 16361x1501 pixels
2019-10-17 22:37:53 (INFO): Estimated memory for full processing: 13226.1MB (avail.: 1024 MB), optimal image partitioning: 13 blocks
2019-10-17 22:37:53 (INFO): Estimation will be performed in 14 blocks of 16361x1179 pixels```
2019-10-18 01:14:02 (INFO): Estimated memory for full processing: 5149.29MB (avail.: 1024 MB), optimal image partitioning: 6 blocks
2019-10-18 01:14:02 (INFO): Estimation will be performed in 7 blocks of 16361x2358 pixels
Execution completed in 37821.38 seconds
Results:
{'out': 'G:/!DELETE/testing_pansharp/LC08_L1TP_160017_20180716_20180730_01_T1/PAN_full.tif'}
Loading resulting layers
Algorithm 'BundleToPerfectSensor' finished

A: RCS method (default) is fast, but poor result.
Bayes method is better, but the price to pay is the processing time.
The pansharpening application requires that the xs image is resampled on the same physical grid as pan.
The BundleToPerfectSensor performs the resampling and  the pansharpening in one pass.

A: Perhaps this is a bug because execution BundleToPerfectSensor with OTB's mapla.bat took only 359 seconds.
Here is my issue for this bug:
https://gitlab.orfeo-toolbox.org/orfeotoolbox/qgis-otb-plugin/issues/35


text:
Q: Beautifulsoup does not scrape thead in tables I tried multiple times to find theads in beautifulsoup but I was not successful. The code that I use is:
pagetable.find("thead", {'class': ''})

The purpose that I used a class with null entry is to make beautilsoup find process, independent of class tag.


text:
Q: Loop to iterate given time by 1 hour I am splitting a 24-hour timeframe API call into an hourly one. I need to create time intervals like 00:00-01:00, 01:00-02:00, ... and assign them to variables start_time and stop_time to be used in the call.
Got this so far:
date=$'20210825'

for i in {0..23}

    start_time=$(date -d $date "+ "$i"hour" +%s)"000"
    stop_time=$(date -d $date "+ "$i+1"hour" +%s)"000"

    echo $start_time
    echo $stop_time

    API call happens here inside for loop

But it complains about syntax error. Any ideas on how to correctly increment the variables?

A: You can use the following date format:
start_time=$(date -d "${date} + ${i} hour" +%s)"000"

The +1 can be done using the $((...)) syntax:
"${date} + $((i + 1)) hour"

So the script becomes:
date=$'20210825'

for i in {0..23}; do

    start_time=$(date -d "${date} + ${i} hour" +%s)"000"
    stop_time=$(date -d "${date} + $((i + 1)) hour" +%s)"000"

    echo $start_time
    echo $stop_time
    echo -e
done

Try it online!

Output:
1629849600000
1629853200000

1629853200000
1629856800000

1629856800000
1629860400000

1629860400000
1629864000000

1629864000000
1629867600000

1629867600000
1629871200000

1629871200000
1629874800000

1629874800000
1629878400000

1629878400000
1629882000000

1629882000000
1629885600000

1629885600000
1629889200000

1629889200000
1629892800000

1629892800000
1629896400000

1629896400000
1629900000000

1629900000000
1629903600000

1629903600000
1629907200000

1629907200000
1629910800000

1629910800000
1629914400000

1629914400000
1629918000000

1629918000000
1629921600000

1629921600000
1629925200000

1629925200000
1629928800000

1629928800000
1629932400000

1629932400000
1629936000000

A: This is what I did in the past for similar scenario:
year='2021'
month='08'
date='25'
for i in {0..23}
do
    end=$(($i + 1))
    start_time=$(date -v ${year}y -v ${month}m -v${date}d -v${i}H -v0M -v0S +%s)"000"
    stop_time=$(date -v ${year}y -v ${month}m -v${date}d -v${end}H -v0M -v0S +%s)"000"

    echo $start_time
    echo $stop_time
done

*

*Added do / done statements to for loop

*Used -v to adjust each date part

A: As long as the time intervals are within the same day, there is no need to call date multiple times. Just call it once to get the baseline, then add to that.
baseline=$(date -d 2021-08-25 +%s)

for((i=0; i<24*3600; i += 3600)); do
    start_time=$((baseline+i))"000"
    stop_time=$((baseline+i+3600))"000"
    printf '%s\n' "$start_time" "$stop_time"
done

I'm wondering if the stop time shouldn't be the start time plus 3599.999, though.
This "C-style" for loop syntax is a Bash extension, and not portable to POSIX sh etc.


text:
Q: Telegram bot: Show full text as ReplyKeyboardMarkup button I'm working on a Poll-like Bot where I want to show the choices as buttons.
Some choices consist of 10 or more words.
When I but that text in as a button, the middle words converted to dots.
i.e:
"We have the capacity to receive messages from the stars and the songs of the night winds."
When I put this as a button, it will show like this:
"We have the capacity to ... of the night winds".
Is there any workaround?

A: i suggest you; using of command instead of reply keyboard.
you can easily add slash and number to beginning of your choices, so user can click on it:
/1 We have the capacity to receive messages from the stars and the songs of the night winds.
/2 We have not the capacity to receive messages from the stars and the songs of the night winds.
/3 test test test
/4 example example example

the /1, /2, /3 and /4 will convert to link and convert to clickable text.


text: Q: Overlay without compositing Is it possible to create a transparent screen overlay on linux over a x11 desktop for drawing primitives with compositor disabled? I've seen some questions on google already but they were only talking about X11/Xlib. However maybe it's possible with openGL/vulkan or more low level stuff.


text:
Q: Clearing input field in JavaScript after click event I made a simple list items page with JavaScript. And everything works just as expected. What I want is that, every time I add a new list-item, the input field should be cleared. As in the value should be deleted.

function addItem() {

  if (document.querySelector('.text-input').value) {

    const listItem = document.createElement('li');
    listItem.className = 'list-item'
    var input = document.querySelector('.text-input').value;
    listItem.textContent = input;
    document.querySelector('.list').appendChild(listItem);
    document.querySelector('.text-input').value = '';

  }

}

document.getElementById('btn').addEventListener('click', addItem);

And I actually achieved what I wanted with that last line of code in the addItem callback function. However instead of writing document.querySelector('.text-input').value = '';, if I write input = '';, it doesn't work. And this is not making any sense to me cause I declared that variable within that function and also used it for listItem.textContent = input; as you can see.

A: Because this var input = document.querySelector('.text-input').value it's a variable declaration initialized with a value.  Doing this input = '' is only re-assigning another value.  You're confused about referencing the attribute value.
What you probably want to do is:
const listItem = document.createElement('li');
listItem.className = 'list-item'

var input = document.querySelector('.text-input'); // Get a reference of element text-input

listItem.textContent = input.value; //Use the current value of text-input.
document.querySelector('.list').appendChild(listItem);

input.value = ''; // Modify the value of the text-input's reference.


text:
Q: MLP running but not learning I am currently trying to implement a MLP by hand, with ReLU activations for each hidden layer and a softmax activation for the output layer. The MLP is running but it is not learning from its training, but i cant seem to find the issue with my backpropagation.
The important functions are forward and backward which seem correct to me. I am pretty new to pytorch, so sorry in advance if there are blatant mistakes, i am still learning.
Here is the corresponding code
import torch
def inputs_tilde(x, axis=-1):
    # augments the inputs `x` with ones along `axis`
    # todo : implémenter code ici.
    pad = [0 for i in range(2 * len(x.size()))]
    pad[-(2 * axis + 1)] = 1
    x_tilde = torch.nn.functional.pad(x,pad, "constant", 1)
    return x_tilde

def softmax(x, axis=-1):
    # assurez vous que la fonction est numeriquement stable
    # e.g. softmax(np.array([1000, 10000, 100000], ndim=2))

    # todo : calcul des valeurs de softmax(x)

    scaled =  x - x.max()

    exp = torch.exp(scaled)
    values = exp / exp.sum()
    if not torch.allclose(values.sum(),torch.tensor(1.000)):
        raise BaseException(values.sum())
    return values

def cross_entropy(y, y_pred):
    # todo : calcul de la valeur d'entropie croisée.
    eps = 10**-6
    loss = (y * torch.log(y_pred + eps) + (1 - y) * torch.log(abs(1 - y_pred) + eps)).sum()
    return loss

def softmax_cross_entropy_backward(y, y_pred):
    # todo : calcul de la valeur du gradient de l'entropie croisée composée avec `softmax`
    values = (y_pred - y)

    # gradients were chosen as vertical for convention
    return values[:,None]

def relu_forward(x):
    # todo : calcul des valeurs de relu(x)
    values = x.clone()
    values[values < 0] = 0
    return values

def relu_backward(x):
    # todo : calcul des valeurs du gradient de la fonction `relu`
    values = x.clone()
    values[values >= 0] = 1
    values[values < 0] = 0
    return values

class MLPModel:
    def __init__(self, n_features, n_hidden_features, n_hidden_layers, n_classes):
        self.n_features        = n_features
        self.n_hidden_features = n_hidden_features
        self.n_hidden_layers   = n_hidden_layers
        self.n_classes         = n_classes

        # todo : initialiser la liste des paramètres Teta de l'estimateur.

        self.params = []
        self.params.append(torch.normal(0, 0.01, (n_hidden_features, n_features + 1)))

        for l in range(0, n_hidden_layers):
            self.params.append(torch.normal(0, 0.01, (n_hidden_features, n_hidden_features+1)))

        self.params.append(torch.normal(0, 0.01, (n_classes,n_hidden_features + 1)))

        print(f"Teta params={[p.shape for p in self.params]}")

        self.a = [] # liste contenant le resultat des multiplications matricielles
        self.h = [] # liste contenant le resultat des fonctions d'activations

    def forward(self, x):
        # todo : implémenter calcul des outputs en fonction des inputs `x`.

        outputs = torch.empty(x.size()[0],self.n_classes)

        for k in range(x.size()[0]):
            out = x[k][:,None]
            # h = torch.empty(self.n_hidden_layers,self.n_features+1,self.n_features)
            # a = torch.empty(self.n_hidden_layers,self.n_features+1,self.n_features)

            h = [0] * (self.n_hidden_layers + 2)
            a = [0] * (self.n_hidden_layers + 2)

            h[0] = out

            for i in range(self.n_hidden_layers+1):
                out = torch.matmul(self.params[i],inputs_tilde(out,0))
                a[i] = out
                out = relu_forward(out)
                h[i+1] = out

            out = torch.matmul(self.params[-1],inputs_tilde(out,0))
            a[-1] = out
            self.a.append(a)
            self.h.append(h)
            out = softmax(out)
            outputs[k] = out.squeeze(1)

        return outputs

    def backward(self, y, y_pred):
        # todo : implémenter calcul des gradients.

        b_size = y.size()[0]
        grads = []
        for i in range(self.n_hidden_layers):
            grads.append(torch.empty([b_size] + [ s for s in self.params[1].size()]))

        grads.append(torch.empty([b_size] + [ s for s in self.params[-1].size()]))

        smloss = softmax_cross_entropy_backward(y,y_pred)

        for k in range(y.size()[0]):

            g = smloss[k]
            g = g.transpose(0,1)

            grads[-1][k] = torch.matmul(g,inputs_tilde(self.h[k][-1],0).transpose(0,1))

            for i in range(self.n_hidden_layers,0,-1):

                g = torch.matmul(self.params[i+1].transpose(0,1)[:-1],g  * relu_backward(self.a[k][i]))
                grads[i][k] = torch.matmul(g,inputs_tilde(self.h[k][i],0).transpose(0,1))

            g = torch.matmul(self.params[1].transpose(0,1)[:-1],g * relu_backward(self.a[k][0]))
            grads[0][k] = torch.matmul(g,inputs_tilde(self.h[k][0],0).transpose(0,1))

        return grads

    def sgd_update(self, lr, grads):
        # TODO : implémenter mise à jour des paramètres ici.
        avg_grads = [g.mean(dim=0) for g in grads]

        for i in range(len(self.params)):
            self.params[i] -= lr * avg_grads[i]

def train(model, lr=0.1, nb_epochs=10, sgd=True, data_loader_train=None, data_loader_val=None):
    best_model = None
    best_val_accuracy = 0
    logger = Logger()

    for epoch in range(nb_epochs+1):

        # at epoch 0 evaluate random initial model
        #   then for subsequent epochs, do optimize before evaluation.
        if epoch > 0:
            for x, y in data_loader_train:
                x, y = reshape_input(x, y)

                y_pred = model.forward(x)
                grads  = model.backward(y, y_pred)

                model.sgd_update(lr, grads)

        accuracy_train, loss_train = accuracy_and_loss_whole_dataset(data_loader_train, model)
        accuracy_val, loss_val = accuracy_and_loss_whole_dataset(data_loader_val, model)

        if accuracy_val > best_val_accuracy:
            # TODO : record the best model parameters and best validation accuracy
            best_model = model
            best_val_accuracy = accuracy_val

        logger.log(accuracy_train, loss_train, accuracy_val, loss_val)
        print(f"Epoch {epoch:2d}, \
                Train:loss={loss_train.item():.3f}, accuracy={accuracy_train.item()*100:.1f}%, \
                Valid: loss={loss_val.item():.3f}, accuracy={accuracy_val.item()*100:.1f}%", flush=True)

    return best_model, best_val_accuracy, logger


text:
Q: Bluetooth discovery not working when screen is off I am working in a application where we need to make some bluetooth scans while the screen is turned off. I set up the receivers using a foreground service that runs every minute using the AlarmManager class. The thing is that with my Oneplus 6 (Android version 9.0), it doesn't run with the screen off but when the screen is on everything works perfectly fine.
Do you know if it is something related with the Android version?
If you need more part of the code just tell me.
Thanks!
Here is where I register the receiver

public void registerReceivers(Context context) {

            IntentFilter intentFilter = new IntentFilter();

            intentFilter.addAction(BluetoothDevice.ACTION_FOUND);

            intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

            context.registerReceiver(btReceiver,intentFilter);

}

Then here is how I start the discover after I register the receiver

public void startScan(Context context){

    registerReceivers(context)

    btReceiver.startScan(context);

}

Where btReceiver is the following object

public class BtReceiver extends BroadcastReceiver {

    //BtConn is an object that store some information about the founded device

    public final List<BtConn> btConns;

    public  BluetoothAdapter bluetoothAdapter;

    public BtReceiver() {

        super(ScanType.BLUETOOTH);

        this.btConns = new ArrayList<>();

        this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    }

    @Override

    public void onReceive(Context context, Intent intent) {

        String action =intent.getAction();

        //Case when a device has been found

        if (BluetoothDevice.ACTION_FOUND.equals(action)) {

            //Getting device values

            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            String deviceName = device.getName();

            String macAddress = device.getAddress();

            int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);

            //Checking if it is a Phone by default is True

            boolean isMobile = true;

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {

                isMobile = BluetoothDevice.DEVICE_TYPE_CLASSIC == device.getType();;

            }

            //adding object to list

            if(deviceName != null && deviceName.length() > 0) { btConns.add(new BtConn(deviceName,rssi, macAddress,isMobile)); }

            return;

        }

        if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { scanFinished(context);return; }

    }

    public void startScan(Context context) {

        this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        bluetoothAdapter.startDiscovery();

    }

    public void scanFinished(context) {

        //Here there is some stuff to upload the information to the database

    }

}

Then in the onStartCommand of my Service I run:

public int onStartCommand(Intent intent, int flags, int startId) {

    startForeground(ID_NOTIFICATION, myCustomNotification()));

    startScan(this);

    return START_STICKY;

}

[EDIT]
I have tried, using handlers instead the AlarmManager but it has the same behaviour. When the screen is off, once I call the startDiscovery method it doesn't seem to be working. Also, instead of using the discovery method I have tested with the BLE scan. This kind of scan works when the screen goes off, but I want to find other Android devices so is useless...

A: You may be experiencing your AlarmManager being suspended when the Android goes into Doze mode.  Android 6 introduced Doze for screen off motionless phones and Android 7 introduced a light Doze mode that starts just a few seconds after the screen going off even if the phone is not motionless (e.g. in your pocket).
If this is the issue, the best way to avoid it is to stop using the AlarmManager for timed processing. Consider using a Handler with postDelayed, which is not affected by Doze.  If you must use AlarmManager, see here for possible kludges to force them to fire.  The Android Beacon Library, for example,  uses Handlers to cycle scans even in Doze mode.
OnePlus also has some proprietary battery saving features which will ultimately kill your foreground service after extended app running time.  But it sounds like that is not the problem you are facing just yet..


text:
Q: How to check if there's a record in every hour in specified time-frame and then count it? I'm using PostgreSQL and this is my table measurement_archive:
+-----------+------------------------+------+-------+
| sensor_id | time                   | type | value |
+-----------+------------------------+------+-------+
| 123       | 2017-11-26 01:53:11+00 | PM25 | 34.32 |
+-----------+------------------------+------+-------+
| 123       | 2017-11-26 02:15:11+00 | PM25 | 32.1  |
+-----------+------------------------+------+-------+
| 123       | 2017-11-26 04:32:11+00 | PM25 | 75.3  |
+-----------+------------------------+------+-------+

I need a query that will take records from specified timeframe (eg. from 2017-01-01 00:00:00 to 2017-12-01 23:59:59) and then check if in every hour there is at least 1 record - if there is, then add 1 to result.
So, if I make that query from 2017-11-26 01:00:00 to 2017-11-26 04:59:59+00 for sensor_id == 123 on above table then the result should be 3.

A: select count(*)
from (
    select date_trunc('hour', time) as time
    from measurement_archive
    where
        time >= '2017-11-26 01:00:00' and time < '2017-11-26 05:00:00'
        and
        sensor_id = 123
    group by 1
) s

A: alternative solution would be using distinct,
select count(*) from (select distinct a, extract(hour from time) from t where time >'2017-11-26 01:00:11' and time <'2017-11-26 05:00:00' and sensor_id=123)t;


text:
Q: How to get the value of a handler/runnable timer? I'm currently using a runnable and handler to have a timer which updates a textview every second.
public class TimerFragment extends Fragment {

    TextView tvTimer;
    long startTime = 0;
    Handler timerHandler = new Handler();
    Runnable timerRunnable = new Runnable() {
        @Override
        public void run() {
            long millis = System.currentTimeMillis() - startTime;
            int seconds = (int)(millis/1000);
            int minutes = seconds / 60;
            seconds = seconds % 60;
            tvTimer.setText(String.format("%d:%02d", minutes, seconds));
            timerHandler.postDelayed(this,500);
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_timer, null);

        tvTimer = (TextView)view.findViewById(R.id.tvTimer);
        Button btn = (Button)view.findViewById(R.id.btn1);

        btn.setText("Start");
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Button b = (Button) v;

                if (b.getText().equals("Stop")){
                    timerHandler.removeCallbacks(timerRunnable);
                    b.setText("Start Monitoring");
                }

                else {
                    startTime = System.currentTimeMillis();
                    timerHandler.postDelayed(timerRunnable, 0);
                    b.setText("Stop");
                    Toast.makeText(getActivity(),"Monitoring started.",Toast.LENGTH_SHORT).show();
                }
            }
        });
        return view;
    }
}

How do i get the value of the timer? Like for example, showing a toast when the text becomes "0:15". I want to be able to get the value so I can use it. The function I have in mind is having the user set a time and have a toast or notification pop up when the timer passes through that time (like 15 or 30 seconds). But right now what I want to know is how to get the value of the timer. Thanks!

A: You should use a CountDownTimer to set a countdown based on interval set by you and it will stop when the time has come in future
 CountDownTimer(long millisInFuture, long countDownInterval)

  // Example : I've set countdown for 30 seconds

CountDownTimer countDownTimer = new CountDownTimer(30000, 1000) {
                public void onTick(long millisUntilFinished) {
                    text_view.setText(millisUntilFinished / 1000 + " " + "Sec");
                }

                public void onFinish() {
// implement your code customization here after interval is over
                    text_view.setText("time over!");
                }
            }.start();

For more insights refer the Android Developer reference for CountDownTimer


text:
Q: MySQL difference between wait_timeout and connect_timeout I have a my.cnf file. In it I see wait_timeout as well as connect_timeout. What's the difference between these 2?

A: Right from the MySQL Documentation

*

*wait_timeout : The number of seconds the server waits for activity on a noninteractive connection before closing it.

*connect_timeout : The number of seconds that the mysqld server waits for a connect packet before responding with Bad handshake

EXAMPLES

*

*If wait_timeout is 1800 (30 Minutes), the DB Connection will close in 30 minutes if the connection is idle (indicated by Sleep in the command column of the processlist).

*If connect_timeout is 10, then mysqld will reject you if you cannot login (authenticate) in 10 seconds.

A: wait_timeout is how long to keep a connection as idle state. connect_timeout is how long to wait for a connection to be made.
This is my best understanding, please comment or edit as needed.


text:
Q: Unable to open twitter bootstrap modal after complete ajax request asp.net mvc $("#find").click(function () {
    var url = "/Home/SendMessage/" + $(this).val('email');

    $.ajax({
        type: 'GET',
        url: url,
        success: function (data) {
            $("#myModal").modal("show");
        },
        error: function (xhr, status, error) {
            alert(error);
        },
        dataType: 'text'
    });
});

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal title

                You have just signed up for beta access!!

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>

After the success of ajax request nothing happens have checked through firebug as well.


text:
Q: AJAX doesn't show image but shows the PHP database query Can anybody help with this I'm having trouble showing the image from a page but the sql query shows the sting just fin this is the code
CODE FOR THE JQUERY(Note: this is a click then load into a targeted spot)

This is the code for the page that the jquery tries to show
CODE
<?php
 $result = mysql_query("SELECT * FROM products WHERE ID='6'");
                            while($row = mysql_fetch_array($result))
                                {echo"

                                            Product: ".$row['Product']."

And this is the code for the page where the navigation for the ajax is
code

                    Products

                                Catia

And this is the body where the ajax will display the page
Code

a

A: This isn't a complete answer yet as I don't really have enough information to go on.
I assume you're having trouble with this line:

If so, please make the following modification and let me know what it prints out:
##".$row['Logo']."##

Note that I added ##".$row['Logo']."## so that you can see what $row['Logo'] contains.


text:
Q: MSP430 Timer Interrupt Not Happening I recently starting learning how to program a MSP430 and thought I'd start by writing a program to turn a LED on and off every second. However, when I run my code the LED goes on an stays on. When I try stepping through my program, it seems like after going into low power mode the MSP430 never enters the interrupt service routine. Below is my code.
#include <msp430.h>

/**
 * main.c
 */
int main(void)
{
    WDTCTL = WDTPW | WDTHOLD;   // stop watchdog timer

    //set clock to 1 MHz and to use DCO
    DCOCTL = DCO1 + DCO0;
    BCSCTL1 = 7;//RSEL0 + RSEL1 + RSEL2;
    BCSCTL2 = DIVS0 + DIVS1; //SMCLK = MCLK / 8, everything else 0 so it uses DCO as source

    //timer settings
    TA0CTL = TASSEL1 + ID1 + ID0 + MC1 + TACLR; //set SMCLK as source, divide source by 8, set to continuous mode, enable interrupts
    TA0CCTL1 &= ~CAP; //set CAP to 0 for compare mode
    TA0CCTL1 |= CCIE; //enable interrupts

    TA0CCR1 = 15625; //1usec * 8 * 8 * 15625 should give an interrupt once a second

    //set pin 1 for output
    P1DIR = BIT0;

    //enable interrupts globally
    //_BIS_SR(CPUOFF + GIE);
    //GIE;
    _EINT();
    LPM0;
}

#pragma vector = TIMER0_A1_VECTOR
__interrupt void Timer_A (void) {
    TA0CCR1 += 15625;
    TA0CCTL1 &= ~CCIFG;
    P1OUT ^= BIT0;
}

As you can see, I've tried a few methods of enabling interrupts globally and entering low power mode at the end of the main fuction, but they all produced the same result. When I try to suspend the program in Code Composer Studio nothing happens and I have to terminate it, which makes it hard to troubleshoot the program.

A: You didn't post the processor, so I'll assume MSP430G2553. The TACCR1 (and the others) works differently than TACCR0. The TI user guide says "Any access, read or write, of the TAIV register automatically resets the highest pending interrupt flag" for it. Since your code does not read (or write) to the TAIV register inside the interrupt routine, then it will be stuck with the interrupt flag set but never clearing, so then it will never retrigger again. To fix this problem you can add the following TA0IV read since you don't currently use the other interrupt sources for TIMER0_A1_VECTOR:
#pragma vector = TIMER0_A1_VECTOR
__interrupt void Timer_A (void) {
    if (TA0IV == TA0IV_TACCR1) { // add read to TA0IV register to clear interrupts
        TA0CCR1 += 15625;
        TA0CCTL1 &= ~CCIFG;
        P1OUT ^= BIT0;
    }
}


text:
Q: Table view Controller duplicate itself in IOS swift I try to pass value one table view controller to another view controller but second table view controller duplicate itself it opens twice. Could you help me fix about it i pasted my code here
Here is the first table view controller codes
    var dataPassed:String!
    var  cars = [String]()

    var valueToPass:String!
    var passedValue:String!

override func viewDidLoad() {
    super.viewDidLoad()

      cars = [dataPassed,"Audi","Volkswagen"]

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return cars.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("carCell", forIndexPath: indexPath) as! UITableViewCell

    cell.textLabel!.text = cars[indexPath.row]
    return cell

}

override func tableView(tableView: (UITableView!), didSelectRowAtIndexPath indexPath: NSIndexPath) {

    // Get Cell Label
    let indexPath = tableView.indexPathForSelectedRow();
    let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;

    valueToPass = currentCell.textLabel!.text
    performSegueWithIdentifier("secondide", sender: self)

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if (segue.identifier == "secondide") {

        // initialize new view controller and cast it as your view controller
        var viewController = segue.destinationViewController as! SecondTableViewController
        // your new view controller should have property that will store passed value
        viewController.value123 = valueToPass
    }

}

Here is the second table view controller codes.
var SecondArray=[String]()
var value123:String!

override func viewDidLoad() {
    super.viewDidLoad()

        SecondArray = ["Kemal","Ekren","Hello"]

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return SecondArray.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("SecondCell", forIndexPath: indexPath) as! UITableViewCell

        cell.textLabel!.text = SecondArray[indexPath.row]
        return cell

}

}

A: It sounds as if you have a segue in your Storyboard created by dragging between the first table view and the second tableview. This will cause the segue to trigger twice; once from the automatic segue and then secondly when you call performSegueWithIdentifier:sender:.
The way I would write this is to delete yourtableView:didSelectRowAtIndexPath: method then alter your prepareForSegue:sender: method to be something similar to this:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject? {

    // Find the correct segue
    if (segue.identifier == "secondide") {

        // initialize new view controller and cast it as your view controller
        var viewController = segue.destinationViewController as! SecondTableViewController

        // Find the index path of the selected row
       let selectedIndex = self.tableView.indexPathForCell(sender as UITableViewCell)

        // your new view controller should have property that will store passed value
        viewController.value123 = cars[selectedIndex]
    }
}

Then ensure the segue is created by control-dragging from the first table view to the second view controller. This will trigger the segue as soon as someone taps a cell.
You will also no longer need your var valueToPass:String! property.


text:
Q: Improperly configured error when running django-admin check I'm relatively new to Django and programming, so I have no idea what caused this error or how to fix it.  I asked another question related to the same error but got no responses so here's a simpler version.
When I run Django-admin check (along with various other commands not including run server) I get the following error.
django.core.exceptions.ImproperlyConfigured: Requested setting LANGUAGE_CODE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

I have spent hours googling and nothing I find works (I either get this error or a module not found error).  What can I do?
here's the full traceback:
Traceback (most recent call last):
File "/Users/linnea/opt/miniconda3/bin/django-admin", line 8, in <module>
sys.exit(execute_from_command_line())
File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute
output = self.handle(*args, **options)
File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/management/commands/check.py", line 69, in handle
databases=options['databases'],
File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/management/base.py", line 396, in check
databases=databases,
File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/checks/registry.py", line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/checks/translation.py", line 60, in check_language_settings_consistent
get_supported_language_variant(settings.LANGUAGE_CODE)
File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/conf/__init__.py", line 83, in __getattr__
self._setup(name)
File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/conf/__init__.py", line 68, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting LANGUAGE_CODE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

Edit: I get the module not found error (no module named ) when I set the Django settings module

A: The problem is that Django cannot find your settings.py file to run the app. You need to set the environment variable DJANGO_SETTINGS_MODULE to point to you settings.py or if you're using an IDE just add it to your project config.


text:
Q: project euler question7 in python my prime function is working fine for numbers greater than 3,i have accounted for that in loop folowing afterward,question is to find 10001st prime
but i am getting wrong answer that is a prime number but not the 10001st,should be 104743
def pr(n):
    for i in range(2,int(n**(0.5))+1):
        if n%i==0:

        return False
        break
    else:
        return True
num = 3
count = 2
while count < 10001:
    num += 1
    x = pr(num)
    if x == True:
        count += 1

print num

A: try;
def pr(n):
    if n%2 == 0:
        return False
    for i in range(3,int(n**(0.5))+1,2):
        if n%i==0:
            return False
    return True

A: def pgen(): # Sieve of Eratosthenes generator
    yield 2
    np_f, q = {}, 3
    while True:
        f = np_f.pop(q, None)
        if f:
            np = q + f
            while np in np_f:
                np += f
            np_f[np] = f
        else:
            yield q
            np_f[q*q] = q+q
        q += 2

>>> p = pgen()
>>> [next(p) for i in xrange(10001)][-1]
104743


text:
Q: Xamarin iOS button width change according to text I have a multi-lingual app and text size can vary according to language.
What i am trying to achieve is resize the button according to space text has taken. Text will only be a one word so width of button will never become so large that it goes out of the screen boundaries.
Is there a way in Xamarin iOS to do it ?

A: Have you tried just doing something like this:
var button = new UIButton();
button.SetTitle("Some text", UIControlState.Normal);
button.SizeToFit();
View.AddSubview(button);


text:
Q: Filter options "Newest" and "Added" in Saves seem counter-intuitive While using the recently saved question/answer, the filter option "Newest" actually refers to the time when the question/answer is created rather than the "newest question" I, as a user, added to my "Saves" list. And the "Added" option is actually what I'm expecting.
This is so counter-intuitive to a normal user expectation. "Newest" option should be the latest entry to the list (i.e. current "Added" option), as most other Internet sites.
I personally don't find much value from the current "Newest" option where I get to look up Saves for the creation time. I don't care about when it was created, I only want the solution from it, hence, better to name the current "Added" option to "Newest".

A: The new Saves feature is great. I'll describe just two ways I make use of Added and Newest.
I regularly add questions to my Saves, but I may not answer immediately.
My regular use of Added is to look at Saves that I have not touched in a while. In an effort to remove them from Saves, answer them, do research in preparation to answer, or refresh the Added time by un-saving/re-saving.
My regular use of Newest is to save any recent questions matching my tags, then systematically answer or eliminate them. I could possibly use Added to do this, but it wouldn't be as precise. Another use is to review older questions regardless of when I added them to Saves.


text:
Q: "file too short" on bundle install I'm getting occasional "file too short" messages when running bundle exec rake:
rake aborted!
/var/lib/jenkins/.rvm/gems/ruby-1.9.3-p327/bundler/gems/amatch-0f95f4ce269f/lib/amatch_ext.so:     file too short - /var/lib/jenkins/.rvm/gems/ruby-1.9.3-p327/bundler/gems/amatch-0f95f4ce269f/lib/amatch_ext.so

*

*Is there a way to make bundler more fault-tolerant and try to re-run when it encounters these spurious failures?

*Why might they be happening in the first place?  Multiple processes may be executing rake tasks simultaneously - can this corrupt rvm's gem repository, and if so how do I avoid the problem?

A: if you use it in multiple processes then use bundle --standalone - assuming every process is ran from different path - if they all use the same path then you could try bundle --path /path/for/gems$$/ the $$ will be replaced with process pid - but --path is recorded option and this will not help as only the last run will be visible in this directory.
best would be to limit amount of runs that are performed at the same time.
other option would be modifying GEM_HOME at runtime, but this can get complicated with jenkins so most likely this would not work:
OLD_GEM_HOME=$GEM_HOME
GEM_HOME=$( mktemp -d )
cp -r $OLD_GEM_HOME/ $GEM_HOME/
bundle install
# other commands
rm -rf $GEM_HOME/
GEM_HOME=$OLD_GEM_HOME


text:
Q: using all the constants with a pattern in QtCreator or vim I use vim or QtCreator as my C++ editors, my problem is the following:
suppose that in the library that I'm currently using there are a lot of constants in the form NUMBER_OF_<something> like NUMBER_OF_PLANETS_IN_THE_UNIVERSE, NUMBER_OF_ATOMS_IN_THINGS, NUMBER_OF_WEBSITES ... you get the idea ...
now, I have a lot of this constants in my library and I would like to use the ones that are fitting a specific pattern as argument of the same method over and over, like so
std::cout << "NUMBER_OF_*" << NUMBER_OF_* << "\n"

there is an easy way to do this without going nuts in QtCreator and/or Vim ?

A: In vim, you can do something like:
:r!grep 'define \<NUMBER_OF' files.where.are.the.constants.h

then you can delete de lines you don't want, mark the input block with SHIFT-V and
:'<'>s,#define *\(\<NUMBER_OF.*\>\).*,    std::cout << "\1" << \1 << "\\n",g


text:
Q: How can I retrieve all the VPC custom images that have a specific tag with terraform? I have a list of custom images in my account.
In my terraform template, I'd like to retrieve an image with a specific tag. I don't want to hardcode or pass the image ID to the terraform template, I want to reference a tag like version:1.0 instead. I could not find how to do it with data ibm_is_image.

A: Using a combination of ibm_is_images to retrieve all images and ibm_resource_tag to retrieve the tags associated to one image, you can filter to find the image you are looking for.
Here is an example. It assumes that you have several images in your custom image library and that these images have been tagged version:1.0 and version:2.0
variable "ibmcloud_api_key" {}
variable "region" { default = "us-south" }

terraform {
  required_providers {
    ibm = {
      source = "IBM-Cloud/ibm"
    }
  }
  required_version = ">= 1.1.8"
}

provider "ibm" {
  ibmcloud_api_key = var.ibmcloud_api_key
  region           = var.region
}

data "ibm_is_images" "images" {
  visibility = "private"
}

data "ibm_resource_tag" "image_tag" {
  for_each = { for image in data.ibm_is_images.images.images : image.id => image.crn }

  resource_id = each.value
}

locals {
  // create an array with all images and their tags
  all_images = [ for image in data.ibm_is_images.images.images : {
    id: image.id,
    name: image.name
    crn: image.crn
    tags: data.ibm_resource_tag.image_tag[image.id].tags
  }
  ]
}

output "all_images" {
  value = local.all_images
}

output "all_v1_images" {
  value = [ for image in local.all_images: image if contains(image.tags, "version:1.0") ]
}

output "all_v2_images" {
  value = [ for image in local.all_images: image if contains(image.tags, "version:2.0") ]
}


text:
Q: Im having problems to retrieve the data attributes I'm trying to retrieve the data attributes from the cart but it's not working.
I also would like to know if there's a way to shorten the code.
HTML:

Lagavulin 16 Year Old

    <button class="add-to-cart"
            data-product-id="1"
            data-product-title="Lagavulin 16 Year Old" data-category="Scotch">
            Add To Cart
    </button>

Vanilla js:
function onPageLoad(event) {
  var title = document.getElementsByTagName("title")[0].innerText;
  console.log({
    event_name: "page loaded",
    page_title: title,

  });
}

var photo = document
  .getElementsByClassName("add-to-cart")
  .getAttribute("data-product-id");

for (var i = 0; i < photo.length; i++) {
  photo[i].onclick = function() {
    console.log({
      event_name: "add_to_cart",
      product_id: data-product-id,
      product_title: data-product-title,
    });
  }
};

A: This should work:

Array.from(document.getElementsByClassName("add-to-cart")).forEach(x => x.onclick = () => console.log({
  event_name: "add_to_cart",
  product_id: x.getAttribute("data-product-id"),
  product_title: x.getAttribute("data-product-title")
}));
<button class="add-to-cart" data-product-id="1" data-product-title="Lagavulin 16 Year Old" data-category="Scotch">Add To Cart</button>

<button class="add-to-cart" data-product-id="2" data-product-title="Some other Scotch" data-category="Scotch">Add To Cart</button>

You were not properly iterating over the elements returned by getElementsByClass and also not using element.getAttribute("") correctly.
To make it shorter I used streams.

A: Try this way:
var photo = document
  .getElementsByClassName("add-to-cart");

for (var i = 0; i < photo.length; i++) {
  photo[i].onclick = function() {

    console.log({
      event_name: "add_to_cart",
      product_id: photo[i].getAttribute("data-product-id"),
      product_title:  photo[i].getAttribute("data-product-title"),
    });
  }
};

A: Try this
var photo = document.querySelectorAll('.add-to-cart');
photo.forEach(function(button){
    button.addEventListener('click',function(){
        console.log(this.getAttribute('data-product-id'));
    },{passive:true});
});

A: No need for loops. Target the button and then destructure the data attributes (note: hyphenated attributes like data-product-id will be represented in camelCase in the data set: productId, for example), and class name from the button, relabel them, and then assign the values to a new object.

const button = document.querySelector('.add-to-cart');
button.addEventListener('click', handleClick, false);

function handleClick() {

  const {
    className: event_name,
    dataset: {
      productId: product_id,
      productTitle: product_title
    }
  } = this;

  const obj = { event_name, product_id, product_title };

  console.log(obj);

}

Lagavulin 16 Year Old

  <button class="add-to-cart" data-product-id="1" data-product-title="Lagavulin 16 Year Old" data-category="Scotch">Add To Cart</button>


text:
Q: react $ doesn't seem to work   alert('Save ${this.state.course.title}');

the above dons't seems to work , am i doing some think wrong?
i have listed the full code which should just display the text entered in the text box in the dialog when save is clicked
import React, {PropTypes} from 'react';

class CoursePage extends React.Component{

  constructor(props, context){
    super(props,context);

    this.state = {
      course: {title: "" }
    };

    this.onTitleChange = this.onTitleChange.bind(this);
    this.onClickSave = this.onClickSave.bind(this);
  }

  onTitleChange(event){
      const course = this.state.course;
      course.title = event.target.value;
      this.setState({course: course});
  }

  onClickSave(){
    alert('Save ${this.state.course.title}');
  }

  render(){
    return (

Courses

Add Course

        <input
          type="text"
          onTitleChange={this.onTitleChange}
          value={this.state.course.title} />

        <input
          type="submit"
          value="Save"
          onClick={this.onClickSave} />

    );
  }
}

export default CoursePage;

and also this doesn't allow me to enter an test , is this because of course: {title: "" } ?
i am trying learn react / redux

A: Template strings use back quotes:
alert(`Save ${this.state.course.title}`);

A: i changed
onTitleChange={this.onTitleChange}

to
onChange={this.onTitleChange}

Duh!


text:
Q: Securely generating a uniformly random BigInteger I want to securely generate a random number in the range [0, N), where N is a parameter. However, System.Security.Cryptography.RandomNumberGenerator only provides a GetBytes() method to fill an array with random values.
(I need the random integers for nonces used in a slightly modified version of SRP. The "slightly modified" part is out of my control, and the only reason I'm even touching crypto stuff.)
I have written a method to do this, but I'm looking for a better way or at least confirmation that I'm doing it right.
using System.Numerics

///<summary>Generates a uniformly random integer in the range [0, bound).</summary>
public static BigInteger RandomIntegerBelow(this System.Security.Cryptography.RandomNumberGenerator source, BigInteger bound) {
    Contract.Requires<ArgumentException>(source != null);
    Contract.Requires<ArgumentException>(bound > 0);
    Contract.Ensures(Contract.Result<BigInteger>() >= 0);
    Contract.Ensures(Contract.Result<BigInteger>() < bound);

    //Get a byte buffer capable of holding any value below the bound
    var buffer = (bound << 16).ToByteArray(); // << 16 adds two bytes, which decrease the chance of a retry later on

    //Compute where the last partial fragment starts, in order to retry if we end up in it
    var generatedValueBound = BigInteger.One << (buffer.Length * 8 - 1); //-1 accounts for the sign bit
    Contract.Assert(generatedValueBound >= bound);
    var validityBound = generatedValueBound - generatedValueBound % bound;
    Contract.Assert(validityBound >= bound);

    while (true) {
        //generate a uniformly random value in [0, 2^(buffer.Length * 8 - 1))
        source.GetBytes(buffer);
        buffer[buffer.Length - 1] &= 0x7F; //force sign bit to positive
        var r = new BigInteger(buffer);

        //return unless in the partial fragment
        if (r >= validityBound) continue;
        return r % bound;
    }
}

A: That implementation looks correct for generating unbiased integers in a range.
Another approach would be to take the random bytes as the infinite digits in the binary fraction 0.xxxxxx..., multiply that by bound and round down. It wouldn't actually take infinite digits, just as many as needed to determine what the rounded-down result is. I think that's more complex though.
But generating numbers in the full range may be unnecessary for your protocol. RFC 5054 section 3.1 requires only 256-bit private exponents. That number comes from doubling the bit-length of the hash output and requires that a safe prime is used. An earlier draft of that RFC referred to On Diffie-Hellman key agreement with short exponents for an explanation, which is in the first paragraph of section 4 there.
If you prefer more random bits, take the bit length of range minus 1. This is what OpenSSL does for Diffie-Hellman (search for BN_rand and the line before it). That's still easier to generate and less that twice shorter than the full range, and if that makes a difference you should use a larger prime.

A: Your code looks correct and unbiased. However, you may want to change it a bit, if you are after performance, and depending on the speed of the random source you are using. The idea is to mask out a few more bits so that the random value r is smaller than 2*bound. If the length in bits of bound is x (length excluding the sign bit), then you generate a buffer of n = ((x+8)/8) bytes, and mask out the upper (n*8-x) bits. In C#, this should look like:
var x = BitLength(bound);
var n = ((x + 8) / 8);
var buffer = new Byte[n];
var mask = 0xFF >> (8 * n - x);
while (true) {
    source.GetBytes(buffer);
    buffer[n - 1] &= mask;
    var r = new BigInteger(buffer);
    if (r < bound)
        return r;
}

With this kind of code, you may have to ask more random bytes from the source, but you avoid the modular reduction (the % operator). A proper PRNG should be much faster than division on big integers, so this should be a better trade-off -- but this really depends on the performance of the random source, and, since it is a question of performance, it cannot be fully answered without trying. Chances are that, as part of an overall SRP implementation, it would not make any noticeable difference anyway.
I have used above a BitLength() function which does not seem to exist in C# (Java's BigInteger class has a bitLength() method, but apparently Microsoft forgot to include one in their big integer implementation -- which is a shame, because it seems that the implementation really includes a private field called _bits which maintains that value). The bit length can be computed efficiently from the representation, in bytes, of the bound value. Thus, the code would become something like this:
var buffer = bound.ToByteArray();
var n = buffer.length;
var msb = buffer[n - 1];
var mask = 0;
while (mask < msb)
    mask = (mask << 1) + 1;
while (true) {
    source.GetBytes(buffer);
    buffer[n - 1] &= mask;
    var r = new BigInteger(buffer);
    if (r < bound)
        return r;
}

I am using the fact that the length, in bytes, of the encoding of bound, as returned by ToByteArray(), is precisely the value of n that I need.


text:
Q: Firebase database keys beginning with underscore removed I started writing a web app and the user object has a _username key so its on the beginning.
If I add the object to firebase database it is not there - everything else is.
Why is this key/value pair not in the database? I mean it is valid JSON, isn't it?
I mean are there other solutions than simply renaming it?
my object which is pushed to an array has following structure:
{
    _username:"",
    history:[],
    // ...
}

My code:
var users = $firebaseArray(ref.child("user"));

// adding user
users.$add($scope.session.user);
// logging afterwards - also no '_username'

// logging on init
users.$loaded().then(function (data) {
    $log.debug(data);
});

Everything is stored, except the underline var...

A: It looks like $add() (or more specifically $firebaseUtils.toJSON()) drop properties whose name starts with an _. A quick way to see this is:
console.log($firebaseUtils.toJSON(user));

A workaround would be to directly write the user object to the database through the JavaScript SDK:
ref.child("user").push(user);

This does write all properties with valid key names, including the ones prefixed with a _.
Since AngularFire is built on top of the same JavaScript SDK, it will pick up the changes straight away.
Demo in jsbin: http://jsbin.com/lobadej/edit?js,console

A: This was a design decision, based on the fact that a common JavaScript convention for declaring private variables is to prefix them with _.
For context on why it's different than the default SDK behavior, keep in mind that AngularFire is creating class instances that can be extended, and provide client-side functionality (not just raw JSON objects for data transfer). So our goal here is to make it as simple and straightforward as possible to extend and use $firebaseArray and $firebaseObject, and to make saving and server sync as transparent as possible.
To do so, you need a simple convention to separate "local" or private things from ones you want sent to the server. Since $ is technically reserved by the Angular libs, _ continues to be the appropriate way to prefix your private variables and methods pre-ES6.
We could revisit if there were significant numbers of people having issues here, but given that it's been implemented this way nearly 3 years and this is the first comment on it, I suspect it's fine as is.
See also: https://github.com/firebase/angularfire/issues/901


text:
Q: Discord py, the bot sends a message twice I am totally new to StackOverflow, and also quite new to python. I've been coding a bot for a few days, and it worked fine until this evening. I tried to add a leveling system (which I found here, can't remember where though). It does work, but now my bot sends a message in the chat twice, on every command.
This is my relevant code:
import discord
import datetime
import requests
import random
import json
import time
import asyncio
import discord.ext.commands
from discord import FFmpegPCMAudio
from discord import Game
from discord import Intents
from discord.ext.commands import Bot
from discord.utils import get
from discord.ext import commands

intents = Intents.all()
BOT_PREFIX = ("z!", "Z!", "zticko!")
TOKEN = 'REDACTED'

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
    activity = discord.Activity(name='Dennis... ;)', type=discord.ActivityType.watching)
    await client.change_presence(activity=activity)

@client.event
async def on_message(message):
    channel = client.get_channel(#the channel ID)
    if 'among us' in message.content or 'Among us' in message.content:
        await channel.send("Glöm bara inte votea ut <@!userid> första rundan, I promise - han är Impostor 8/10 gånger.")
        emoji = client.get_emoji(robinemo)
        await message.add_reaction(emoji)
    await client.process_commands(message)
    #####################################################################
    #                                                                   #
    #               LEVELSYSTEMET BÖRJAR NEDAN                          #
    #                                                                   #
    #####################################################################
    if message.author.bot == False:
        with open('users.json', 'r') as f:
            users = json.load(f)

        await update_data(users, message.author)
        await add_experience(users, message.author, 5)
        await level_up(users, message.author, message)

        with open('users.json', 'w') as f:
            json.dump(users, f)

    await client.process_commands(message)

async def update_data(users, user):
    if not f'{user.id}' in users:
        users[f'{user.id}'] = {}
        users[f'{user.id}']['experience'] = 0
        users[f'{user.id}']['level'] = 1
    print("Uppdaterar en User")

async def add_experience(users, user, exp):
    users[f'{user.id}']['experience'] += exp
    pass

async def level_up(users, user, message):
    with open('levels.json', 'r') as g:
        levels = json.load(g)
    experience = users[f'{user.id}']['experience']
    lvl_start = users[f'{user.id}']['level']
    lvl_end = int(experience ** (1 / 4))
    if lvl_start < lvl_end:
        await message.channel.send(f'{user.mention} har levlat upp till level {lvl_end}! Gz till ding!')
        users[f'{user.id}']['level'] = lvl_end
    pass

#
# Vid ny användare, lägg in för LEVELSYSTEMET
#

@client.event
async def on_member_join(member):
    with open('users.json', 'r') as f:
        users = json.load(f)

    await update_data(users, member)

    with open('users.json', 'w') as f:
        json.dump(users, f)

    print("Ny user!")

@client.command(description="Kolla vilken level du ligger på.", brief="Vilken level är du?")
async def level(ctx, member: discord.Member = None):
    if not member:
        id = ctx.message.author.id
        with open('users.json', 'r') as f:
            users = json.load(f)
        lvl = users[str(id)]['level']
        await ctx.send(f'Du är på level {lvl}!')
    else:
        id = member.id
        with open('users.json', 'r') as f:
            users = json.load(f)
        lvl = users[str(id)]['level']
        await ctx.send(f'{member.mention} är på level {lvl}!')
    pass

The output would look something like:
BOT
Today 04:17
@User är på level 2!
@User är på level 2!
And it's only supposed to send one of those. It also runs every other command I have twice. It did not do this, until I added the leveling system. Can someone point me in the right direction? I'm sorry if this is a rookie mistake, I'm trying to learn and balance my medical studies at the same time, haha...

A: OH WOW, I'm sorry guys. I had the line "await client.process_commands(message)" twice in the on_message event. I removed one, it works now!

A: well you need to do:
@client.command()
async def command(ctx): #u can change the comand if you want
    await ctx.send("enter message here")
    await ctx.send("enter same message here")


text:
Q: Encontrar arquivo no diretório templates Em versões até a 2.2.5 do Django eu colocava meus arquivos html que eram passados na view da seguinte forma :
myapp
   templates
       myapp
          index.html

Mas no django 2.2.6 e 2.2.7 quando faço isso dá o seguinte erro :
TemplateDoesNotExist at /

Mas quando eu faço :
myapp
   templates
       index.html

O template é encontrado.
Como nessas versões mais novas o Django  faz o tratamento para identificar 2 templates com o mesmo nome sem precisar do subdiretório para distinguir ?

A: Acredito que seja uma configuração no arquivo settings.py do projeto.
Verifique se tem a variável TEMPLATES, dessa forma:
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Importante:
'DIRS': ['templates']: Define o nome das pastas onde o django vai procurar pelos templates, no seu caso, é templates mesmo.
'APP_DIRS': True: Informa se o django deve procurar pelos templates dentro das aplicações, no seu caso, é True mesmo.
Fazendo essa configuração ele vai encontrar templates dentro da pasta 'templates' dentro da sua aplicação.
Outra coisa:
Se sua estrutura estiver:
myapp
   templates
       myapp
          index.html

O caminho do seu template não é index.html e sim myapp/index.html
Espero que te ajude.
Abraço.


text:
Q: ffmpeg: How to place multiple overlays and fade out the topmost properly I'm trying to place several overlays on top of each other and fade out the topmost after some frames. Therefore I'm using 2 .png files which should be placed on the final video in the following order:

fademe.png <-- Topmost overlay, should be faded after some frames
overlay.png <-- second overlay, always visible
movie.mov <-- a movie as the bottom layer

I'm using this code to create a PNG encoded .mov from the overlays:
ffmpeg -y -loop 1 -i fademe.png -loop 1 -i overlay.png -filter_complex "[0:0]fade=out:25:25[fad];[1:0][fad] overlay" -vframes 55 -vcodec png overlay.mov

Then I'm using ffmbc to place overlay.mov on top of another video.
(I'm using ffmbc because the final output is going to be ProRes4444)
ffmbc -y -threads 0 -i movie.mov -vf "movie=overlay.mov [watermark]; [in][watermark] overlay [out]"  -vcodec libx264 faded.mp4

The output video looks nice until fading starts and fademe.png [fad] seems to get faded to white and doing some strange things to the colours below until it disappears.
When I'm changing the order in the last overlay from [1:0][fad] overlay to [fad][1:0] overlay so it looks like this:
ffmpeg -y -loop 1 -i fademe.png -loop 1 -i overlay.png -filter_complex "[0:0]fade=out:25:25[fad];[fad][1:0] overlay" -vframes 55 -vcodec png overlay.mov

the fading looks right, but overlay.png [1:0] shouldn't be the topmost layer.
My guess is that something wrong happens to the alpha-channel on my first try.
Any suggestions how to solve this problem?

A: It should not be necessary to use two commands and create an intermediate file with an alpha channel.  A single command with 3 inputs, 2 overlay filters, and a fade filter with alpha=1 should do it:
ffmpeg -y -i movie.mov -loop 1 -i overlay.png -loop 1 -i fademe.png \
-filter_complex '[0:v][1:v] overlay [V1]; \
[2:v] fade=out:25:25:alpha=1 [V2]; [V1][V2] overlay' \
faded.mp4

A: I think i found a solution:
First I created a intermediate movie of the fading logo
ffmpeg -y -loop 1  -i fademe.png -filter_complex "fade=out:25:25" -vframes 55 -vcodec png fademe.mov

then I used this command with ffmbc
ffmbc -i movie.mov -vf "movie=overlay.png [over]; movie=fademe.mov [fade]; [in][over] overlay [inter]; [inter][fade] overlay [out]" -vcodec libx264 out.mp4

...Heureka!!!
The logo sitting on top of the composition is fading away nice and smooth!


text:
Q: Windows event 4771 , different use case between computer and user I am using powershell to get audit fail events 4625 and 4771 from the Domain Controllers. Most of these are 0x18 Status. Now i understand the events with usernames (don't end in a $) as having bad passwords from a machine. Most of the google examples show 4771's from users.

What i want to understand, is what it means when it is coming from a machine?

i.e. surely it is an account on the machine which has an issue, how does a machine have a bad password? And if it can, how does one find out what the issue is ?

A: Active Directory is an identity management system, and so anything that authenticates with Active Directory needs an "identity" of some sort. Since computers themselves can be joined to a domain and must authenticate against it (with a username and password via Kerberos the same as a regular user logon), they have a username. The AD machine account username is the computer's DNS hostname followed by a dollar sign, for example: Desktop-AB123$
Since every computer in the domain must authenticate against the domain with a username and password, it is possible for that authentication to fail. And it can fail for all of the same reasons that a regular user logon can fail: unrecognized or misspelled username, incorrect password, wrong domain or UPN suffix, or any number of authentication errors.
Event ID 4771 indicates a Kerberos preauthentication error and status 0x18 (usually) indicates a bad password. Source.
Machine accounts renegotiate their password automatically with the Domain Controller when they connect to the domain. If a domain-joined workstation is unable to communicate with a domain controller long enough for the password to expire, it will not be able to log in and you will get a failed logon for that computer's machine name. The computer will need to be rejoined to the domain (or have its password reset using Reset-ComputerMachinePassword and a domain admin credential). The same is also true if a domain controller is unable to communicate with the PDC Emulator. This will be the most common type of error that will lead to failed machine account logins. The second most common will probably be due to computers being renamed while unable to contact a DC, changing the computer's logon username without updating AD.
Beyond password expiration or computer renames, you have to start looking deeper for root causes. These are likely going to be Kerberos negotiation errors caused by services attempting to authenticate in order to perform certain actions. Note that the authentication error does not necessarily occur at service start and may occur when the service is accessed or triggered by another application. I recommend reviewing my question & answer in ServerFault regarding one such example where a server's DNS name didn't match its NETBIOS name, which caused Kerberos authentication to fail and fall back to NTLM.
As that ServerFault question illustrates, tracking down the root cause of a failed machine logon, once you've ruled out username and password errors, can be extremely difficult. Your first step should probably be to enable Netlogon debug logging and then searching the netlogon log file for your failure events. You can also search the SYSTEM event log for any events related to services failing to start. After those two starting points you're basically on your own and will need to develop some advanced troubleshooting and investigation skills to track down the root cause.
One final note, your question is not exactly related to programming or software development, so SuperUser or ServerFault might be a better place for questions such as this in the future. ServerFault is geared towards professional sys admins working in production environments while SuperUser is more geared towards hobbyists, enthusiasts, home servers, and DIYers.


text:
Q: Xamarin Forms : Access list data when click of a Button inside listview-viewcell I have a button inside listview-viewcell. For the button, I am using clicked event. So on click of the button, I need the details of the selected list item like the first name, email etc. I tried like following:
Xaml code:
  <ListView x:Name="MyDirectories"
                  HasUnevenRows="True">
             <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ViewCell.View>
                                 <Button
                                        BorderRadius="25"
                                        HeightRequest="40"
                                        WidthRequest="150"
                                        TextColor="White"
                                        HorizontalOptions="CenterAndExpand"
                                        Font="Bold,15"
                                        Margin="0,0,0,5"
                                        BackgroundColor="#004F7E"
                                        Clicked="MoreDetails"
                                        Text="More Details"/>
                            </StackLayout>
                        </ViewCell.View>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
         </ListView>

Xaml.cs code:
       public class MyListItemEventArgs : EventArgs
        {
            public UserProfileTO MyItem { get; set; }
            public MyListItemEventArgs(UserProfileTO item)
            {
                this.MyItem = item;
            }
        }

       public void MoreDetails(Object sender, MyListItemEventArgs args)
        {
             var item = args.MyItem;
            if (item != null)
            {
                Debug.WriteLine("Firstname:>"+item.firstName);
            }
       }

When I run getting InvalidCastException: Specified cast is not valid.
Anybody, please suggest any other solution.
Thanks in advance.

A: The problem was with the model class given in MyListEventArgs:
   public class MyListItemEventArgs : EventArgs
    {
        public UserProfileHBList MyItem { get; set; }
        public MyListItemEventArgs(UserProfileHBList item)
        {
            this.MyItem = item;
        }
    }

   public void MoreDetails(Object sender, MyListItemEventArgs args)
    {
        var item = args.MyItem;
        if (item != null)
        {
            Debug.WriteLine("Firstname:>" + item.userProfileTO.firstName);
        }
    }

The firstname, email etc are another json(userProfileTO) inside of the main json(UserProfileHBList). Also forget to add stacklayout, thank you Alessandro Caliaro.


text:
Q: why isn't this home icon centered inside the div? I have set the inner div to style="margin:auto;", yet the home icon is not centered.

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

This is what I am seeing:

A: If you inspect the page, you will notice that your div is taking up the entire width. You can use text-align to align your icon instead (see snippet below).
Also, setting margin: auto will set all margins to auto (top, bottom, left, right). If you just want left/right, you can write: margin: 0px auto (source)

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

A: If you really want to use margin: auto;, then you need to set a width. width: min-content; should be enough.

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">


text:
Q: prove that f is a surjection Let C be a partition of a given set A.
Prove that there exists a set B and $ f : A \rightarrow B$ such that
$ \quad $ (i) f is surjective
$\quad $ (ii) $ C = \{\{x \in A : f(x)=y\} : y \in B \}.  $
Let $ C = A_1 \cup A_2 ... \cup A_n$, n = infinity if A is infinite set.
Let f be a function s.t. $ \forall x,y \in A, \exists i \in \{1,2,....n\} $ where $ x,y \in A_i \iff f(x) = f(y) = i. $
$ B = \{1,2,...n\}. $
Take any $ y \in B,  f(x) = y, \forall x  \in A_y $. Therefore, f is surjective
I am not sure if this proof is correct?

A: If $C$ is an arbitrary partition then it looks like one can take $B = \{c_{1},...c_{n},...\}$ where $c_{i}$ corresponds to the first element in the $i$th partition subset of $A$. If you have a uncountable partition set and/or a "first element" is not defined then one can choose one using a random function. However, I don't know how to make this rigourous because it completely depends on what the partitions are. If the partitions are intervals then of course you can take all midpoints. If it is a partition of a tricky nowhere continuous function then you might need to be a bit more creative.

A: There are several problems with your attempt. First, $C$ is a set of subsets of $A$, not the union of those sets. Next, there is no reason to think that $C$ can be enumerated by the natural numbers: we might, for instance, have the partition
$$\big\{\{x,-x\}:x\in\Bbb R\big\}$$
of $\Bbb R$, which has uncountably many members. Finally, there may not be any natural way to index the members of $C$ by numbers of any kind. Fortunately, there is no need to do so: we can in a sense index them by themselves.
Just let $B=C$, and for each $a\in A$ let $f(a)$ be the unique member of $C$ containing $a$. Clearly $f$ is surjective, since every member of $C$ is non-empty. Let $c\in C$; then for each $a\in A$ we have $f(a)=c$ iff $a\in c$, so $c=\{a\in A:f(a)=c\}$. Thus,
$$\begin{align*}
C&=\{c:c\in C\}\\
&=\big\{\{a\in A:f(a)=c\}:c\in C\big\}\,.
\end{align*}$$


text:
Q: using ajax technique in laravel 5.7 I want to delete and update table row with modal by using ajax technique
in
laravel 5.7 but I m quite naive with ajax.
I would be appreciated if anyone helps and explain how ajax send/get data in
controller and is there any difference between using ajax in PHP and
laravel.?
this is my table

    ID
    Title
    Description

@foreach($project as $pro)

    {{$pro->id}}
    {{$pro->title}}
    {{$pro->description}}

        <button class="btn btn-info"
data-toggle="modal" data-target="#edit">Edit</button>
        <button class="btn btn-danger"
data-toggle="modal" data-target="#dlt">Delete</button>

<--------------------->

        <form method="post" action="">
            @method('PATCH')
            @csrf

                <button type="button" class="close" data-dismiss="modal"
aria-label="Close">×</button>

Modal title

                     Title
                     <input type="text" class="form-control" name="title" >

                    Description
                    <input type="text" class="form-control"
name="description">

                <button type="button" class="btn btn-default" data-
dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Save
changes</button>

        </form>

 this is my modal code

                <button type="button" class="close" data-dismiss="modal"
aria-label="Close">×</button>

Adding
Project

             <form method="post" action="">
                @method('delete')
                @csrf

                    Are you sure, you want to delete this.?

                    <button type="button" class="btn btn-default" data-
dismiss="modal">No, Cancel</button>
                    <button type="submit" class="btn btn-info">Yes,
Delete</button>

        </form>

my route
Route::resource('projects', 'ProjectsController');

A: There no difference between using ajax in PHP and laravel.
html adjustment, add this meta inside your html head.
 <meta name="csrf-token" content="{{ csrf_token() }}" />

Update your delete button and add a hidden field inside your delete modal body.
   <button class="btn btn-danger btn-delete-project" data-toggle="modal" data-target="#dlt" data-project-id="{{ $pro->id}}">Delete</button>
    <input type="hidden" name="project_id" id="project_id" value="">

    <button type="submit" class="btn btn-info delete-project-confirm">Yes, Delete</button>

Get Your deleted row,

id }}">

Define your ajax function, there are many defferent technique you can do it. A simple one below.
/**
 * project delete confirm modal
 */
$(document).on('click', '.btn-delete-project', function (e) {
    e.preventDefault();
    var projectId = $(this).data('project-id');
    $('#dlt #project_id').val(projectId);
});
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

 /**
  * ajax call
  */
// give your delete button id
$(document).on('click', '.delete-project-confirm', function (e) {
    e.preventDefault();
    var projectId = $('#dlt  #project_id').val();
    var deletedRow = $('tr[data-row-id="' + projectId + '"]');
    $.ajax({
        type: 'delete',
        url: '/project/' + projectId,
        success: function () {
            $('#dlt').modal('toggle');
             deletedRow.remove();
            // toastr.success('Order Has Been Deleted Successfully.');
        },
        error: function(XMLHttpRequest) {
            // toastr.error('Something Went Wrong !');
        }
    });

});

In your ProjectController destroy() method,
public function destroy($id)
{
    // dd($id);
    $project = Project::findOrFail($id);

    // dd($project);
    $project->delete();

}


text:
Q: How can I delegate an implementation to a mutable property in Kotlin? As to my understanding, the idea of delegating an implementation in Kotlin is to avoid code that looks like this:
class MyClass(val delegate : MyInterface) : MyInterface
{
    override fun myAbstractFun1() = delegate.myAbstractFun1()
    override fun myAbstractFun2() = delegate.myAbstractFun2()
    // ...
}

Instead, we can write the following code which should do the same:
class MyClass(val delegate : MyInterface) : MyInterface by delegate

Now, I'd like delegate to be a mutable variable, i.e. my code looks like this:
var delegate : MyInterface = MyImplementation()
object MyObject : MyInterface by delegate

So if I'd delegated every abstract method to delegate by myself like in the first example, changing the value of delegate does change the behaviour of the methods. However, the above code compiles to this Java code:
public final class MyObject implements MyInterface {
    public static final MyObject INSTANCE;
    // $FF: synthetic field
    private final MyInterface $$delegate_0 = MyObjectKt.access$getDelegate$p();

    @NotNull
    public String myAbstractFun1() {
        return this.$$delegate_0.myAbstractFun1();
    }

    @NotNull
    public String myAbstractFun2() {
        return this.$$delegate_0.myAbstractFun2();
    }
}

So obviously, instead of just using the delegate field, the Kotlin compiler decides to copy it when creating MyObject to a final field $$delegate_0, which is not modified when I change the value of delegate
Is there a better solution for doing this instead of delegating every method manually?

A: Sadly, as far as I know there is no way of changing the delegate by changing the original property content, but you might still be able to do something similar by working in an immutable way and copying the object:
interface MyInterface {
  fun foo():Int
}

data class MyClass(val delegate : MyInterface) : MyInterface by delegate

object ImplementationA: MyInterface { override fun foo() = 7 }
object ImplementationB: MyInterface { override fun foo() = 5 }

val objA = MyClass(ImplementationA)
println(objA.foo()) // returns 7

val objB = objA.copy(ImplementationB)
println(objB.foo()) // returns 5
println(objA.foo()) // still 7

Hope this is still useful.


text:
Q: Should experiments of high energy electron collisions be done as an experimental test of the Standard Model? As I see from this discussion link there were no experiments where high energy electron beams were collided, only at low energy (VEP-1 collider in Novosibirsk, Russia). Assuming that standard model (SM) is correct we should see generation of electron-positron pairs in electron-electron-collisions when energies of the colliding electrons are high enough. So, the question is following. Should such experiments be done to test SM since if we will not see the electron-positron pairs the validity of SM is under a question.

A: Quite contrary to the answer mentioned in the link you provided, there were electron electron collision experiments. In fact, they were the first collider experiments that have been conducted.
So, electron electron collisions are also called Moller scattering which is well described quantitatively by the feynman rules for Quantum Electro Dynamics.
First, there is VEP-1 collider in Novosibirsk, Russia. It is a collider with an energy of $2*160 \,\mathrm{MeV}$. It reached a luminosity of $4*10^{28} \,\mathrm{cm^{-2}s^{-1}}$. The experimental studies on scattering of electrons were conducted and the following reactions were observed
$$e^{-} e^{-} \rightarrow e^{-} e^{-} \gamma$$
$$e^{-} e^{-} \rightarrow e^{-} e^{-} 2\gamma \tag{Double bremstrahlung}$$
So, the first reaction can be seen as a pair annihilation producing a photon. But, most probably it was from bremsstrahlung of either the initial or final states.
Secondly, there is also a collider in the US which is the Princeton-Stanford Experiment Collider. It was the most powerful electron accelerator during it's time. It is a collider with an energy of $2*500 \,\mathrm{MeV}$. It reached a luminosity of $2*10^{28} \,\mathrm{cm^{-2}s^{-1}}$. It has conducted several tests for QED.
QED is very well tested and understood. So, according to me we do not require a electron electron collider even at high energies today. I am more excited to see a Linear Collider of electron positron of higher energies or a muon anti-muon collider.
Also, if you would like to read about these colliders here is the link: https://arxiv.org/abs/1307.3116


text:
Q: Bijection between sets homotopy classes and homotopy I want to see intuition , how to work with homotopy classes of spaces. Here is the problem: given two topological spaces X and Y, also we have that for every top. space Z
there is bijection between [Z,X] and [Z,Y],and i need to prove that X is homotopic to X.
I tried to use bijection between [X,X] and [X,Y] and see what it can give me, but i only understood that, if [X,X] has one element, then X contractible,so [X,Y] has one element,thus Y is contractible too,so X is homotopic to Y in this case.


text:
Q: Firebase - Get object by userID from a list of profiles I'm trying to  get an object by userID from a list of profiles using Firebase.
I'm coding in Angular2 with Typescript.
I've got the reference to firebase working and can do other commands like push an object etc.
I just need to know how to extract an object by its field value e.g. uid in this case.
Here's my code snippet:
getUserProfileByUid(uid){
    console.log("Get profile by uid");

    var ref = new Firebase("https://markng2.firebaseio.com/profiles/uid");
    var data = ref.child(uid);

    console.log(data));
}

*See attached photo for view of my firebase profiles json.

Thanks in advance.

A: You can use a query.
var rootRef = new Firebase('<my-firebase-app>.firebaseio.com/');
var profileRef = rootRef.child('profiles');

// order by email and then find the specific email
var query = profileRef.orderByChild('email').equalTo('myemail@email.com');

// Do a one time read of that email
query.once('value', (snap) => console.log(snap.val()));

Read the Firebase documentation for more details.


text:
Q: Umbraco generated links broken when switching from IIS express to local IIS How do you let Umbraco know the root of the project?
I developed an Umbraco site using IIS express when I deployed it to local IIS all of the relative links are broken.
I have control over all the links I generated but not over the Umbraco generated links.
I'm using Umbraco 7.4.2
For example, the root of my project used to be "//localhost:01010/" now it is "//localhost/sitename/"
The Umbraco generated links does not consider /sitename so an Umbraco generated link will look like "//localhost/media/50/img.png" instead of "//localhost/sitename/media/50/img.png"

A: Two things to check

*

*get rid of the umbraco.config file as it contains the cache for the OLD site and do 'Re-publish entire site'

*remove the contents of App_Data/ClientDependency folder.

See https://our.umbraco.org/forum/getting-started/installing-umbraco/19071-Moved-Installation-to-new-server-umbracoconfig-issue