text:
Q: How to remove the dots in Wpf Chart which is using Data Visualzation tool kit dll I am working MVVM & Wpf Application, in that I am developing a chart using Data visualization tool kit Chart Line series...
This is my Xaml Code..

xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting; assembly=System.Windows.Controls.DataVisualization.Toolkit"

    <chartingToolkit:Chart>
         <chartingToolkit:LineSeries
                 DataContext="{Binding}"
                 DependentValueBinding="{Binding Path=y}"
                 IndependentValueBinding="{Binding Path=x}"
                 ItemsSource="{Binding Path=Data}" >
         </chartingToolkit:LineSeries>
         <chartingToolkit:Chart.Axes>
            <chartingToolkit:LinearAxis ShowGridLines="False" Orientation="X" Interval="0">
            </chartingToolkit:LinearAxis>
            <chartingToolkit:LinearAxis ShowGridLines="False" Orientation="Y" Interval="0">
            </chartingToolkit:LinearAxis>
       </chartingToolkit:Chart.Axes>
    </chartingToolkit:Chart>

I am able to display my chart, but the problem is how to hide dots. (I marked them with pink Circle in the picture (graph/ chart))

A: You have to set a style with Opacity = 0
<Style x:Key="LineDataPointStyle" TargetType="{x:Type chartingToolkit:LineDataPoint}">
    <Setter Property="Background" Value="Blue" ></Setter>
    <Setter Property="Opacity" Value="0" />
</Style>

<chartingToolkit:LineSeries
    Title="Line"
    ItemsSource="{Binding}"
    IndependentValuePath="Int"
    DependentValuePath="LineValue"
    DataPointStyle="{StaticResource LineDataPointStyle}"/>


text:
Q: Undefined object when trying to clone - but it logs correctly I have the following:
$(window).on('drop', this.onDrop.bind(this));

p.onDrop = function(e) {
    var self = this;
    var files = e.originalEvent.dataTransfer.files;
    $.each(files, function(index, file){
        self.showTemplate();
    });
};

p.showTemplate = function() {
    console.log(this.template); //logs template correctly
    var template = this.template.clone(); //Uncaught TypeError: undefined is not a function
};

I'm not sure what is happening. I can log the template so I must have access to it, but for some reason it can not be cloned?

A: The error "undefined is not a function" is saying .clone is not a function. It doesn't appear to exist (as function, at least) on this.template.
Since you're using jQuery, you can use .extend():
// Shallow copy
var clone = jQuery.extend({}, this.template);

// Deep copy
var clone = jQuery.extend(true, {}, this.template);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use a hash table to find a cycle in a singly linked list? I am aware this is a common question asked, but no answers I've found differ from my algorithm, yet leetcode states my algorithm doesn't work. How can I use a hash table to find if there is a cycle in a singly linked list in JS? I implemented the following algorithm:
var hasCycle = function(head) {
    let node = head;
    let table = {};

    while(node) {
        if(table[node.value]) {
            return true;
        }
        else {
            table[node.value] = true;
        }
        node = node.next;
    }

    return false;
};

However on leetcode, my algorithm works until it hits the following test case:
Input: [1, 2], pos: -1

Where [1, 2] is the linked list, and pos is the position of the node that the tail points to. Since it is -1, the tail points to null so there is no cycle.
Why does leetcode say my code returns true? In my while loop, the first iteration sets table[1] to true. In the second iteration, table[2] is set to true. Then we exit the while loop since node points to null now, so my code should return false. However, leetcode says my algorithm returns true. Where did I make a mistake?
I am aware of the tortoise and hare algorithm, but I am trying to understand the hash table method to find a cycle.

A: Essentially what you need to do is traverse through the list and see which comes first? The end of the list, or a previously visited node. You can use your Hashtable to record what nodes you have visited, although you really need is a Set, but you can use a hashtable for this purpose if that is what the specifications are:
Here's how you go about it:

*

*Check if the node you are at is null. If so, there are no cycles

*Check if the node you are at is already in the hashtable. If so, there is a cycle

If not 1 or 2:

*Add the node to the hashtable

*Go on to the next node in the list

A: Check this algorithm. It works fine for array
var hasCycle = function(data) {
    let dataLength = data.length;
    let table = {};
    for(let i=0 ; i < dataLength; i++ ) {
      if(table[data[i]]) {
            return i;
        }
        table[data[i]] = true;
    }
    return -1;
};

console.log(hasCycle([1,2,1]));// 2
console.log(hasCycle([1,2])); // -1


text:
Q: How to fill the width of the content in vuetify
*

*What I want is that to fill the width of the entire mobile screen with vuetify

with this code :
 <v-content>
    <router-view>
      <v-container fluid></v-container>
    </router-view>
  </v-content>

the router view has a margin on both left and right side

*and that bottom-nav is already fitted on the screen and I won't be dragging the screen to show the bottom-nav

A: you can also try this, vuetify has helper classes to set padding and margin
<v-container fluid  class="pa-0 ma-0">
</v-container>

A: v-container creates a div with the class container. This class gives your div padding on all sides. (The amount changes depending on the viewport breakpoint; it's 2px for xs, 24px for xl). If you include the below in your css, your side padding should go away.
.container {
   padding: 0!important
}

A: I needed to dynamically remove padding only on mobile, this works for me:
<v-container :class="{'px-0': $vuetify.breakpoint.xsOnly }">
   <router-view> </router-view>
</v-container>

There is not much documentation that I could find as of now, but looking at the code I found these:
// Breakpoint ranges.
xsOnly,
smOnly,
smAndDown,
smAndUp,
mdOnly,
mdAndDown,
mdAndUp,
lgOnly,
lgAndDown,
lgAndUp,
xlOnly,


text:
Q: Why is the Completed callback from SocketAsyncEventArgs frequently executed in newly created threads instead of using a bounded thread pool? I have a simple client application that receives byte buffers from the network with a low throughput. Here is the code:
private static readonly HashSet<int> _capturedThreadIds = new HashSet<int>();

private static void RunClient(Socket socket)
{
    var e = new SocketAsyncEventArgs();
    e.SetBuffer(new byte[10000], 0, 10000);
    e.Completed += SocketAsyncEventsArgsCompleted;

    Receive(socket, e);
}

private static void Receive(Socket socket, SocketAsyncEventArgs e)
{
    var isAsynchronous = socket.ReceiveAsync(e);
    if (!isAsynchronous)
        SocketAsyncEventsArgsCompleted(socket, e);
}

private static void SocketAsyncEventsArgsCompleted(object sender, SocketAsyncEventArgs e)
{
    if (e.LastOperation != SocketAsyncOperation.Receive || e.SocketError != SocketError.Success || e.BytesTransferred <= 0)
    {
        Console.WriteLine("Operation: {0}, Error: {1}, BytesTransferred: {2}", e.LastOperation, e.SocketError, e.BytesTransferred);
        return;
    }

    var thread = Thread.CurrentThread;
    if (_capturedThreadIds.Add(thread.ManagedThreadId))
        Console.WriteLine("New thread, ManagedId: " + thread.ManagedThreadId + ", NativeId: " + GetCurrentThreadId());

    //Console.WriteLine(e.BytesTransferred);

    Receive((Socket)sender, e);
}

The threading behavior of the application is quite curious:

*

*The SocketAsyncEventsArgsCompleted method is frequently run in new threads. I would have expected that after some time no new thread would be created. I would have expected the threads to be reused, because of the thread pool (or IOCP thread pool) and because the throughput is very stable.

*The number of threads stays low, but I can see in the process explorer that threads are frequently created and destroyed. Likewise, I would not have expected threads to be created or destroyed.

Can you explain the application behavior?
Edit: The "low" throughput is 20 messages per second (roughly 200 KB/s). If I increase the throughput to more than 1000 messages per second (50 MB/s), the application behavior does not change.

A: The low application throughput itself cannot explain the thread creation and destruction. The socket receives 20 messages per seconds, which is more than enough to keep a thread alive (the waiting threads are being destroyed after spending 10 seconds idle).
This problem is related to the thread pool thread injection, i.e. the threads creation and destruction strategy. Thread pool threads are regularly injected and destroyed in order to measure the impact of new threads on the thread pool throughput.
This is called thread probing. It is clearly explained in the Channel 9 video CLR 4 - Inside the Thread Pool (jump to 26:30).
It seems like thread probing is always done with newly created threads instead of moving a thread in and out of the pool. I suppose it works better like this for most applications because it avoids to keep an unused thread alive.

A: From MSDN

Beginning with the .NET Framework 4, the thread pool creates and
  destroys worker threads in order to optimize throughput, which is
  defined as the number of tasks that complete per unit of time. Too few
  threads might not make optimal use of available resources, whereas too
  many threads could increase resource contention.
Note
When demand is low, the actual number of thread pool threads can
  fall below the minimum values.

Basically it sounds like your low throughput is causing the thread pool to destroy threads since they are not required, and are just sat taking up resources. I wouldn't worry about it. As MS explicitly state:

In most cases the thread pool will perform better with its own
  algorithm for allocating threads.

If you're really bothered, you could always poll ThreadPool.GetAvailableThreads() to watch the pool, and see how different network throughputs affect it.


text:
Q: Extract cell indicators from MeshRegion? As of version 11.1, one can create successive steps of such objects as the Cantor ternary set and a Menger carpet (aka Sierpinski carpet) directly. For example:
     CantorMesh /@ Range[0, 2]

(Aside: To create a suitable image to insert here, the code I actually used was
GraphicsColumn[
 CantorMesh[#, MeshCellStyle -> {Thick, Red}] & /@ Range[0, 2], AspectRatio -> 0.25].)
What I would like, instead of the several mesh pictures, are Boolean indicators of which sections of the original interval and, at each step, its subintervals, are retained and which are deleted. That is, I want to obtain the output:
{{1}, {1, 0, 1}, {1, 0, 1, 0, 0, 0, 1, 0, 1}}

That is easy to do by using the built-in function SubstitutionSystem:
    SubstitutionSystem[{1 -> {1, 0, 1}, 0 -> {0, 0, 0}}, 1, 2]

Or, going back to more basic functions, by:
    cStep[lis_] := Flatten[lis /. {1 -> {1, 0, 1}, 0 -> {0, 0, 0}}]
    NestList[cStep, {1}, 2]

Question Is there a way to extract the same binary information directly from the result of CantorMesh?
And similarly for higher-level steps of the Cantor set and for the steps of forming the Menger carpet?

A: Try to map the following function. It tests wether the interval midpoints are contained in the MeshRegion R, where R is assumed to be a CantorMesh.
find = R \[Function] Boole[RegionMember[R, MovingAverage[
 Transpose[{Range[0., 1., 3^-Log2[MeshCellCount[R, 1]]]}], 2]]]

PS.: For those of you who are not working on a Mathematica version 11.1 or above (just like me), here an implementation of CantorMesh using the function cStep from the OP.
cantorMesh = n \[Function] Module[{edges, cStep},
    cStep[lis_] := Flatten[lis /. {1 -> {1, 0, 1}, 0 -> {0, 0, 0}}];
    edges =
     Transpose[{Range[1, 3^n], Range[2, 3^n + 1]}][[
      Flatten@Position[Nest[cStep, {1}, n], 1]]];
    MeshRegion[Transpose[{Range[0., 1., 3^-n]}], Line[edges]]
    ];

A: Using the similar idea that Henrik did:
iStep[r_?MeshRegionQ] :=
 Block[{n, dx, pts, grid, f, d, l, i, ind},
  l = First[Differences@RegionBounds[r][[1]]];
  dx = RegionMeasure[MeshPrimitives[r, {1, 1}]];
  n = l/dx;
  pts = N@Table[i dx + dx/2, {i, 0, n - 1, 1}];
  d = RegionEmbeddingDimension[r];
  ind = Table[{i[j], pts}, {j, d}];
  grid = Table[ind[[All, 1]], ##] & @@ ind;
  f = RegionMember[r];
  Boole[Map[f, grid, {d - 1}]]
  ]

iStep /@ Table[CantorMesh[i], {i, 0, 2}]

{{1}, {1, 0, 1}, {1, 0, 1, 0, 0, 0, 1, 0, 1}}

iStep /@ Table[MengerMesh[i], {i, 0, 2}]

{{{1}}, {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}, {{1, 1, 1, 1, 1, 1, 1, 1,
  1}, {1, 0, 1, 1, 0, 1, 1, 0, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1}, {1,
  1, 1, 0, 0, 0, 1, 1, 1}, {1, 0, 1, 0, 0, 0, 1, 0, 1}, {1, 1, 1, 0,
  0, 0, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 0, 1, 1, 0, 1, 1,
  0, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1}}}

iStep /@ Table[MengerMesh[i, 3], {i, 0, 1}]

{{{{1}}}, {{{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}, {{1, 0, 1}, {0, 0,
      0}, {1, 0, 1}}, {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}}}


text:
Q: ionic 2 with restAPI I am using ionic2 with rest API.
Here is my code
let body={
      O_NUMBER: "",
      CART_ID: "",
      S_ID: "",
      PRODUCTS:"",
      BILLING: "string",
      SHIPPING: "",
      PAYMENT: {
        "TYPE": "",
        "SUBTOTAL": "",
        "TAX_TOTAL": "",
        "TOTAL_AMOUNT": "",
        "TRANSACTION_ID": ""
      },
      DATE: "",
      STATUS: "",
      customerId: ""
    }
let headers = new Headers();
     headers.append('Content-Type','application/json');

     let options = new RequestOptions({
        method: "POST",
        body: body,
        headers: headers });
     return this.http.get(this.url + 'orders?access_token='+ this.Id+body,options);

But body values passed into an object.
How can I fix this issue.
Here is my output.
http://35.154.116.133:3000/api/orders?access_token=ZzhdW7cLdocFyOtPsmMMWH4Q60fHs4zzJ1uYDOPTSWDxx83792pfJvLbRfSKbtRn[object%20Object]

also i tried to http.post.
But not work.

A: To pass values as a part of the query string use URLSearchParams class from the @angular/http:
import { Headers, URLSearchParams } from '@angular/http'

let body = { ... };

let queryParams = new URLSearchParams();

// Add AccessToken to query parameters.
queryParams.set('access_token', this.Id);

// Add all the elements of the 'body' object to query parameters.
for (let key in body) {
  if (body.hasOwnProperty(key)) {
    queryParams.set(key, body[key]);
  }
}

let headers = new Headers();
headers.append('Content-Type','application/json');

let options = new RequestOptions({
  method: 'GET',
  headers: headers,
  params: queryParams
});

return this.http.get(this.url + 'orders', options);


text:
Q: Min-width automatically added in firefox (don't want that) I have a website where I've set a div to 100% width;
On either side of the div I've put in links that touches both left and right side inside the div.
So when I resize the window to it's smallest size I have the links right next eachother.
This works in IE9 and Chrome but in Firefox the right link disappears like an overflow hidden at around 600-650px (same as the min-width of the actual browserwindow depending on the toolbar icons I think).
Does anyone know how to disable the min-width of the browserwindow in firefox?
Thanks


text:
Q: Applying callbacks in a custom training loop in Tensorflow 2.0 I'm writing a custom training loop using the code provided in the Tensorflow DCGAN implementation guide. I wanted to add callbacks in the training loop. In Keras I know we pass them as an argument to the 'fit' method, but can't find resources on how to use these callbacks in the custom training loop. I'm adding the code for the custom training loop from the Tensorflow documentation:
# Notice the use of `tf.function`
# This annotation causes the function to be "compiled".
@tf.function
def train_step(images):
    noise = tf.random.normal([BATCH_SIZE, noise_dim])

    with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
      generated_images = generator(noise, training=True)

      real_output = discriminator(images, training=True)
      fake_output = discriminator(generated_images, training=True)

      gen_loss = generator_loss(fake_output)
      disc_loss = discriminator_loss(real_output, fake_output)

    gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)
    gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)

    generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))
    discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))

def train(dataset, epochs):
  for epoch in range(epochs):
    start = time.time()

    for image_batch in dataset:
      train_step(image_batch)

    # Produce images for the GIF as we go
    display.clear_output(wait=True)
    generate_and_save_images(generator,
                             epoch + 1,
                             seed)

    # Save the model every 15 epochs
    if (epoch + 1) % 15 == 0:
      checkpoint.save(file_prefix = checkpoint_prefix)

    print ('Time for epoch {} is {} sec'.format(epoch + 1, time.time()-start))

  # Generate after the final epoch
  display.clear_output(wait=True)
  generate_and_save_images(generator,
                           epochs,
                           seed)

A: The simplest way would be to check if the loss has changed over your expected period and break or manipulate the training process if not.
Here is one way you could implement a custom early stopping callback :
def Callback_EarlyStopping(LossList, min_delta=0.1, patience=20):
    #No early stopping for 2*patience epochs
    if len(LossList)//patience < 2 :
        return False
    #Mean loss for last patience epochs and second-last patience epochs
    mean_previous = np.mean(LossList[::-1][patience:2*patience]) #second-last
    mean_recent = np.mean(LossList[::-1][:patience]) #last
    #you can use relative or absolute change
    delta_abs = np.abs(mean_recent - mean_previous) #abs change
    delta_abs = np.abs(delta_abs / mean_previous)  # relative change
    if delta_abs < min_delta :
        print("*CB_ES* Loss didn't change much from last %d epochs"%(patience))
        print("*CB_ES* Percent change in loss value:", delta_abs*1e2)
        return True
    else:
        return False

This Callback_EarlyStopping checks your metrics/loss every epoch and returns True if the relative change is less than what you expected by computing moving average of losses after every patience number of epochs. You can then capture this True signal and break the training loop. To completely answer your question, within your sample training loop you can use this as:
gen_loss_seq = []
for epoch in range(epochs):
  #in your example, make sure your train_step returns gen_loss
  gen_loss = train_step(dataset)
  #ideally, you can have a validation_step and get gen_valid_loss
  gen_loss_seq.append(gen_loss)
  #check every 20 epochs and stop if gen_valid_loss doesn't change by 10%
  stopEarly = Callback_EarlyStopping(gen_loss_seq, min_delta=0.1, patience=20)
  if stopEarly:
    print("Callback_EarlyStopping signal received at epoch= %d/%d"%(epoch,epochs))
    print("Terminating training ")
    break

Of course, you can increase the complexity in numerous ways, for example, which loss or metrics you would like to track, your interest in the loss at a particular epoch or moving average of loss, your interest in relative or absolute change in value, etc. You can refer to Tensorflow 2.x implementation of tf.keras.callbacks.EarlyStopping here which is generally used in the popular tf.keras.Model.fit method.

A: I think you would need to implement the functionality of the callback manually. It should not be too difficult. You could for instance have the "train_step" function return the losses and then implement functionality of callbacks such as early stopping in your "train" function. For callbacks such as learning rate schedule the function tf.keras.backend.set_value(generator_optimizer.lr,new_lr) would come in handy. Therefore the functionality of the callback would be implemented in your "train" function.

A: A custom training loop is just a normal Python loop, so you can use if statements to break the loop whenever some condition is met. For instance:
if len(loss_history) > patience:
    if loss_history.popleft()*delta < min(loss_history):
        print(f'\nEarly stopping. No improvement of more than {delta:.5%} in '
              f'validation loss in the last {patience} epochs.')
        break

If there is no improvement of delta% in the loss in the past patience epochs,  the loop will be broken. Here, I'm using a collections.deque, which can easily be used as a rolling list that keeps in memory information only the last patience epochs.
Here's a full implementation, with the documentation example from the Tensorflow documentation:
patience = 3
delta = 0.001

loss_history = deque(maxlen=patience + 1)

for epoch in range(1, 25 + 1):
    train_loss = tf.metrics.Mean()
    train_acc = tf.metrics.CategoricalAccuracy()
    test_loss = tf.metrics.Mean()
    test_acc = tf.metrics.CategoricalAccuracy()

    for x, y in train:
        loss_value, grads = get_grad(model, x, y)
        optimizer.apply_gradients(zip(grads, model.trainable_variables))
        train_loss.update_state(loss_value)
        train_acc.update_state(y, model(x, training=True))

    for x, y in test:
        loss_value, _ = get_grad(model, x, y)
        test_loss.update_state(loss_value)
        test_acc.update_state(y, model(x, training=False))

    print(verbose.format(epoch,
                         train_loss.result(),
                         test_loss.result(),
                         train_acc.result(),
                         test_acc.result()))

    loss_history.append(test_loss.result())

    if len(loss_history) > patience:
        if loss_history.popleft()*delta < min(loss_history):
            print(f'\nEarly stopping. No improvement of more than {delta:.5%} in '
                  f'validation loss in the last {patience} epochs.')
            break

Epoch  1 Loss: 0.191 TLoss: 0.282 Acc: 68.920% TAcc: 89.200%
Epoch  2 Loss: 0.157 TLoss: 0.297 Acc: 70.880% TAcc: 90.000%
Epoch  3 Loss: 0.133 TLoss: 0.318 Acc: 71.560% TAcc: 90.800%
Epoch  4 Loss: 0.117 TLoss: 0.299 Acc: 71.960% TAcc: 90.800%

Early stopping. No improvement of more than 0.10000% in validation loss in the last 3 epochs.

A: aapa3e8's answer is correct but I am providing an implementation of Callback_EarlyStopping below that is more similar to tf.keras.callbacks.EarlyStopping
def Callback_EarlyStopping(MetricList, min_delta=0.1, patience=20, mode='min'):
    #No early stopping for the first patience epochs
    if len(MetricList) <= patience:
        return False

    min_delta = abs(min_delta)
    if mode == 'min':
      min_delta *= -1
    else:
      min_delta *= 1

    #last patience epochs
    last_patience_epochs = [x + min_delta for x in MetricList[::-1][1:patience + 1]]
    current_metric = MetricList[::-1][0]

    if mode == 'min':
        if current_metric >= max(last_patience_epochs):
            print(f'Metric did not decrease for the last {patience} epochs.')
            return True
        else:
            return False
    else:
        if current_metric <= min(last_patience_epochs):
            print(f'Metric did not increase for the last {patience} epochs.')
            return True
        else:
            return False

A: I've had this problem myself: (1) I want to use a custom training loop; (2) I don't want to lose the bells and whistles Keras gives me in terms of callbacks; (3) I don't want to re-implement them all myself. Tensorflow has a design philosophy of allowing a developer to gradually opt-in to its more low-level APIs. As @HyeonPhilYoun notes in his comment below, the official documentation for tf.keras.callbacks.Callback gives an example of what we're looking for.
The following has worked for me, but can be improved by reverse engineering tf.keras.Model.
The trick is to use tf.keras.callbacks.CallbackList and then manually trigger its lifecycle events from within your custom training loop. This example uses tqdm to give attractive progress bars, but CallbackList has a progress_bar initialization argument that can let you use the defaults. training_model is a typical instance of tf.keras.Model.
from tqdm.notebook import tqdm, trange

# Populate with typical keras callbacks
_callbacks = []

callbacks = tf.keras.callbacks.CallbackList(
    _callbacks, add_history=True, model=training_model)

logs = {}
callbacks.on_train_begin(logs=logs)

# Presentation
epochs = trange(
    max_epochs,
    desc="Epoch",
    unit="Epoch",
    postfix="loss = {loss:.4f}, accuracy = {accuracy:.4f}")
epochs.set_postfix(loss=0, accuracy=0)

# Get a stable test set so epoch results are comparable
test_batches = batches(test_x, test_Y)

for epoch in epochs:
    callbacks.on_epoch_begin(epoch, logs=logs)

    # I like to formulate new batches each epoch
    # if there are data augmentation methods in play
    training_batches = batches(x, Y)

    # Presentation
    enumerated_batches = tqdm(
        enumerate(training_batches),
        desc="Batch",
        unit="batch",
        postfix="loss = {loss:.4f}, accuracy = {accuracy:.4f}",
        position=1,
        leave=False)

    for (batch, (x, y)) in enumerated_batches:
        training_model.reset_states()

        callbacks.on_batch_begin(batch, logs=logs)
        callbacks.on_train_batch_begin(batch, logs=logs)

        logs = training_model.train_on_batch(x=x, y=Y, return_dict=True)

        callbacks.on_train_batch_end(batch, logs=logs)
        callbacks.on_batch_end(batch, logs=logs)

        # Presentation
        enumerated_batches.set_postfix(
            loss=float(logs["loss"]),
            accuracy=float(logs["accuracy"]))

    for (batch, (x, y)) in enumerate(test_batches):
        training_model.reset_states()

        callbacks.on_batch_begin(batch, logs=logs)
        callbacks.on_test_batch_begin(batch, logs=logs)

        logs = training_model.test_on_batch(x=x, y=Y, return_dict=True)

        callbacks.on_test_batch_end(batch, logs=logs)
        callbacks.on_batch_end(batch, logs=logs)

    # Presentation
    epochs.set_postfix(
        loss=float(logs["loss"]),
        accuracy=float(logs["accuracy"]))

    callbacks.on_epoch_end(epoch, logs=logs)

    # NOTE: This is a decent place to check on your early stopping
    # callback.
    # Example: use training_model.stop_training to check for early stopping

callbacks.on_train_end(logs=logs)

# Fetch the history object we normally get from keras.fit
history_object = None
for cb in callbacks:
    if isinstance(cb, tf.keras.callbacks.History):
        history_object = cb
assert history_object is not None

A: I tested @Rob Hall's method with tensorboard callbacks and it did indeed work. So in my case it looked like this:
'''
tensorboard_callback = keras.callbacks.TensorBoard(
    log_dir='./callbacks/tensorboard',
    histogram_freq=1)

_callbacks = [tensorboard_callback]
callbacks = keras.callbacks.CallbackList(
    _callbacks, add_history=True, model=encoder)

    logs_ae = {}
    callbacks.on_train_begin(logs=logs_ae)
...
...

'''


text:
Q: Fullscreen YouTube Video as Background without Share/Watch Later/Icon/Start Button

import React from "react";
import tree from "../components/tree";

function HomePage() {
  return (

      "

  );
}

export default HomePage;
.videoContainer {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

iframe {
    width: 100%;
    height:100%
}

.screen {
    position: fixed;
    z-index: -99;
    width: 100%;
    height: 100%;
}

I'm working on a project that needs to use YouTube video as fullscreen background when user visits the page, I read through a lot of articles and tried, but I am only able to remove the control bar, not the icon of the left, share and watch later on the right, and the start button on the center, I'm using react on the project, basically just need the page to load with video as fullscreen background, nothing else, can somebody help please?  Thank you.

A: This is because by default the youtube embedding links have these features automatically build-in. You can see this by visiting this /embed/ example. So, in short you need to update your src link or just use something like CSS selectors to ignore the button tags that coorespond with the following classes: ytp-share-button and ytp-watch-later-button. You could do something like this...
.ytp-share-button {
  display:none
}


text:
Q: Detect malicious script or reason creating lots of smtp connection My VPS was suspended due to lots of SMTP connection(over 2000) per hour. But I am pretty sure none of my script was sending mail. I am using google apps and live service for mail. I have blocked my port 25 using Fuser as mentioned in a SF thread as well as in iptable. I have added a php wrapper to detect php scripts sending mail. But til now I can't detect any.
The log entry look like:
Sep 10 19:24:52 myservername postfix/error[31297]: 698105A75F9F: to=<georgina_taylor@oneofmydomain.com>, relay=none, delay=71958, delays=71958/0.01/0/0, dsn=4.4.2, status=deferred (delivery temporarily suspended: lost connection with cfxxx603c2d730000000fb12eaf.pamx1.hotmail.com[65.54.188.78] while sending RCPT TO)

Note I don't have any user called georgina_taylor and there are lots of similar entry with different recipient having @oneofmydomain.com.
All log entries associated with 69810575F9F is as below:
Sep  9 23:25:34 myservername postfix/cleanup[29650]: 698105A75F9F: message-id=<20130909192534.698105A75F9F@myserverhostname>
Sep  9 23:25:34 myservername postfix/bounce[31209]: 0D1495A74808: sender non-delivery notification: 698105A75F9F
Sep  9 23:25:34 myservername postfix/error[31205]: 698105A75F9F: to=<georgina_taylor@oneofmydomain.com>, relay=none, delay=0.1, delays=0.06/0.04/0/0.01, dsn=4.4.2, status=deferred (delivery temporarily suspended: lost connection with cf5ff603c2d73d459329de7fb12eaf.pamx1.hotmail.com[65.54.188.109] while sending RCPT TO)
Sep  9 23:34:51 myservername postfix/error[32597]: 698105A75F9F: to=<georgina_taylor@oneofmydomain.com>, relay=none, delay=557, delays=557/0/0/0, dsn=4.4.2, status=deferred (delivery temporarily suspended: lost connection with cf5ff603c2d73d459329de7fb12eaf.pamx1.hotmail.com[65.54.188.78] while sending RCPT TO)
Sep  9 23:44:48 myservername postfix/qmgr[1179]: 698105A75F9F: from=<>, size=3681, nrcpt=1 (queue active)
Sep  9 23:44:48 myservername postfix/smtp[2008]: 698105A75F9F: host cf5ff603c2d73d459329de7fb12eaf.pamx1.hotmail.com[65.54.188.78] said: 421 RP-001 (BAY0-PAMC1-F7) Unfortunately, some messages from myip weren't sent. Please try again. We have limits for how many messages can be sent per hour and per day. You can also refer to http://mail.live.com/mail/troubleshooting.aspx#errors. (in reply to MAIL FROM command)
Sep  9 23:44:48 myservername postfix/smtp[2008]: 698105A75F9F: lost connection with cf5ff603c2d73d459329de7fb12eaf.pamx1.hotmail.com[65.54.188.78] while sending RCPT TO
Sep  9 23:44:48 myservername postfix/smtp[2008]: 698105A75F9F: to=<georgina_taylor@oneofmydomain.com>, relay=cf5ff603c2d73d459329de7fb12eaf.pamx1.hotmail.com[65.54.188.109]:25, delay=1154, delays=1154/0.02/0.15/0.01, dsn=4.0.0, status=deferred (host cf5ff603c2d73d459329de7fb12eaf.pamx1.hotmail.com[65.54.188.109] said: 421 RP-001 (BAY0-PAMC2-F8) Unfortunately, some messages from my ip weren't sent. Please try again. We have limits for how many messages can be sent per hour and per day. You can also refer to http://mail.live.com/mail/troubleshooting.aspx#errors. (in reply to MAIL FROM command))
Sep 10 00:04:55 myservername postfix/qmgr[1179]: 698105A75F9F: from=<>, size=3681, nrcpt=1 (queue active)
Sep 10 00:04:55 myservername postfix/error[2961]: 698105A75F9F: to=<georgina_taylor@oneofmydomain.com>, relay=none, delay=2361, delays=2361/0/0/0, dsn=4.4.2, status=deferred (delivery temporarily suspended: lost connection with cf5ff603c2d73d459329de7fb12eaf.pamx1.hotmail.com[65.54.188.109] while sending RCPT TO)

All log entries associated with 0D1495A74808
Sep  8 01:13:36 myserver postfix/qmgr[1177]: 0D1495A74808: from=<georgina_taylor@oneofmydomain>, size=1640, nrcpt=1 (queue active)
Sep  8 01:16:07 myserver postfix/smtp[20152]: 0D1495A74808: to=<miles316@gateway.net>, relay=none, delay=266989, delays=266839/0.12/150/0, dsn=4.4.1, status=deferred (connect to gateway.net[64.12.89.186]:25: Connection timed out)
Sep  8 02:23:58 myserver postfix/qmgr[1177]: 0D1495A74808: from=<georgina_taylor@oneofmydomain>, size=1640, nrcpt=1 (queue active)
Sep  8 02:24:56 myserver postfix/error[1322]: 0D1495A74808: to=<miles316@gateway.net>, relay=none, delay=271119, delays=271061/58/0/0, dsn=4.4.1, status=deferred (delivery temporarily suspended: connect to gateway.net[64.12.79.57]:25: Connection timed out)
Sep  8 03:32:32 myserver postfix/qmgr[1177]: 0D1495A74808: from=<georgina_taylor@oneofmydomain>, size=1640, nrcpt=1 (queue active)
Sep  8 03:34:33 myserver postfix/error[14116]: 0D1495A74808: to=<miles316@gateway.net>, relay=none, delay=275295, delays=275174/121/0/0, dsn=4.4.1, status=deferred (delivery temporarily suspended: connect to gateway.net[205.188.101.58]:25: Connection timed out)
Sep  8 04:44:13 myserver postfix/smtp[18671]: 0D1495A74808: to=<miles316@gateway.net>, relay=none, delay=279476, delays=279326/0.02/150/0, dsn=4.4.1, status=deferred (connect to gateway.net[205.188.101.58]:25: Connection timed out)
Sep  8 05:52:11 myserver postfix/qmgr[1177]: 0D1495A74808: from=<georgina_taylor@oneofmydomain>, size=1640, nrcpt=1 (queue active)
Sep  8 05:54:41 myserver postfix/smtp[25035]: 0D1495A74808: to=<miles316@gateway.net>, relay=none, delay=283704, delays=283554/0.02/150/0, dsn=4.4.1, status=deferred (connect to gateway.net[64.12.79.57]:25: Connection timed out)
Sep  8 07:03:55 myserver postfix/smtp[31497]: 0D1495A74808: to=<miles316@gateway.net>, relay=none, delay=287857, delays=287707/0.03/150/0, dsn=4.4.1, status=deferred (connect to gateway.net[64.12.89.186]:25: Connection timed out)

A: The 'last' command will show you recent logins to your server with associated ip addresses. My guess is that someone compromised your password and is running a script to send spam. ps -ef should show a list of running processes on the vps. perhaps there is something that does not belong?
The other common suspect is an insecure mail form on a webpage you host. If your wrapper for mail is working as expected this should be caught with that mechanism.

A: I have seen automated PERL scripts running under /tmp doing that kind of damage.
See if you can find anything suspicious running under /tmp including files starting with a dot that contain code


text:
Q: ssl erros sending mail using devise in rails 6 I am deploying rails 6 in production. I am testing the mail function of devise and I am getting this error
OpenSSL::SSL::SSLError (hostname "localhost" does not match the server certificate):

how can I fix this?
Thanks

A: The problem
If you encounter this problem when running Ruby on Rails:
OpenSSL::SSL::SSLError (hostname "localhost" does not match the server certificate)
it is likely due to ActionMailer using the smtp as the delivery_method and your local mail server supporting TLS/SSL, but not having a correct/valid certificate.
The solution
You can add a valid certificate, but if the server is just used for sending out mails, this may not be suited. In that case, you can change the delivery_method to sendmail, which makes ActionMailer use the sendmail binary directly.
source


text:
Q: Sessions variable unseen in multiple pages I don't understand the thing with sessions in php. It says that after you start a session, the session variable are stored and can be seen in multiple pages.But in my pages that are not seen. For example I have my index.php page where I start the session_start(). Then I click a button to login and if everything is ok it should redirect me to profile.php page where I print the session email. But it doesn't recognize my session variable.My code:
if($_POST['actiune'] == 'login'){

$email = $_POST['email'];
$_SESSION['username'] = $email;
$password = $_POST['password'];
$pass = getPassword($email);
$verify = password_verify($password, $pass);
    if ($verify) {
        header("Location: index.php?page=profile");
    }
    else {
        header("Location: index.php?page=login&msg=PleaseRegister");
    }
}

profile.php
echo $_SESSION['username'] ; die();

Any help?
UPDATE:
profile.php
 <?php
 session_start();
 echo $_SESSION['username'] ;

 ?>

Welcome :<?php echo $_SESSION['username']; ?>

<?php
    if ($_SESSION['avatar'] == ""){
        ?>

        <?php
    }
    else if ($_SESSION['avatar'] != ""){
        ?>
        <img src="avatars/<?php echo $user['file'];?>">
        <?php
    }
?>

 Modify

 Reset password

 Article page

<form action="action.scripts.php" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="actiune" value="avatar">
    <input type="hidden" name="id" value="<?php echo $user['id'];?>">

Upload an avatar:

<input type="file" name="avatar" id="fileToUpload">

<input id ="button" class="btn btn-primary" type="submit" name="button" value="Send"/>

</form>

A: You need session_start() at the top of every page request - exactly one time per request. It doesn't just create the session; it's required for every request in which you want to use the session. From the docs:

session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.

A: You need to call session_start(); in profile.php also.

session_start() creates a session or resumes the current one based on
  a session identifier passed via a GET or POST request, or passed via a
  cookie.

Update
<?php
    if(!isset($_SESSION))
    {
       session_start();
    }

    if (isset($_SESSION['username'])){
?>

Welcome :<?php echo $_SESSION['username']; ?>

            <?php if ($_SESSION['avatar'] == ""){ ?>

            <?php
                }
                else if ($_SESSION['avatar'] != ""){
            ?>
                <img src="avatars/<?php echo $user['file'];?>">
            <?php
                }
            ?>

 Modify

 Reset password

 Article page

            <form action="action.scripts.php" method="POST" enctype="multipart/form-data">
                <input type="hidden" name="actiune" value="avatar">
                <input type="hidden" name="id" value="<?php echo $user['id'];?>">

Upload an avatar:

<input type="file" name="avatar" id="fileToUpload">

<input id ="button" class="btn btn-primary" type="submit" name="button" value="Send"/>

            </form>

<?php
    }
    else {
        echo '
';
        var_dump($_SESSION);
        echo '
';
    }
?>

Index.php
   <?php
        session_start();

        if($_POST['actiune'] == 'login'){
            $email = $_POST['email'];
            $_SESSION['username'] = $email;
            $password = $_POST['password'];
            $pass = getPassword($email);
            $verify = password_verify($password, $pass);
            if ($verify) {
                header("Location: index.php?page=profile");
            }
            else {
                header("Location: index.php?page=login&msg=PleaseRegister");
            }
        }
        else {
            echo 'POST actiune is not login';
        }
    ?>


text:
Q: Azure UserDelegation Key Exception I am trying to generate UserDelegationKey for my Azure Storage Blob but i am getting an exception:

Can not instantiate Stax reader for XML source type class org.codehaus.stax2.io.Stax2ByteArraySource (unrecognized type)

This Exception occurs when i call getUserDelegationKey on BlobContainerAsyncClient
Version of my azure-storage-blob library is 12.12.0
Below is the code snippet
 private void uploadNextWeekReportToAzure() {
    BlobServiceAsyncClient blobServiceAsyncClient = blobServiceClientBuilder
        .credential(new DefaultAzureCredentialBuilder().build())
        .buildAsyncClient();
    BlobContainerAsyncClient blobContainerAsyncClient = blobServiceAsyncClient.getBlobContainerAsyncClient("container name");
    BlobAsyncClient blobAsyncClient = blobContainerAsyncClient.getBlobAsyncClient("blob name");
    OffsetDateTime keyStart = OffsetDateTime.now();
    OffsetDateTime keyExpiry = OffsetDateTime.now().plusDays(7);
    blobServiceAsyncClient.getUserDelegationKey(keyStart,keyExpiry)
    .doOnError(throwable -> log.error("Exception occurred:{}",throwable.getMessage()))
    .doOnSuccess(userDelegationKey -> {
      log.info("UserDelegationKey:{}",userDelegationKey.getValue());
      String saSToken = generateSaSToken(blobAsyncClient, userDelegationKey);
      log.info("SAS TOKEN:{}",saSToken);
    })
    .subscribe();
  }

private String generateSaSToken(BlobAsyncClient blobAsyncClient,
                                  UserDelegationKey userDelegationKey) {
    BlobContainerSasPermission blobContainerSasPermission = new BlobContainerSasPermission()
        .setReadPermission(true);
    BlobServiceSasSignatureValues builder = new BlobServiceSasSignatureValues(
        OffsetDateTime.now().plusDays(1), blobContainerSasPermission)
        .setProtocol(SasProtocol.HTTPS_ONLY);
    return String
        .format("https://%s.blob.core.windows.net/%s/%s?%s", blobAsyncClient.getAccountName(),
            blobAsyncClient.getContainerName(),
            blobAsyncClient.getBlobName(),
            blobAsyncClient.generateUserDelegationSas(builder, userDelegationKey));
  }

Complete Exception Trace:

CallbackNotImplemented: java.lang.IllegalArgumentException: Can not instantiate Stax reader for XML source type class org.codehaus.stax2.io.Stax2ByteArraySource (unrecognized type)
Caused by: java.lang.IllegalArgumentException: Can not instantiate Stax reader for XML source type class org.codehaus.stax2.io.Stax2ByteArraySource (unrecognized type)
at io.strati.libs.forklift.com.ctc.wstx.stax.WstxInputFactory.createSR(WstxInputFactory.java:770)
at io.strati.libs.forklift.com.ctc.wstx.stax.WstxInputFactory.createXMLStreamReader(WstxInputFactory.java:345)
at com.fasterxml.jackson.dataformat.xml.XmlFactory._createParser(XmlFactory.java:631)
at com.fasterxml.jackson.dataformat.xml.XmlFactory._createParser(XmlFactory.java:29)
at com.fasterxml.jackson.core.JsonFactory.createParser(JsonFactory.java:1124)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3643)
at com.azure.core.util.serializer.JacksonAdapter.deserialize(JacksonAdapter.java:281)
at com.azure.core.implementation.serializer.HttpResponseBodyDecoder.deserializeBody(HttpResponseBodyDecoder.java:169)
at com.azure.core.implementation.serializer.HttpResponseBodyDecoder.lambda$decodeByteArray$1(HttpResponseBodyDecoder.java:105)
at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:125)
at reactor.core.publisher.Operators$ScalarSubscription.request(Operators.java:2397)
at reactor.core.publisher.MonoFlatMap$FlatMapMain.onSubscribe(MonoFlatMap.java:110)
at reactor.core.publisher.MonoJust.subscribe(MonoJust.java:54)
at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52)
at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64)
at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52)
at reactor.core.publisher.MonoCacheTime.subscribeOrReturn(MonoCacheTime.java:143)
at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:57)
at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:157)
at reactor.core.publisher.FluxContextWrite$ContextWriteSubscriber.onNext(FluxContextWrite.java:107)
at reactor.core.publisher.FluxDoOnEach$DoOnEachSubscriber.onNext(FluxDoOnEach.java:173)
at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1815)
at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:151)
at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:120)
at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onNext(FluxOnErrorResume.java:79)
at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1815)
at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:151)
at reactor.core.publisher.FluxDelaySubscription$DelaySubscriptionMainSubscriber.onNext(FluxDelaySubscription.java:188)
at reactor.core.publisher.SerializedSubscriber.onNext(SerializedSubscriber.java:99)
at reactor.core.publisher.SerializedSubscriber.onNext(SerializedSubscriber.java:99)
at reactor.core.publisher.FluxTimeout$TimeoutMainSubscriber.onNext(FluxTimeout.java:179)
at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1815)
at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:151)
at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.complete(MonoIgnoreThen.java:284)
at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.onNext(MonoIgnoreThen.java:187)
at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:127)
at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:127)
at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1815)
at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:151)
at reactor.core.publisher.SerializedSubscriber.onNext(SerializedSubscriber.java:99)
at reactor.core.publisher.FluxRetryWhen$RetryWhenMainSubscriber.onNext(FluxRetryWhen.java:173)
at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onNext(FluxOnErrorResume.java:79)
at reactor.core.publisher.Operators$MonoInnerProducerBase.complete(Operators.java:2663)
at reactor.core.publisher.MonoSingle$SingleSubscriber.onComplete(MonoSingle.java:180)
at reactor.core.publisher.MonoFlatMapMany$FlatMapManyInner.onComplete(MonoFlatMapMany.java:260)
at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onComplete(FluxMapFuseable.java:150)
at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onComplete(FluxMapFuseable.java:150)
at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1816)
at reactor.core.publisher.MonoCollect$CollectSubscriber.onComplete(MonoCollect.java:159)
at reactor.core.publisher.FluxDoFinally$DoFinallySubscriber.onComplete(FluxDoFinally.java:145)
at reactor.core.publisher.FluxHandle$HandleSubscriber.onComplete(FluxHandle.java:212)
at reactor.core.publisher.FluxMap$MapConditionalSubscriber.onComplete(FluxMap.java:269)
at reactor.netty.channel.FluxReceive.onInboundComplete(FluxReceive.java:401)
at reactor.netty.channel.ChannelOperations.onInboundComplete(ChannelOperations.java:416)
at reactor.netty.channel.ChannelOperations.terminate(ChannelOperations.java:470)
at reactor.netty.http.client.HttpClientOperations.onInboundNext(HttpClientOperations.java:685)
at reactor.netty.channel.ChannelOperationsHandler.channelRead(ChannelOperationsHandler.java:94)

A: Try this code to generate user delegation key and SAS
String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", "accountName");,
blobServiceClient = new BlobServiceClientBuilder().endpoint(endpoint).credential(new DefaultAzureCredentialBuilder().build()).buildClient();
keyStart = OffsetDateTime.now();
keyExpiry = OffsetDateTime.now().plusDays(7);
userDelegationKey = blobServiceClient.getUserDelegationKey(keyStart, keyExpiry);
BlobContainerSasPermission blobContainerSas = new BlobContainerSasPermission();
blobContainerSas.setReadPermission(true);
BlobServiceSasSignatureValues blobServiceSasSignatureValues = new BlobServiceSasSignatureValues(keyExpiry,blobContainerSas);
BlobContainerClient blobContainerClient=blobServiceClient.getBlobContainerClient("containerName");
if (!blobContainerClient.exists())
    blobContainerClient.create();
String sas = blobContainerClient.generateUserDelegationSas(blobServiceSasSignatureValues, userDelegationKey);

For more information refer  this link
You may also check this method to Generate Key
The Get User Delegation Key operation gets a key that can be used to sign a user delegation SAS (shared access signature). A user delegation SAS grants access to resources in the Blob service using Azure Active Directory (Azure AD) credentials.
For more information refer  this link


text:
Q: $\tilde{T} : X/X_0 \to Y $ is also compact In a normed linear space N, let $B=\{x \in N : |x| <1\}$ . Then define a linear map  $T :N \to N_1$ ,( $N_1$ some normed linear space ) to be compact if  closure of $T(\bar{B})$ is compact in $N_1$ . With this definition I was trying to prove :

X,Y Banach space. $T : X \to Y$ compact, $X_0$ closed subspace of $X$ s.t. $X_0 \subset Ker(T)$, Then $\tilde{T} : X/X_0 \to Y $ is also compact.

I couldn't figure out how to proceed. Thanks in advance for help!

A: Let $B'=\{x\in X/X_0: |x|<1\}$, $\bar T(B')=T(B)$ since by definition of the norm of a quotient space if $p:X\rightarrow X/X_0$ is the quotient map, $p(B)=B'$. Since $T=\bar T\circ p$ we deduce that $T(B)=\bar T(B')$.


text:
Q: Xamarin File Storage Question:
I know how to Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),  "SomeFile.txt");
But my question is when using emulator where does it store it or is it only in memory?
Thanks.

A: on Android, files are stored in the file system within the emulator image.  You can use adb to access the files.
on iOS, the emulator file system is mapped onto the MacOS file system.  You can get the full file path in code and then just access the files from Terminal or Finder


text:
Q: How do I install command line tools without installing Xcode? I would like to install command line tools without installing Xcode as it is more than 4GB and I don't want to waste that much space since all I need are the command line tools.
I have used xcode-select --install command but I still get an error message
active developer path ("/Applications/Xcode 2.app/Contents/Developer") does not exist, use `xcode-select --switch path/to/Xcode.app` to specify the Xcode that you wish to use for command line developer tools (or see `man xcode-select`)

Does anybody have an idea?

A: Go to Apple Developer, login with a valid Apple ID, search for "command line tools", download an appropriate version, open the dmg and finally install the tools.
Here is a direct link (which still requires an Apple ID!) to the latest non-beta version: Command Line Tools OS X 10.11 for Xcode 7.1


text:
Q: Ant JUnit failure with french thousands separator Using Netbeans 6.9.1 my unit tests pass without issue.  Using junit (4.8.2, which seems to be the same version that Netbeans uses) the tests fail on the command line.
The failure has to do with this line:
assertEquals("x doit être >= 10 et < 100, était la suivante: 1 000", messages_fr.between("x", 10, 100, 1000));

On the command line the message displays as:

x doit être >= 10 et < 100, était la
  suivante: 1á000

I am at a loss for what is going on.  I know that the thousands separator is not a space but 0XA0, no issue with that, but the fact that Netbeans and the command line are in disagreement about it is a real issue.
I am using ant 1.8.1 which is also the same version as Netbeans.   It happens on OS X (10.6.5) and Windows 7.  I still need to check Ubuntu 10.10.
Any ideas why it works in Netbeans but not on the command line in ant?

A: Note the inconsistency in the output: ê and é look like UTF-8 displayed as CP437, whereas no-break space looks like Windows-1252 displayed as CP437.
Let's put aside the fact that the console encoding (CP437) doesn't match the system encoding (Windows-1252). Then I assume that no-break space is represented properly, since it comes from the runtime library. This means that UTF-8 in representation of the message is an error. Perhaps template of your message is stored in UTF-8, but loaded as Windows-1252. If this template is stored in the code, you need to set compiler encoding to UTF-8.

A: I think you problem is the encoding. You can try to change the encoding of your Java class (from ISO to UTF or viceversa).
If this doesn't work, you can try to configure Ant to use the same encoding Netbeans does.
If this doesn't work too, you can try to write a method that convert your message in another message without special characters.
In Spain we have the same problems, and many times we write every string with no special character (not the best solution, but it works).


text:
Q: UCAExc:::4.0.1 access denied exception running in applet code via the appletviewer utility public class SetupExam extends Applet {
    /**
     *
     */
    private static final long serialVersionUID = -4106575420788590877L;
    private JTextField td_tf;
    private JTextField mfeq_tf;
    private JTextField nmfe_tf;

    /**
     * Create the applet.
     */
    public SetupExam() {
        setLayout(null);
        JLabel main_l = new JLabel("Exam");
        main_l.setHorizontalAlignment(SwingConstants.CENTER);
        main_l.setFont(new Font("Arial", Font.BOLD, 15));
        main_l.setBounds(7, 4, 601, 42);
        add(main_l);

        JLabel cat_l = new JLabel("1.Category");
        cat_l.setFont(new Font("Arial", Font.PLAIN, 15));
        cat_l.setBounds(16, 80, 162, 32);
        add(cat_l);

        JLabel td_l = new JLabel("2.Time Duration");
        td_l.setFont(new Font("Arial", Font.PLAIN, 15));
        td_l.setBounds(16, 130, 162, 32);
        add(td_l);

        JLabel noq_l = new JLabel("3.Number of Questions");
        noq_l.setFont(new Font("Arial", Font.PLAIN, 15));
        noq_l.setBounds(13, 184, 165, 32);
        add(noq_l);

        JLabel mfeq_l = new JLabel("4.Marks for each Question");
        mfeq_l.setFont(new Font("Arial", Font.PLAIN, 15));
        mfeq_l.setBounds(13, 236, 178, 32);
        add(mfeq_l);

        JLabel nmfe_l = new JLabel("5.Negtive Mark For Each");
        nmfe_l.setFont(new Font("Arial", Font.PLAIN, 15));
        nmfe_l.setBounds(13, 293, 178, 32);
        add(nmfe_l);

        JComboBox cat_combo = new JComboBox();
        cat_combo.setEditable(true);
        cat_combo.setBounds(237, 80, 208, 32);
        add(cat_combo);

        td_tf = new JTextField();
        td_tf.setBounds(237, 130, 208, 32);
        add(td_tf);
        td_tf.setColumns(10);

        mfeq_tf = new JTextField();
        mfeq_tf.setColumns(10);
        mfeq_tf.setBounds(237, 236, 208, 32);
        add(mfeq_tf);

        nmfe_tf = new JTextField();
        nmfe_tf.setColumns(10);
        nmfe_tf.setBounds(237, 293, 208, 32);
        add(nmfe_tf);

        JSpinner noq_spin = new JSpinner();
        noq_spin.setModel(new SpinnerNumberModel(10, 1, 100, 1));
        noq_spin.setBounds(237, 180, 208, 32);
        add(noq_spin);

        JButton sbmt_btn = new JButton(mfun());
        sbmt_btn.setFont(new Font("Arial", Font.PLAIN, 12));
        sbmt_btn.setBounds(228, 383, 126, 41);
        add(sbmt_btn);

    }
    public String mfun()
    {
        try
        {
         Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
        Connection con=DriverManager.getConnection("jdbc:ucanaccess://C:\\workspace\\exam.mdb");
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery("Select * from  exam_setup");
        while (rs.next())
            {
                //System.out.println(rs.getString(3));
                return rs.getString(3);

            }
         } catch (Exception ex)
                   {
                System.err.print("Exception: ");
                System.err.println(ex.getMessage());
                   }
        return null;

    }

}

I am using Ucanacess 4.0.1.
Before this I checked connectivity by inserting data in table exam through a Java program but it's not working when I added the code in my applet.
I used following command to run applet
appletviewer ExamSystem.html

output:

Exception: UCAExc:::4.0.1 access denied ("java.util.logging.LoggingPermission" "control")

A: The appletviewer utility apparently runs the applet code in a restricted environment, most likely similar to the "sandbox" that would be used for an unsigned applet. UCanAccess was not designed to run in such an environment.


text:
Q: If Exist inside of For loop I am having trouble getting this code to work after modifying it to accept multiple arguments. I am getting "( was unexpected at this time." at the second for loop. (Line 23).
Any idea if it's even possible to have these if groups inside of a for loop? From what I've seen it is possible.
Instead of the if exist group. I could just use an IF NOT EXIST but I don't know how to make it to skip the rest of the code in the loop for the current item, but continue for the loop for the next item. I'm unable to find how to do this, and only found how to exit the loop entirely which I don't want to do.
@echo off
:variables
set script_dir="E:\Plex Scripts\DVR"
set script1=MCEBuddyScriptv2.bat
set method2=GPU
set script2=ScanMedia%method2%.ps1
set extension=mkv
set logfile=post_processing_log.txt
set history=history.txt
:change_directory
cd /d %script_dir%
:method
setlocal enabledelayedexpansion
:counter
set argCount=0
for %%x in (%*) do (
    set /A argCount+=1
    set "argVec[!argCount!]=%%~x"
)
::How many videos we will attempt to process
echo Number of files to process: %argCount%
:loop_start
for /L %%i in (1,1,%argCount%) do (
    set fullpath=!argVec[%%i]!
    ::get new filepath (with new extension)
    REM :names
    for %%f in (!fullpath!) do set itemname=%%~nf
    for %%f in (!fullpath!) do set newpath=%%~dpnf.%extension%
    ::if logfile doesn't exist then create it
    REM :log_init
    if not exist %logfile% echo This log file is a detailed history of the DVR Post Process scipt. >> %logfile%
    if not exist %history% echo This is a history of the items processed with the DVR Post Process script. >> %history%
    ::check if input file exist
    REM :check
    if exist ( !fullpath! ) (
        REM :script1
        set state=Processing started
        echo %date% - %time% - !state! for !itemname! with %script1% >> %logfile%
        call %script1% !fullpath!
        set state=Processing finished
        echo %date% - %time% - !state! for !itemname! with %script1% >> %logfile%
        REM :script2
        set state=Processing started
        echo %date% - %time% - !state! for !itemname! with %script2% >> %logfile%
        powershell.exe -NoProfile -ExecutionPolicy Bypass -File %script2% -Path "!newpath!" -LimitCPU -AutoRepair -RemoveOriginal -RemoveRepaired -IAcceptResponsibility
        set state=Processing finished
        echo %date% - %time% - !state! for !itemname! with %script2% >> %logfile%
        REM :log_final
        echo %date% - %time% - Plex post processing script finished for !itemname!. The file will be moved and added to the library. >> %logfile%
        echo. >> %logfile%
        REM :history_final
        echo %date% - %time% - !itemname! >> %history%
    ) else (
        echo %date% - %time% - !itemname! does not exist. Error code 1. >> %logfile%
    )
)
:end
exit /b 0

Edit: Got it to work by removing the parenthesis from the "if exist ( !fullpath! ) ..."
I'm not sure why that even worked initially, before putting inside the for loop. Anyway here is the final code.
@echo off

:variables
set script_dir="E:\Plex Scripts\DVR"
set script1=MCEBuddyScriptv2.bat
set method2=GPU
set script2=ScanMedia%method2%.ps1
set extension=mkv
set logfile=post_processing_log.txt
set history=history.txt

:change_directory
cd /d %script_dir%

:method
setlocal enabledelayedexpansion

:counter
set argCount=0
for %%x in (%*) do (
    set /A argCount+=1
    set "argVec[!argCount!]=%%~x"
)
::How many videos we will attempt to process
echo Number of files to process: %argCount%

:loop_start
for /L %%i in (1,1,%argCount%) do (
    set fullpath="!argVec[%%i]!"
    echo !fullpath!

    ::get new filepath (with new extension)
    :names
    for %%f in (!fullpath!) do set itemname=%%~nf
    echo !itemname!
    for %%f in (!fullpath!) do set newpath=%%~dpnf.%extension%
    echo !newpath!

    ::if logfile doesn't exist then create it
    :log_init
    if not exist %logfile% echo This log file is a detailed history of the DVR Post Process scipt. >> %logfile%
    if not exist %history% echo This is a history of the items processed with the DVR Post Process script. >> %history%

    ::check if input file exist
    :check
    if exist !fullpath! (
        :script1
        set state=Processing started
        echo %date% - %time% - !state! for !itemname! with %script1% >> %logfile%
        call %script1% !fullpath!
        set state=Processing finished
        echo %date% - %time% - !state! for !itemname! with %script1% >> %logfile%

        :script2
        set state=Processing started
        echo %date% - %time% - !state! for !itemname! with %script2% >> %logfile%
        powershell.exe -NoProfile -ExecutionPolicy Bypass -File %script2% -Path "!newpath!" -LimitCPU -AutoRepair -RemoveOriginal -RemoveRepaired -IAcceptResponsibility
        set state=Processing finished
        echo %date% - %time% - !state! for !itemname! with %script2% >> %logfile%

        :log_final
        echo %date% - %time% - Plex post processing script finished for !itemname!. The file will be moved and added to the library. >> %logfile%
        echo. >> %logfile%

        :history_final
        echo %date% - %time% - !itemname! >> %history%
    ) else (
        echo %date% - %time% - !itemname! does not exist. Error code 1. >> %logfile%
    )
)
:end
exit /b 0

A: if /?

Performs conditional processing in batch programs.

IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command

There are no parentheses around the filename token. Use
if exist !fullpath! (

or even
if exist "!fullpath!" (


text:
Q: Why is the performance of ogr methods different on different OS? This question actually comes forth from an earlier question of mine
.
A short introduction. I was writing a program that performs near analysis and creates buffers for a set of points. On my Linux Ubuntu machine this turned out to be really slow. Hence the earlier mentioned question of mine.
When running the same code on my OSX it was tremendously fast. At least n comparison to the results I was getting on Ubuntu.
Here are my results
Method     | OSX            | Linux Ubuntu

ogr buffer | 0:00:01.434389 | 0:01:08.384309

sub string | 0:00:19.714432 | 0:00:10.048649

sorted set | 0:00:01.239999 | 0:00:00.600773

So my question really is: why are there such great performance difference with OGR?
Specs Mac OSX
Processor 4x2.5 GHz
Memory 8 GB 1600 MHz

Specs Dell Linux Ubuntu
Processor 8x3.4GHz
Memory 7.8 GB


text:
Q: ZF3 - An event attached to the EventManager does not trigger I have got an EntityRepository class and I want to attach an event to its "save" method. Here is the AbstractRepository class where I set identifier of the event manager:
abstract class AbstractRepository extends EntityRepository implements RepositoryInterface
{
    /**
     * @var EventManagerInterface
     */
    protected $events;

    /**
     * Set the event manager instance used by this context.
     *
     * @param EventManagerInterface $events
     *
     * @return mixed
     */
    public function setEventManager(EventManagerInterface $events)
    {
        $events->setIdentifiers([
            __CLASS__,
            get_class($this),
        ]);

        $this->events = $events;

        return $this;
    }

    /**
     * Retrieve the event manager.
     *
     * Lazy-loads an EventManager instance if none registered.
     *
     * @return EventManagerInterface
     */
    public function getEventManager()
    {
        if (!$this->events) {
            $this->setEventManager(new EventManager());
        }

        return $this->events;
    }
}

and the repository class called DocumentRepository:
class DocumentsRepository extends AbstractRepository
{
    public function save(Documents $entity)
    {
        $this->getEventManager()->trigger(RepositoryInterface::EVENT_BEFORE_SAVE);

        $this->getEntityManager()->persist($entity);
        $this->getEntityManager()->flush($entity);

        $this->getEventManager()->trigger(RepositoryInterface::EVENT_AFTER_SAVE);

        return $entity;
    }
}

Also an interface to define event names:
interface RepositoryInterface extends EventManagerAwareInterface
{
    const EVENT_BEFORE_SAVE   = 'before.save';
    const EVENT_AFTER_SAVE    = 'after.save';
}

To register the listener I added the following code to module.php.
public function onBootstrap(MvcEvent $event)
{
    $application    = $event->getApplication();
    $eventManager   = $application->getEventManager();

    /* Register event listener(s) */
    (new DocumentsRepositoryListener($serviceManager))->attach($eventManager);
}

And finally, added the listener class:
class DocumentsRepositoryListener extends AbstractListener implements ListenerAggregateInterface
{
    public function attach(EventManagerInterface $events, $priority = 1)
    {
        $sharedEvents = $events->getSharedManager();

        $this->listeners[] = $sharedEvents
            ->attach(DocumentsRepository::class, RepositoryInterface::EVENT_BEFORE_SAVE, [$this, 'beforeSave']);
        $this->listeners[] = $sharedEvents
            ->attach(DocumentsRepository::class, RepositoryInterface::EVENT_AFTER_SAVE, [$this, 'afterSave']);
    }

    public function detach(EventManagerInterface $events)
    {
        foreach ($this->listeners as $index => $listener) {
            if ($events->detach($listener)) {
                unset($this->listeners[$index]);
            }
        }
    }

    public function beforeSave(EventInterface $event)
    {
        /* Something to do before saving */
    }

    public function afterSave(EventInterface $event)
    {
        /* Something to do after saving */
    }
}

The class AbstractListener is also contains a constructor to inject serviceLocator and setter/getter methods.
Now, I don't know why the trigger doesn't work. Is there anything else which may be missed!?

A: The code you have written to trigger the events in DocumentsRepository has no issues. You have however a misunderstanding regarding the use of the event manager; specifically how you attach the event listeners.
The first point to make is that you have given the repository class is own instance of an EventManager; this is the instance that you should attach your event listeners to. The code in Module::onBootstrap() is registering with the application event manager,  which is the wrong instance. The application event manager deals with the application events and so it will never trigger your custom events.
/* Register event listener(s) */
(new DocumentsRepositoryListener($serviceManager))->attach($eventManager);

Would be replaced with :
$documentRepositoryListener->attach($repository->getEventManager());

The logic to register the listeners might be better suited in the RepositoryFactory, for example :
class RepositoryFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $repository = new Repository();

        if ($repository instanceof EventManagerAwareInterface) {
            $eventManager = $repository->getEventManager();
            $listener = $container->get('Foo/Event/Listener');

            $listener->attach($eventManager);
        }

        return $repository;
    }
}

Lastly, you will also need to remove the $sharedEvents usage in DocumentsRepositoryListener::attach(); as you want to attach event listeners to the repository event manager, which would be the $events argument.


text:
Q: Lubuntu won't start anymore after completely removing ubuntu-desktop I installed ubuntu-desktop, kubuntu-desktop and xubuntu-desktop on my Lubuntu.
I wanted to remove them and found this. I first used the command to remove ubuntu-desktop. While running it, I noticed that it was also deleting KDE packages.
The command took a while and I had to go away, so I locked the screen (And it used the lock screen from ubuntu-desktop). After 2 hours I came back and pressed a button to wake from standby. After that it reacted to NOTHING so I had to do a forced shutdown.
And now it won't start anymore (black screen). I can still get into Windows and safemode. I tried safemode, enabling network and running apt-get install lubuntu-desktop,  but it looks like it already is there. I tried dpkg and apt-get autoremove and doing apt-get install lubuntu-desktop again, but it still looks like it already is there. When I reboot now I do get the Lubuntu logo but after that, black screen again.
I also tried removing lubuntu-desktop and installing it again but that didn't help either.
What should I do? (except reinstalling)


text:
Q: nginx php-fpm: Permission denied while connecting to upstream Installing nginx and php-fpm make the error below not going even after setting all required permissions like suggested in previous answers here:
[error] 2443#0: *2 connect() to unix:/run/php-fpm/php-fpm.pid failed (111: Connection refused) while connecting to upstream

This all my configurations:
/etc/php-fpm.d/www.conf
[www]
user = nginx
group = nginx
listen = /run/php-fpm/php-fpm.pid
listen.owner = nginx
listen.group = nginx
listen.mode = 0660
listen.allowed_clients = 127.0.0.1

pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35

slowlog = /var/log/php-fpm/www-slow.log

php_admin_value[error_log] = /var/log/php-fpm/www-error.log
php_admin_flag[log_errors] = on
php_value[session.save_handler] = files
php_value[session.save_path]    = /var/lib/php/session
php_value[soap.wsdl_cache_dir]  = /var/lib/php/wsdlcache

/etc/php-fpm.conf
include=/etc/php-fpm.d/*.conf
[global]
pid = /run/php-fpm/php-fpm.pid
error_log = /var/log/php-fpm/error.log
daemonize = yes
events.mechanism = epoll

/etc/nginx/nginx.conf
user nginx nginx;
worker_processes 1;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
include /usr/share/nginx/modules/*.conf;
events {
    worker_connections 1024;
}
http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    access_log  /var/log/nginx/access.log  main;
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;
    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;
    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;
    upstream php {
        #server unix:/var/run/php-fpm/php-fpm.pid;
        server 127.0.0.1:9000;
    }
    server_names_hash_bucket_size 64;
    # Virtual hosts
    include /etc/nginx/sites/*.conf;
}

/etc/nginx/sites/*.conf
server {
        listen 80 ;
        listen [::]:80;
        server_name elkhobara.com www.elkhobara.com;
        root /var/hosts/elkhobara;
        index index.html index.htm index.php;
        location / {
                try_files $uri $uri/ =404;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
                root   html;
        }
        location ~ \.php$ {
               try_files $uri =404;
               fastcgi_pass unix:/run/php-fpm/php-fpm.pid;
               #fastcgi_pass 127.0.0.1:9000;
               fastcgi_index index.php;
               include /etc/nginx/fastcgi_params;
               fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
        }
}

Note, if I changed the socket to 127.0.0.1:9000 then it will work perfectly.
UPDATE:
SELinux status:
# sestatus
SELinux status:                 enabled
SELinuxfs mount:                /sys/fs/selinux
SELinux root directory:         /etc/selinux
Loaded policy name:             targeted
Current mode:                   permissive
Mode from config file:          permissive
Policy MLS status:              enabled
Policy deny_unknown status:     allowed
Max kernel policy version:      28

/var/log/audit/audit.log
--------------------------------------------------------------------------------

SELinux is preventing /usr/sbin/nginx from getattr access on the file /var/hosts/elkhobara/index.php.

*****  Plugin catchall_labels (83.8 confidence) suggests   *******************

If you want to allow nginx to have getattr access on the index.php file
Then you need to change the label on /var/hosts/elkhobara/index.php
Do
# semanage fcontext -a -t FILE_TYPE '/var/hosts/elkhobara/index.php'
where FILE_TYPE is one of the following: --Striped text--.
Then execute:
restorecon -v '/var/hosts/elkhobara/index.php'

*****  Plugin catchall (17.1 confidence) suggests   **************************

If you believe that nginx should be allowed getattr access on the index.php file by default.
Then you should report this as a bug.
You can generate a local policy module to allow this access.
Do
allow this access for now by executing:
# ausearch -c 'nginx' --raw | audit2allow -M my-nginx
# semodule -i my-nginx.pp

Additional Information:
Source Context                system_u:system_r:httpd_t:s0
Target Context                unconfined_u:object_r:var_t:s0
Target Objects                /var/hosts/elkhobara/index.php [ file ]
Source                        nginx
Source Path                   /usr/sbin/nginx
Port                          <Unknown>
Host                          <Unknown>
Source RPM Packages           nginx-1.10.2-1.el7.x86_64
Target RPM Packages
Policy RPM                    selinux-policy-3.13.1-102.el7_3.7.noarch
Selinux Enabled               True
Policy Type                   targeted
Enforcing Mode                Permissive
Host Name                     ip-172-31-39-125.us-west-2.compute.internal
Platform                      Linux ip-172-31-39-125.us-west-2.compute.internal
                              3.10.0-514.2.2.el7.x86_64 #1 SMP Wed Nov 16
                              13:15:13 EST 2016 x86_64 x86_64
Alert Count                   23
First Seen                    2017-01-01 16:46:48 EST
Last Seen                     2017-01-02 10:32:42 EST
Local ID                      0ff17cb3-2f01-4acf-8510-ab289c98d946

Raw Audit Messages
type=AVC msg=audit(1483371162.342:339): avc:  denied  { getattr } for  pid=2443 comm="nginx" path="/var/hosts/elkhobara/index.php" dev="xvda2" ino=25207236 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:var_t:s0 tclass=file

type=SYSCALL msg=audit(1483371162.342:339): arch=x86_64 syscall=stat success=yes exit=0 a0=7f9f09cef2d4 a1=7ffcd9347290 a2=7ffcd9347290 a3=7f9f09db3b30 items=0 ppid=2442 pid=2443 auid=4294967295 uid=996 gid=993 euid=996 suid=996 fsuid=996 egid=993 sgid=993 fsgid=993 tty=(none) ses=4294967295 comm=nginx exe=/usr/sbin/nginx subj=system_u:system_r:httpd_t:s0 key=(null)

Hash: nginx,httpd_t,var_t,file,getattr

--------------------------------------------------------------------------------

SELinux is preventing /usr/sbin/nginx from read access on the file index.php.

*****  Plugin catchall_labels (83.8 confidence) suggests   *******************

If you want to allow nginx to have read access on the index.php file
Then you need to change the label on index.php
Do
# semanage fcontext -a -t FILE_TYPE 'index.php'
where FILE_TYPE is one of the following: --Striped long text for future readability.
Then execute:
restorecon -v 'index.php'

*****  Plugin catchall (17.1 confidence) suggests   **************************

If you believe that nginx should be allowed read access on the index.php file by default.
Then you should report this as a bug.
You can generate a local policy module to allow this access.
Do
allow this access for now by executing:
# ausearch -c 'nginx' --raw | audit2allow -M my-nginx
# semodule -i my-nginx.pp

Additional Information:
Source Context                system_u:system_r:httpd_t:s0
Target Context                unconfined_u:object_r:var_t:s0
Target Objects                index.php [ file ]
Source                        nginx
Source Path                   /usr/sbin/nginx
Port                          <Unknown>
Host                          <Unknown>
Source RPM Packages           php-fpm-7.1.0-1.el7.remi.x86_64
Target RPM Packages
Policy RPM                    selinux-policy-3.13.1-102.el7_3.7.noarch
Selinux Enabled               True
Policy Type                   targeted
Enforcing Mode                Permissive
Host Name                     ip-172-31-39-125.us-west-2.compute.internal
Platform                      Linux ip-172-31-39-125.us-west-2.compute.internal
                              3.10.0-514.2.2.el7.x86_64 #1 SMP Wed Nov 16
                              13:15:13 EST 2016 x86_64 x86_64
Alert Count                   2
First Seen                    2017-01-01 17:10:48 EST
Last Seen                     2017-01-02 06:22:16 EST
Local ID                      ce7a65cb-6b95-4fc4-b31b-19efccf56ab1

Raw Audit Messages
type=AVC msg=audit(1483356136.314:121): avc:  denied  { read } for  pid=9421 comm="php-fpm" name="index.php" dev="xvda2" ino=25207236 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:var_t:s0 tclass=file

type=AVC msg=audit(1483356136.314:121): avc:  denied  { open } for  pid=9421 comm="php-fpm" path="/var/hosts/elkhobara/index.php" dev="xvda2" ino=25207236 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:var_t:s0 tclass=file

type=SYSCALL msg=audit(1483356136.314:121): arch=x86_64 syscall=open success=yes exit=EIO a0=7ffc64561010 a1=0 a2=1b6 a3=2 items=0 ppid=9419 pid=9421 auid=4294967295 uid=996 gid=993 euid=996 suid=996 fsuid=996 egid=993 sgid=993 fsgid=993 tty=(none) ses=4294967295 comm=php-fpm exe=/usr/sbin/php-fpm subj=system_u:system_r:httpd_t:s0 key=(null)

Hash: nginx,httpd_t,var_t,file,read

--------------------------------------------------------------------------------

A: Don't listen on the pid file...
In your pool config:
You must listen on a socket file or over tcp, like this:
listen = /run/run/php-fpm.sock

or
listen = 127.0.0.1:9000

See http://php.net/manual/fr/install.fpm.configuration.php#listen
And in Nginx:
fastcgi_pass unix:/run/run/php-fpm.sock;

or
fastcgi_pass 127.0.0.1:9000;

See http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_pass


text:
Q: Class with nested association to itself I have a class with a nested association to itself:
class Location < ActiveRecord::Base
  has_many :location_gateways
  has_many :gateways, through: :location_gateways, class_name: "Location", :dependent => :destroy
  accepts_nested_attributes_for :gateways, reject_if: :all_blank, allow_destroy: true
  belongs_to :location, optional: true
end

The connecting model:
class LocationGateway < ActiveRecord::Base
  belongs_to :location, :class_name => "Location"
  belongs_to :gateway, :class_name => "Location"
end

Now I would like to make a form that can create a Location and some gateways but I get an Gateway must exist error when I submit it (the call to Location.new)
I'm assuming this is because the model Gateway doesn't exist. How can I make rails understand that it should create another Locationand not a Gateway?

A: Found no way around this error. I had to make a new class Gateway that inherits from Location and add a type to Locations (STI).


text:
Q: Making Custom Posts behave like pages i am currently working on a theme, within this theme i would like to have posts which have parent and child posts. Within this theme I have currently created a post type called "associations". In a way i would like to create a microsite using posts and their hierarchal structure. These posts must also belong to custom taxonomy terms as well. The structure would be like:
Association landing page
-Super cool association name (parent post) (taxonomy term: dentists)

*

*Contact (child post)

*history (child post)

*tips    (child post)

I would like all the permalinks of the child pages to display wether the user is on the (parent post) or any of its (child posts)
I currently have this code but it only displays the children of the post on the parent single-associations.php
<?php
    // setup your arguments:
    $args = array(
        // We want to call all posts the custom post type 'help'
        'post_type' => 'associations',
        'posts_per_page' => -1,
        'post_status' => 'publish',
        'order' => 'ASC',
        // Next, we want to see if the current post is a parent of any help posts
        'post_parent' => $post->ID
    );
    // We then pass these to a wordpress query, and setup our loop
    $loop = new WP_Query( $args );
?>
<?php if ($loop->have_posts()) : while ($loop->have_posts()) : $loop->the_post(); ?>

    <a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?>
<?php endwhile; ?>
<?php else : ?>

<?php endif; ?>

I wanted to know if there is a way to have a custom template for each of the child posts as well.
I registered the custom post and made sure the
hierarchical was set to true.
'hierarchical'          => true,

in order to get the page attributes of the post I also made sure that the post type supported page attributes.
'supports'              => array( 'title', 'thumbnail','editor','page-attributes',),

I also registered  a taxonomy and inputed multiple terms.
This so far has allowed me to be able to create a parent-child relationship much like the pages in wordpress. But i need some guidance on understanding wether or not this is the most effective way to achieve this sort of setup. if anyone has any ideas on how to improve this method or a suggestion on how to achieve what i want i would highly appreciate it.


text:
Q: Sharing a link to Facebook directly with an intent? I currently share links on facebook with the below code. Is it possible to specify the text to put in the "Say something about this..." field in the ShareLinkActivity (ie. is it possible to specify the text that goes in that field in the intent)? I'm looking for a solution, if any exists, that does not require the Facebook API
public void shareFacebook(String url) {
    try {

        Intent sendShareIntent = new Intent(Intent.ACTION_SEND);
        sendShareIntent.setClassName("com.facebook.katana",
                "com.facebook.katana.ShareLinkActivity");
        sendShareIntent.setType("text/*");
        sendShareIntent.putExtra(android.content.Intent.EXTRA_TEXT, url);
        startActivityForResult(sendShareIntent, FACEBOOK_REQUEST_CODE);

    } catch (Exception e) {

    }
}

A: Try..
sendShareIntent.putExtra(Intent.EXTRA_SUBJECT, "something";

A: unfortunately there is not a way to share text, only a single URL.
a known bug that facebook knows and does not want to fix, possibly because they want you to use their SDK
what i've done is branch the intent, so that everything besides facebook gets the String of text + URL, while facebook just shares the URL. not ideal.
heres a link showing how i branched if interested Branching the Android Share Intent extras depending on which method they choose to share
someone also came up with a very ugly workaround, where they passed string vars to a webpage URL they control, and dynamically rewrite the meta description (or content) of the page being shared to have the text you want to share. then the text is at least there in the share, although not in the facebook message area, but the URL preview. (can't find that example atm)


text:
Q: finding mutual friends in a cypher statement starting with three or more persons I am trying to build a cypher statement for neo4j where I know 2-n starting nodes by name and need to find a node (if any) that can be reached by all of the starting nodes.
At first I tought it was similar to the "Mutual Friend" situation that could be handled like
(start1)-[*..2]->(main)<-[*..2]-(start2)
but in my case I often have more then 2 starting points up around 6 that I know by name.
So basically I am puzzled by how i can include the third, fourth and so on node into the cypher to be able to find a commmon root amongst them.

In the above Example from the neo4j Website I would need a path starting with 'Dilshad', 'Becky' and 'Cesar' to check if they have a common friend (Anders) excluding 'Filipa' and 'Emil' as they are not friends of all three.
So far I would create a statement programmatically that looks like
MATCH (start1 {name:'Person1'}), (start2 {name:'Person2'}),
(start3 {name: 'Person3'}), (main)
WHERE (start1)-[*..2]->(main) AND
(start2)-[*..2]->(main) AND
(start3)-[*..2]->(main) RETURN distinct main

But I was wondering if there is a more elegant / efficient way in cypher possibly where I could use the list of names as parameter

A: The query shown in your question is building a cartesian product because you are matching multiple disconnected patterns.
Instead of MATCH all nodes separately and use WHERE to restrict the relations between these nodes you can do something like:
MATCH (start1 {name:'Person1'})-[*..2]->(main),
(start2 {name:'Person2'})-[*..2]->(main),
(start3 {name: 'Person3'})-[*..2]->(main)
RETURN main

The above query will be more efficient because it will match only the required pattern. Note that when you are doing MATCH (start1 {name:'Person1'}), (start2 {name:'Person2'}), (start3 {name: 'Person3'}), (main), the part (main) is matching all nodes of your graph because no restrictions to this are specified. You can use PROFILE with your query to see it more clearly.


text:
Q: Cannot make folder read only Here is what happens when I make the folder read only:

It asks for admin access to it and I click ok.
But when I go back and check it again it has reverted back to read only.
the reason I am doing this is I need to be able to make a new file in the folder via cmd.

Thanks, I am using windows 7

A: Folders don't show their read only status in Explorer. This is by design as users will screw things up by removing read only on Windows special folders.
The file system ignores it except it resists deletion. However programs can change the attribute and then delete it, and this is what Windows Explorer does.
As the read only attribute is unused for folders (except as noted above) Windows Explorer uses it (or the system attribute) to mark a folder as special. When opening a folder for viewing it uses the presence of the read only attribute to tell it to use a different viewer from the standard folder viewer. Like the fonts folder - instead of showing files it shows installed fonts. This use is specific to Windows Explorer and there is no support to other programs for it.
As Windows Explorer doesn't want you changing the flag it uses it doesn't show if a folder is marked read only or not. It shows indeterminate. If you click the box it will change between ticked, unticked, and indeterminate. Clicking the box and changing it, it will apply to files in the folder not the folder.
Attrib shows the attributes of a folder
attrib "%userprofile%\documents"

And you can see even though read only is set you can save files to your Documents folder.
Attrib can only change an attribute if the file doesn't have hidden or system attribute also set. To change it on these you must change all three to off.
attrib -r -s -h "%userprofile%\documents"

For Help on attrib type
attrib /?


text:
Q: How to read a data frame in jsonlite I am trying to read a data frame in jsonlite. I have a json file (which is made from an html code from a newspaper article , and structured in some variables: title, body, comments), and I managed to rename it.
install.packages("jsonlite")
library("jsonlite")
article1 <- fromJSON("/Users/eva/Desktop/bdk.blufaerdighed.html.json")

I now want to "see" the content of my file (I want to see the text belonging to the variables; title, body, comments etc.), but I don't know which function to use.
my json file looks like this:

{ "author":"Ulla Gunge", "body":"De har »opført sig blufærdighedskrænkende«. I en uge har to otteårige drenge derfor været bortvist fra deres skole i Horsens.", "comments":[], "subtitle":"To otteårige drenge er blevet bortvist fra deres skole for at have vist deres tissemænd til en pige. Men den slags er helt normalt i den alder, fortæller forsker i voksnes syn på børns seksualitet, doktorlege og pædofilifrygt.", "title":"Blufærdighed i børnehøjde" }

A: To see those fields you just print them
article1$title
article1$body
article1$comments

A: Data frame structure is a list of vectors of equal length. The comment field in your json has length 0. You can see this for example by typing:
sapply(article1, length)
#   author     body comments subtitle    title
#        1        1        0        1        1

If you can change the json from "comments":[] to "comments":["NA"] it is possible to get the data frame directly with fromJSON function by using simplifyDataFrame attribute.
Or you could change the list with article1$comments <- NA and get the data frame with:
as.data.frame(article1)


text:
Q: Detecting if a variable is empty I have a variable of $message that when I echo displays nothing. Unfortunately the following code does not work.
if (!$message) {
    echo 'Nothing here!';
}

When I var_dump($message); I get the following:

string(48) ""

So it looks like somethings in there. Any ides?
Thanks,
John

A: You could also use :
if($var == "")
{
    echo("nothing here");
}

A: Use empty()
isset() will return true for empty value
What's the difference between 'isset()' and '!empty()' in PHP?

A: use one of these:
http://php.net/manual/en/function.empty.php
if(isset($message)){
   echo "variable has value set";
}

if(!empty($message)){
   echo "Variable is empty";
}

A: Try this:
if(!$message || $message == "") {
   echo 'Nothing here!';
}

You can also use isset($message) or empty($message).

A: When you are typing the name of your question, notice, that below many same questions could appear, like in this post, and you will not duplicate it then. For example, first post where you can find many answers:
check if variable empty
And you save your time for typing question ;-)

A: Ok - I worked it out. I was building the $message variable with a load of MySQL queries and if there we're results displaying the in a table. I had a few  tags outside of a if (mysqli_num_rows($result) <> 0) { } clause so they we're being saved in the variable.
Thanks all for your help anyway.

A: You can use:
<?php
    is_null($var) //returns true if it's null

    empty($var) //returns true if it's empty

    isset($var) //returns true if it's not null.
?>

https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/
I hope I've helped!


text:
Q: Angular 2 RC6 - Setting default params in URL and redirect to route with params I have done a lot a research but I don't seem to find the exact answer...
My problem is simple; I have a route, let's call it "parent/child", and I want to set default params in it if the params are not provided (parent/child?param1=xxx&param2=xxx and so on).
I constantly need params in my URL because it allows me to update some graphs on my page that rely on these params. I also want them in the URL and not on a localeStorage/Session or service because my users are susceptible to copy/paste to share the page.
I have tried several things, like:
{
        path: 'parent',
        component: Parent,
        children: [
            {
                path: 'child',
                redirectTo: 'child:param1:param2'
            },
            {
                path: 'child:param1:param2',
                component: Child
            },

But it does not work. I have thought about a shared service between my components to set these params when they are not provided, but after that I guess I should do something like route.navigate([myLocation], myParams) to change the URL with the params.
So it means that each time I need to retrieve my current location ?
If someone could help me, I am a bit confused. Thanks !
EDIT : my app.routes :
{
        path: 'parent',
        component: Parent,
        children: [
            {
                path: 'child',
                component: Child
            },
        ]
},
{
        path: '**',
        redirectTo: '/parent/child'
}

Sorry if it is a silly question, it must be a syntax error...

A: Just add the URL like:
{
    path: 'child',
    redirectTo: 'child/a/b'
},

where "a" is the value for param1 and "b" for param2

A: As per the official router guide, routes can have required and optional query parameters.
Required parameters (ie /parent/child/required)
  {
    path: '',
    redirectTo: '/parent/child/required',
    pathMatch: 'full'
  },
  {
    path: 'parent',
    component: ParentComponent,
    children:[
      {
        path: 'child/:info',
        component: ChildComponent
      }
    ]
  }

http://plnkr.co/edit/35oXBWL1rg7biLgww3TF (click 'launch the preview in a separate window' to see the url)
Optional parameters (ie /parent/child?info=optional)
this.router.navigate(['/parent/child',{info: "optional"}]);

http://plnkr.co/edit/HPwcfN9BUYqcSrWEawd6 (click 'launch the preview in a separate window' to see the url)
edit: versions in systemjs hardcoded to fix plunkrs

A: Routes only define required parameters. Do not include parameters that may or may not be present
{
    path: 'child',
    component: Child
}

To navigate to Child and provide several parameters you would do
this.router.navigate(['/parent/child', {optionA:value1,optionB:value2}]);

This will navigate to /parent/child;optionA=value1;optionB=value2.  Inside the Child component, you subscribe to ActivatedRoute.params to be notified every time the parameters change.
Child
import {ActivatedRoute, Router} from '@angular/router';
...
constructor(private activeRoute:ActivatedRoute, private router:Router){}

//chart options
optionA;
optionB;

//redraws the chart
redrawChart(){/*todo*/}

ngOnInit(){
    this.activeRoute.params.subscribe(
        //executed each time new params arrive
        params => {
            this.optionA = params['optionA'] || null;
            this.optionB = params['optionB'] || null;
            this.redrawChart();
        }
    );
}

To change the chart option, you could do
changeChart(a, b){
    this.router.navigate(['/parent/child',{optionA:a,optionB:b}]);
}

For more info on how to handle changing route parameters, see the manual  (search for params.subscribe)
With all that said, you are right. A ChartService would be much cleaner.  Your component could subscribe to a chartOptionsChanged Observable exposed by that service and just update the chart.


text:
Q: Java Connection Pooling I searched for connection pooling and read about it. If I understand it correctly, a connection pool is like a collection of open connections. If a connection is established or created it should be added to the connection pool, and if that connection is closed it should be removed in connection pool; while it is open I can use it again and again.
While reading these tutorials and explanations about connection pooling I have some questions:

*

*Can a pool of connections only be used on a certain computer? Like ComputerA
cannot share its connection pool with ComputerB?

*Where should connection.close() be placed?
Is it correct to use a connection ONLY when selecting/loading record? After I got the returned records/data I close the connection at finally statement. Same as adding, editing and deleting records. And while it is processing I place a progress bar so the user will have to wait for it to be completed and to do some process again, which means I will only open connection one at a time.
Thanks for the explanation. :)

A: Note: I assume we're talking about the java.sql.Connection interface.

Can a pool of connections only be used on a certain computer? Like ComputerA cannot share its connection pool with ComputerB?

A connection exists between a running application and a database. Naturally, two different machines can't share the same running application, so they can't share connections with a database.

Where should connection.close() be placed?

You should always make sure to call close() on a Connection instance after using it (typically in a finally block). If pooling is being used, this will actually return the connection to the pool behind the scenes. Reference: Closing JDBC Connections in Pool

Is it correct to use a connection ONLY when selecting/loading record? After I got the returned records/data I close the connection at finally statement.

Yes, that's correct. You don't want to manually hang on to a Connection reference - use it to execute SQL/DML and then check it back into the pool by calling close() in the finally block, just like you're doing.


text:
Q: Delete registry keys with subkeys using winreg on python i am currently making a function that uses winreg to help me delete all the subkeys of a registry key. my current code
import winreg as wr

def delsub(k0, k1, k2=""):
    if k2 == "": current = k1
    else: current =  f'{k1}\\{k2}'

    openkey = wr.OpenKey(k0, current, 0, wr.KEY_ALL_ACCESS)
    infokey = wr.QueryInfoKey(openkey)
    for x in range(infokey[0]):
        subkey = wr.EnumKey(openkey, 0)

        try: wr.DeleteKey(openkey, subkey)
        except: delsub(k0, current, subkey)

    wr.DeleteKey(openkey,"")
    openkey.Close()

then i basically went to a random directory thing on regedit and created a key with 2 subkeys inside on the path Computer\HKEY_USERS\.DEFAULT\Control Panel\test. then i ran the function
delsub(wr.HKEY_USERS,r'.DEFAULT\Control Panel\test')

it gave me an error
Traceback (most recent call last):
  File "main.py", line 18, in <module>
    delsub(wr.HKEY_USERS,r'.DEFAULT\Control Panel\test')
  File "main.py", line 7, in delsub
    openkey = wr.OpenKey(k0, current, 0, wr.KEY_ALL_ACCESS)
PermissionError: [WinError 5] Access is denied

i tried giving it administrator access and same thing, so i really dont understand why
i get an error when opening the key though. the error doesn't explain much and i need some help
also im knew to winreg so if i did something extremely stupid here please let me know

A: I have no idea why but it works now when i run it on administrator mode. Maybe yesterday I forgotten to give it admin access.