text:
Q: How to use 'Recall' as metric in keras classifier? How can use use the 'Recall' and other metrics in keras classifier. The following code only works for accuracy but if I change the metric to recall it fails.
Versions
"""
[('numpy', '1.19.1'),
 ('pandas', '1.1.1'),
 ('sklearn', '0.23.2'),
 ('tensorflow', '2.3.0'),
 ('keras', '2.4.3')]

"""

MWE
import numpy as np
import pandas as pd
import sklearn
import tensorflow as tf
import keras
from keras.models import Sequential
from keras.layers.core import Dense

SEED = 100

np.random.seed(100)
X = np.random.random((20, 3))
y = np.random.randint(0,2,size=20)

print(x.shape, y.shape) # (20, 3) (20,)

n_inputs = X.shape[1]

model = Sequential([
    Dense(n_inputs, input_shape=(n_inputs, ), activation='relu'),
    Dense(32, activation='relu'),
    Dense(2, activation='softmax')
])

METRIC = 'Recall' # Recall fails
# METRIC = 'accuracy' # accuracy works

model.compile('adam',loss='binary_crossentropy',metrics=[METRIC])
model.fit(X, y,validation_split=0.2,epochs=1)

Error
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-b372311b0ed4> in <module>
     38             epochs=10,
     39             shuffle=True,
---> 40             verbose=5)

~/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py in _method_wrapper(self, *args, **kwargs)
    106   def _method_wrapper(self, *args, **kwargs):
    107     if not self._in_multi_worker_mode():  # pylint: disable=protected-access
--> 108       return method(self, *args, **kwargs)
    109
    110     # Running inside `run_distribute_coordinator` already.

~/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
   1096                 batch_size=batch_size):
   1097               callbacks.on_train_batch_begin(step)
-> 1098               tmp_logs = train_function(iterator)
   1099               if data_handler.should_sync:
   1100                 context.async_wait()

~/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)
    778       else:
    779         compiler = "nonXla"
--> 780         result = self._call(*args, **kwds)
    781
    782       new_tracing_count = self._get_tracing_count()

~/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)
    821       # This is the first call of __call__, so we have to initialize.
    822       initializers = []
--> 823       self._initialize(args, kwds, add_initializers_to=initializers)
    824     finally:
    825       # At this point we know that the initialization is complete (or less

~/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)
    695     self._concrete_stateful_fn = (
    696         self._stateful_fn._get_concrete_function_internal_garbage_collected(  # pylint: disable=protected-access
--> 697             *args, **kwds))
    698
    699     def invalid_creator_scope(*unused_args, **unused_kwds):

~/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)
   2853       args, kwargs = None, None
   2854     with self._lock:
-> 2855       graph_function, _, _ = self._maybe_define_function(args, kwargs)
   2856     return graph_function
   2857

~/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)
   3211
   3212       self._function_cache.missed.add(call_context_key)
-> 3213       graph_function = self._create_graph_function(args, kwargs)
   3214       self._function_cache.primary[cache_key] = graph_function
   3215       return graph_function, args, kwargs

~/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)
   3073             arg_names=arg_names,
   3074             override_flat_arg_shapes=override_flat_arg_shapes,
-> 3075             capture_by_value=self._capture_by_value),
   3076         self._function_attributes,
   3077         function_spec=self.function_spec,

~/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)
    984         _, original_func = tf_decorator.unwrap(python_func)
    985
--> 986       func_outputs = python_func(*func_args, **func_kwargs)
    987
    988       # invariant: `func_outputs` contains only Tensors, CompositeTensors,

~/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)
    598         # __wrapped__ allows AutoGraph to swap in a converted function. We give
    599         # the function a weak reference to itself to avoid a reference cycle.
--> 600         return weak_wrapped_fn().__wrapped__(*args, **kwds)
    601     weak_wrapped_fn = weakref.ref(wrapped_fn)
    602

~/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    971           except Exception as e:  # pylint:disable=broad-except
    972             if hasattr(e, "ag_error_metadata"):
--> 973               raise e.ag_error_metadata.to_exception(e)
    974             else:
    975               raise

ValueError: in user code:

    /Users/poudel/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py:806 train_function  *
        return step_function(self, iterator)
    /Users/poudel/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py:796 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    /Users/poudel/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:1211 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /Users/poudel/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:2585 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /Users/poudel/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:2945 _call_for_each_replica
        return fn(*args, **kwargs)
    /Users/poudel/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py:789 run_step  **
        outputs = model.train_step(data)
    /Users/poudel/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py:759 train_step
        self.compiled_metrics.update_state(y, y_pred, sample_weight)
    /Users/poudel/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/keras/engine/compile_utils.py:409 update_state
        metric_obj.update_state(y_t, y_p, sample_weight=mask)
    /Users/poudel/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/keras/utils/metrics_utils.py:90 decorated
        update_op = update_state_fn(*args, **kwargs)
    /Users/poudel/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/keras/metrics.py:176 update_state_fn
        return ag_update_state(*args, **kwargs)
    /Users/poudel/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/keras/metrics.py:1410 update_state  **
        sample_weight=sample_weight)
    /Users/poudel/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/keras/utils/metrics_utils.py:353 update_confusion_matrix_variables
        y_pred.shape.assert_is_compatible_with(y_true.shape)
    /Users/poudel/opt/miniconda3/envs/tf2/lib/python3.7/site-packages/tensorflow/python/framework/tensor_shape.py:1134 assert_is_compatible_with
        raise ValueError("Shapes %s and %s are incompatible" % (self, other))

    ValueError: Shapes (None, 2) and (None, 1) are incompatible

A: Change the final layer output 2 to 1.
import numpy as np
import pandas as pd
import sklearn
import tensorflow as tf
import keras
from keras.models import Sequential
from keras.layers.core import Dense

SEED = 100

np.random.seed(100)
X = np.random.random((20, 3))
y = np.random.randint(0,2,size=20)

print(X.shape, y.shape) # (20, 3) (20,)

n_inputs = X.shape[1]

model = Sequential([
    Dense(n_inputs, input_shape=(n_inputs, ), activation='relu'),
    Dense(32, activation='relu'),
    Dense(1, activation='relu')
])

METRIC = 'Recall' # Recall fails
# METRIC = 'accuracy' # accuracy works

model.compile('adam',loss='binary_crossentropy',metrics=[METRIC])
model.fit(X, y,validation_split=0.2,epochs=1)


text:
Q: Seeing double, triple sound in javascript audio, how to solve it? **This function is in javascript:**

function quesfl(qsvalue) {
sngno = qsvalue + ".wav";
var audiophile = new Audio();
audiophile.src = sngno;
   audiophile.play();
}

**html part:**

<input type="radio" name="qno" value="02" onClick="quesfl(this.value);">2
<input type="radio" name="qno" value="03" onClick="quesfl(this.value);">3
<input type="radio" name="qno" value="04" onClick="quesfl(this.value);">4

In the above java script code for audio, I have a variable 'sngno' for different src. However, when I change to different src, all the songs are playing, but I want only the one. While my web page is open, if I reload the page, each time the first selected song is played, but when i select other button for another song, both plays. Help please.

A: I had success using this jquery sound library: https://code.google.com/p/jqueryjs/source/browse/trunk/plugins/sound/jquery.sound.js?r=5750

A: Got the solution.
Try the following code.
<html>
<head>
    <script>
        audiophile = new Audio();
        function quesfl(qsvalue) {
        sngno = qsvalue + ".wav";
        audiophile.src = sngno;
           audiophile.play();
        }
    </script>
</head>
<body>
    <input type="radio" name="qno" value="02" onClick="quesfl(this.value);">2
    <input type="radio" name="qno" value="03" onClick="quesfl(this.value);">3
    <input type="radio" name="qno" value="04" onClick="quesfl(this.value);">4
</body>
</html>

It is happening because each time you select a different radio button a new Audio object is created and gets played and hence all of the selected audio files get played simultaneously. This got solved from the very basic concept of Object Oriented Programming.

A: Your Audio variable is inside the handler function, and every time it's called you create a new one & start it playing. Thus you end up with multiple, playing simultaneously.
Move the variable outside and only create it once.
var globalAudio = new Audio();

function playSong (songName) {
    var songUrl = songName + ".wav";
    globalAudio.src = songUrl;
    globalAudio.play();
}

I've also improved the naming of your function & variables.. Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prevent UITableViewCell highlighting when image in content view is touched I have added a UIImageView to the right side of the content view of my UITableViewCell.
I am trying to prevent the cell from being highlighted while the user is touching the UIImageView (because an attached gesture recognizer performs some other functionality).
I have thought about implementing tableView:shouldHighlightRowAtIndexPath: and returning NO, but I am unsure how to easily determine if the image is being touched when this method is called. Is there an easy way to do this?

A: Try this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ...

    // Add tap gesture recogniser to cell's image view
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped)];
    tap.cancelsTouchesInView = YES;

    cell.theImageView.userInteractionEnabled = YES;
    [cell.theImageView addGestureRecognizer:tap];

    return cell;
}

The important parts are to make sure the image view has userInteractionEnabled = YES and the gesture recogniser has cancelsTouchesInView = YES.
This will cause the tapped method to fire if the image view is tapped, but the cell will not be highlighted.

A: why don't you add a UIButton with type custom.Will have the tap button action.Will not affect the cell highlight
Prevent highlight of tablecell
cell.selectionStyle = UITableViewCellSelectionStyleNone;

or
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];


text:
Q: Eager loading of grandchild object with Entity Framework 6 I've got three classes that look like the following. I'll call them Parent, Child and Grandchild.
public class Parent
{
  public int Id {get;set;}
  public string Name {get;set;}
  public virtual List<Child> Children {get;set;}
  public virtual List<Grandchild> Grandchildren {get;set;}
}

public class Child
{
  public int Id {get;set;}
  public string Name {get;set;}
  public virtual Parent Parent {get;set;}
  public virtual List<Grandchild> Grandchildren {get;set;}
}

public class Grandchild
{
  public int Id {get;set;}
  public string Name {get;set;}
  public virtual Parent Parent {get;set;}
  public virtual Child Child {get;set;}
}

Now, I use a repository pattern with EF6. For the grab method for a parent, I have something like the following:
public List<Parent> GrabParent(Expression<Func<Parent, bool>> predicate)
{
  return _context.Parents
    .Include(a => a.Children)
    .Include(a => a.Grandchildren)
    .Where(predicate)
    .ToList();
}

I use a similar method to grab the grandchild records:
public List<Grandchild> GrabGrandchildren(Expression<Func<Grandchild, bool>> predicate)
{
  return _context.Grandchildren
    .Include(a => a.Parent)
    .Include(a => a.Child)
    .Where(predicate)
    .ToList();
}

Now, if I were to call the GrabParent method, I would receive a list of Parents and a list of each of the Children. However, I wouldn't be able to access any of the Grandchildren records, despite their being relationally linked to each of the Children records that I am able to access.
Similarly, if I call the GrabGrandchildren method, I'll be able to retrieve a list of the Grandchildren and information about the Child, but I wouldn't be able to get any information about the Parent.
Why is this and how can I go about retrieving that additional related information?

A: See EF code-first: How to load related data (parent-child-grandchild)? for an explanation.
Essentially, I would modify the GrabGrandchildren method to the following:
public List<Grandchild> GrabGrandchildren(Expression<Func<Grandchild, bool>> predicate)
{
  return _context.Grandchildren
    .Include(a => a.Child)
    .Include(a => a.Child.Select(b => b.Parent)
    .ToList();
}


text:
Q: event.target points to a child element When a user clicks on a <li>-element or on a child element of it, I want to add a class to this <li>-element.
This works fine, but for performance enhancement I decided to bind this event to the <ul>-element, so unbinding and binding this event is much faster in a list consisting of 1000 <li>-elements. The only change I thought I had to make was to replace this with event.target BUT event.target can also refer to a child element of a list item or even to a grandchild.
Is there an easy way to check this target element is part of a list item or do I need to walk the path from event.target till I reach a <li> element?
This is what I had before I decided to bind an event to the <ul> tag, which works but is not fast enough:
$('#list li').mousedown(function(){
    $(this).addClass('green');
});

And this is what I have now which doesn't work properly, mousedown on a child element doesn't give the <li> another classname:
$('#list').mousedown(function(event){
    if(event.target.nodeName == 'LI'){
        $(event.target).addClass('green');
    }
});

I wonder if my second way to achieve this is faster if there is not a simple solution to check if that target element is part of a list item...

A: You need to check if there is a LI tag in the parents of the target element.
All of the common frameworks have a way of determining this, it is up() in prototype, ancestor() in YUI3, and looking at the JQuery docs, it seems like it has a parent(), and parents() function that you can use for this.
See: http://docs.jquery.com/Traversing
Haven't used JQuery, but it I assume checking for $(event.target).parent('li') is the answer.

A: Well, you could do all of this with the jQuery on tool:
$('#list li').on('mousedown', function() {
  $(this).addClass('green');
});

You can read about what on does here: http://api.jquery.com/on/


text:
Q: CallNtPowerInformation and GetPwrCapabilities under Linux I have code that returns information about the running CPUs on an intel-based system under Windows. It does this with the CallNtPowerInformation and GetPwrCapabilities functions. Typical information returned is the maximum Mhz, current Mhz, maximum idle state, current idle state.
Presumably this is being done with a single instruction, like cpuid.
I want to have similar code that runs under Linux. Any ideas how to do it?
Here is the Windows code that I have:
    /** cpustat.h -- Header for cpustat.cpp.
     * Copyright (c) 2004 Brad Fish (brad.fish@gmail.com).
     */

    #if !defined(MAIN_H)
    #define MAIN_H

    #include <windows.h>

    // missing Windows processor power information struct
    typedef struct _PROCESSOR_POWER_INFORMATION {
      ULONG  Number;
      ULONG  MaxMhz;
      ULONG  CurrentMhz;
      ULONG  MhzLimit;
      ULONG  MaxIdleState;
      ULONG  CurrentIdleState;
    } PROCESSOR_POWER_INFORMATION , *PPROCESSOR_POWER_INFORMATION;

    int main (int argc, char *argv[]);

    #endif  // MAIN_H

#include "cpustat.h"
#include <cstdio>
#include <vector>
#include <iostream>

extern "C" {
#include <powrprof.h>
}
int main (int argc, char *argv[])
{
    typedef std::vector<PROCESSOR_POWER_INFORMATION> PPIVector;

    SYSTEM_INFO sys_info;
    PPIVector ppis;
    SYSTEM_POWER_CAPABILITIES spc;

    // find out how many processors we have in the system
    GetSystemInfo(&sys_info);
    ppis.resize(sys_info.dwNumberOfProcessors);

    // get CPU stats
    if (CallNtPowerInformation(ProcessorInformation, NULL, 0, &ppis[0],
        sizeof(PROCESSOR_POWER_INFORMATION) * ppis.size()) != ERROR_SUCCESS)
    {
        perror("main: ");
        return -1;
    }

    // print out CPU stats
    for (PPIVector::iterator it = ppis.begin(); it != ppis.end(); ++it)
    {
        std::cout << "stats for CPU " << it->Number << ':' << std::endl;
        std::cout << "  maximum MHz: " << it->MaxMhz << std::endl;
        std::cout << "  current MHz: " << it->CurrentMhz << std::endl;
        std::cout << "  MHz limit: " << it->MhzLimit << std::endl;
        std::cout << "  maximum idle state: " << it->MaxIdleState << std::endl;
        std::cout << "  current idle state: " << it->CurrentIdleState <<
            std::endl;
    }

    // get system power settings
    if (!GetPwrCapabilities(&spc))
    {
        perror("main: ");
        return -2;
    }

    // print power settings
    std::cout << "system power capabilities:" << std::endl;
    std::cout << "  processor throttle: " <<
        (spc.ProcessorThrottle ? "enabled" : "disabled") << std::endl;
    std::cout << "  processor minimum throttle: " <<
        static_cast<int>(spc.ProcessorMinThrottle) << '%' << std::endl;
    std::cout << "  processor maximum throttle: " <<
        static_cast<int>(spc.ProcessorMaxThrottle) << '%' << std::endl;
}

A: You can find some info by looking around in the proc file system under /proc, for example /proc/cpuinfo or /proc/acpi/processor/.

A: We finally got some code that does this. It uses the cpuid instruction:
#include <stdint.h>
#include <stdio.h>
#include <limits.h>

#define cpuid(id) __asm__( "cpuid" : "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx) : "a"(id), "b"(0), "c"(0), "d"(0))
#define b(val, base, end) ((val << (__WORDSIZE-end-1)) >> (__WORDSIZE-end+base-1))

int main(int argc, char **argv)
{
        unsigned long eax, ebx, ecx, edx;

        cpuid(0);
        printf("identification: \"%.4s%.4s%.4s\"\n", (char *)&ebx, (char *)&edx, (char *)&ecx);

        printf("cpu information:\n");

        cpuid(1);
        printf(" family %ld model %ld stepping %ld efamily %ld emodel %ld\n",
                        b(eax, 8, 11), b(eax, 4, 7), b(eax, 0, 3), b(eax, 20, 27), b(eax, 16, 19));
        printf(" brand %ld cflush sz %ld*8 nproc %ld apicid %ld\n",
                        b(ebx, 0, 7), b(ebx, 8, 15), b(ebx, 16, 23), b(ebx, 24, 31));

        cpuid(0x80000006);
        printf("L1 cache size (per core): %ld KB\n", b(ecx, 16, 31));

        return(0);
}


text:
Q: Creating a list of CheckBoxes  Okay so basically I am new to C# and I am currently working for a company that develops ecommerce software and I am having an issue that I can't seem to crack.
I  have two columns and I want to add a third column that displays a list of check boxes but I only want to display these checkboxes when the other two(or one) of the fields displays some form of data in it, I.E:
            Name Type Check
            lol   lol

I also want these check boxes to be automatically ticked.
Another issue is that I also want to make it so when checked the products are displayed in our search, but if they are unticked I wish them to be hidden but not deleted.
I am currently using GridView as I don't want to have to rewrite the rest of what is already there as it communicates with a SQL database which I know nothing about yet.
We are not using ASP, we are using XAML & C# (both of which I have very little knowledge in.) The below image is a bad drawing of what it needs to look like.

A: Your question is very broad, and somewhat difficult to answer.  In short, what you want to look at is the Visibility property on the controls.
By setting Visibility to Collapsed, the UI will not display the element.  You can set Visibility based on the value of another XAML element or data delement if you want, but you'll need to implement a class that implements IValueConverter to make the conversion.
One of the most common of the value converters is a "boolean to visibility" converter.  If you search on the Internets, you'll be able to find examples of these.  You can copy that approach and create an "EmptyToVisibilityConverter" or "NullToVisibilityConverter" or whatever else you need.  Once you have that converter, you just specify it in the binding for the visibility.  For example:
<Page.Resources>
    <conv:NullToVisibilityConverter x:Key="NullToVis"/>
</Page.Resources>

<CheckBox ... Checked={Binding ThisBoxIsChecked}
              Visibility={Binding SomeOtherValue,
                          Converter={StaticResource NullToVis}}"/>

Keep in mind that your databinding between the content of the control, and the visibility properties need not be the same.  You can bind your content to one value, and visibility to another.
If you're not using databinding, you're going to have to set these in the codebehind.  But why wouldn't you be using databinding?
EDIT:  Here's a working example.
If this isn't what you're looking for, then I'm being obtuse and not understanding the question
I recommend you start a blank project, throw this into it, and play around with it a bit to get a feel for how to set things up.  XAML has a relatively steep learning curve, and there are usually a couple ways to accomplish what you need, but you really need a foundational understanding of databinding and INotifyPropertyChanged (which I didn't get into in this example).
Here's the C# code:
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace CheckboxList
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            //Create a viewmodel and add some data to it.
            var viewModel = new MyViewModel();
            viewModel.Items.Add(new Data() {Name = "lol", Type = "lol", Selected = true});
            viewModel.Items.Add(new Data() { Name = "lol", Type = "not_lol", Selected = true });
            viewModel.Items.Add(new Data() { Name = "not_lol", Type = "not_lol", Selected = true });

            //Set the window's datacontext to the ViewModel.  This will make binding work.
            this.DataContext = viewModel;

        }
    }

    //This is the ViewModel used to bind your data
    public class MyViewModel
    {
        //This could just be a List<Data> but ObservableCollection<T> will automatically
        //update your UI when items are added or removed from the collection.
        public ObservableCollection<Data> Items { get; set; }

        public MyViewModel()
        {
            Items = new ObservableCollection<Data>();
        }
    }

    //Just a sample class to hold the data for the grid.
    //This is the class that is contained in the ObservableColleciton in the ViewModel
    public class Data
    {
        public string Name { get; set; }
        public string Type { get; set; }
        public bool Selected { get; set; }
    }

    //This is an example converter.  It looks to see if the element is set to "lol"
    //If so, it returns Visibility.Collapsed.  Otherwise, it returns Visibility.Visible.
    public class LolToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null && value is string)
            {
                var input = (string) value;
                if (string.Equals(input, "lol", StringComparison.CurrentCultureIgnoreCase))
                {
                    return Visibility.Collapsed;
                }
                else
                {
                    return Visibility.Visible;
                }
            }

            return Visibility.Visible;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

And the XAML:
<Window x:Class="CheckboxList.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:CheckboxList="clr-namespace:CheckboxList"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <!-- Create an instance of LolToVisibilityConverter and call it "LolToVis" -->
        <CheckboxList:LolToVisibilityConverter x:Key="LolToVis"/>
    </Window.Resources>
    <Grid>

        <ListView ItemsSource="{Binding Items}">  <!--Bind the contents of the Items collection in our viewmodel -->
            <ListView.View>
                <GridView>
                    <GridViewColumn Width="140" Header="Name" DisplayMemberBinding="{Binding Name}"/> <!-- bind this element to this column-->
                    <GridViewColumn Width="140" Header="Type" DisplayMemberBinding="{Binding Type}"/> <!-- bind this element to this column-->
                    <GridViewColumn Width="140" Header="Selected" >  <!-- because we don't want this to just display true/false, we need to set up a template-->
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <!-- we set the Visibility property to Name, and the converter to LolToVis-->
                                <!-- whenever this field will be displayed, it calls the converter to convert the string to a Visibility value-->
                                <!-- The visibility value is checked to determine whether or not the element should be displayed-->
                                <CheckBox IsChecked="{Binding Selected}" Visibility="{Binding Name, Converter={StaticResource LolToVis}}"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</Window>

A: This is what I have used in the past to create a checkbox for each datagridview row... I then use the datagridview_cellcontentclick event handler to change the value of the checkbox when clicked.  In the context of the code below, I have a custom class that consisted a program name, a window title, and an open file or url. I then created a global list "oplist" that was of the type custom custructor.  I then specified the column Headers when I added the items from the list to the datagridview.  Then adding or removing anything from the datagridview becomes extremely easy.  All you have to do is remove or add the item to the list and then refresh the datagridview.
    public void addOpenProgramsToDataGrid()
    {
        dataGridView1.ColumnCount = 3;

        DataGridViewCheckBoxColumn column = new DataGridViewCheckBoxColumn();
        {
            column.HeaderText = "Selected";
            column.Name = "Selected";
            column.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
            column.FlatStyle = FlatStyle.Standard;
            column.ThreeState = false;
            column.CellTemplate = new DataGridViewCheckBoxCell();
            column.CellTemplate.Style.BackColor = Color.White;
        }

        dataGridView1.Columns.Insert(0, column); // This is to be a checkbox column
        dataGridView1.Columns[0].HeaderText = "X";

        dataGridView1.Columns[1].HeaderText = "Process Name:";

        dataGridView1.Columns[2].HeaderText = "Window Title";
        dataGridView1.Columns[3].HeaderText = "Open File or URL";

        dataGridView1.RowCount = opList.Count;
        //opList.RemoveRange(0, opList.Count);
        for (int a = 0; a < opList.Count; a++)
        {
            openProgram tempProgram = new openProgram();
            tempProgram = opList[a];
            dataGridView1.Rows[a].Cells[0].Value = true;

            dataGridView1.Rows[a].Cells[1].Value = tempProgram.processName;
            dataGridView1.Rows[a].Cells[2].Value = tempProgram.windowTitle;
            dataGridView1.Rows[a].Cells[3].Value = tempProgram.openFileOrURL;
        }
        selectAllCheckBox.Checked = true;
    }


text:
Q: How to store the GCM push notification message into sqlite database? I am working on GCM. Everything is okay and I have implemented the GCM successfully and it is working. But I need to save the message into a database table. But when I implemented the below database manipulation code, the GCM stopped working as well as database. No error is shown on log also.
   @Override
        protected void onMessage(Context context, Intent intent) {
            String message = getString(R.string.gcm_message);
            message = (String) intent.getExtras().getCharSequence("hello");
            displayMessage(context, message);
                /* database manipulation */
                String dbName = new String("GCM");
        SQLiteDatabase db = openOrCreateDatabase(dbName, MODE_PRIVATE, null);
        String tableName = new String("newsTable");
                db.execSQL("INSERT INTO " + tableName + "(message) VALUES(" + message + ");");
                db.close();
                /* database manipulation ends */
            generateNotification(context, message);
        }

Again, when I removed the database code snippet, the GCM worked well.
I made sure that, the database and table is already exist. Is my database manipulation code wrong? if yes, what's the actual way t do so ?

A: Try this way..
Create new DatabaseHelper  class that will create and insert message into sqlite database
public class DatabaseHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "GCM";
private static final String TABLE_NAME = "newsTable";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    // TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub

    db.execSQL("CREATE TABLE " + TABLE_NAME
            + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, MESSAGE STRING)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}

public void insertMsg(String msg) {

    SQLiteDatabase db = getWritableDatabase();

    ContentValues cv = new ContentValues();

    cv.put("MESSAGE", msg);

    db.insert(TABLE_NAME, null, cv);

    db.close();

  }
 }

GCM SERVICE
    @Override
    protected void onMessage(Context context, Intent intent) {
        String message = getString(R.string.gcm_message);
        message = (String) intent.getExtras().getCharSequence("hello");
        displayMessage(context, message);

        DatabaseHelper db = new DatabaseHelper(context);
        db.insertMsg(message);
        generateNotification(context, message);
    }

Always make the code clean, so that it looks easy..
Happy coding :)


text:
Q: How to copy only non-provided dependencies when several are provided? In our project setup we have at runtime a spring boot app where we add other jars to it via the loader.path mechanism of the PropertiesLauncher. Those jars are all located in a lib folder beside the actual spring boot app. In development the spring boot app itself is provided to us and we only develop the additional jars.
So we have a lot of dependencies that are provided via the spring-boot app like spring-context etc. But for example in one jar we depend on spring-webflux, which is not provided in the spring-boot app itself. But some of the dependencies of spring-webflux are already provided. So we only want to copy those dependencies of spring-webflux that are not provided by the spring-boot app, to not have jars in our lib folder that are already packaged in the spring-boot app.
To put it more general: How do I copy dependencies of artifact A excluding all those that artifact B depends on?
I tried it using:
            <plugin>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-dependencies-to-lib</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
                            <includeScope>runtime</includeScope>
                            <excludeScope>provided</excludeScope>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

The spring-boot is declared as a provided dependency and the additional jars are declared as runtime dependencies.
A complete minimal example is this:
./pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.example</groupId>
    <artifactId>parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>
    <modules>
        <module>a</module>
        <module>b</module>
        <module>c</module>
    </modules>
</project>

./a/pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.example</groupId>
    <artifactId>parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>a</artifactId>
  <dependencies>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
    </dependency>
  </dependencies>
</project>

./b/pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.example</groupId>
        <artifactId>parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>b</artifactId>
    <dependencies>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>
</project>

./c/pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.example</groupId>
        <artifactId>parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>c</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.example</groupId>
            <artifactId>a</artifactId>
            <version>${project.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.example</groupId>
            <artifactId>b</artifactId>
            <version>${project.version}</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-dependencies-to-lib</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
                            <includeScope>runtime</includeScope>
                            <excludeScope>provided</excludeScope>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

In the above example my expectation is that ./c/target/lib only contains b-0.0.1-SNAPSHOT.jar and commons-lang-2.6.jar since commons-io is provided by module a. But the directory still contains commons-io.


text:
Q: What is the Optimal Virtual Memory Size For 8 GB RAM | WIN 10? I would like to ask experts that What is the optimal Virtual Memory Size For 8 GB RAM | WIN 10 and how you calculate?
I know the system says 1906 MB is recommended but is it enough or I should set it more?
Currently, my Virtual Memory size is 12 GB by the way but I feel it is useless.
Thanks in advance!

A: Automatic Method
Windows 10 automatically manages the pagefile for your computer's configuration and the amount of RAM present in it. Typically you'll simply allow the Windows OS to dynamically manage this since in most cases that'll suffice and it'll work just fine.

The minimum and maximum size of the Pagefile can be up to 1.5 times
  and 4 times of the physical memory that your computer has
  respectively. For example, if your computer has 1 GB of RAM, the
  minimum Pagefile size can be 1.5 GB, and the maximum size of the file
  can be 4 GB.
Source

Manual Method
To calculate the "general rule" recommended size of virtual memory in Windows 10 per the 8 GB your system has, here's the equation 1024 x 8 x 1.5 = 12288 MB. So it sounds as if the 12 GB configured in your system currently is correct so when or if Windows needs to utilize the virtual memory, the 12 GB should suffice.

As a general rule, the maximum size of the paging file must be x1.5
  the amount of RAM installed. Thus for a PC running with 4GB of RAM,
  the maximum size of the swap file will be 1024 x 4 x 1.5 Mb.
Source

Fine-Tuned Method (Critical Systems)
It's probably true there is no 'one size fits all' formula for Windows 10 systems that are super fine-tuned to find the most optimal configuration per those systems.
In these cases, depending on various factors of the system and what's important for the system processes, there are many other factors to consider obviously.
There are many options available to record and measure system performance metrics to help benchmark and super fine-tune this configuration if needed though.
While all this is really just a trivial matter, it'll add some complexity and time to get the most optimal configuration where this setting must be the most optimal.

In most cases though using 1.5 times virtual memory for the amount of total RAM on Windows 10 systems will suffice and keep it simple or be a good enough starting point if simply allowing Windows 10 to manage it automatically will not work.

A: There is no hard and fast rule that encompasses the ideal page file size on all systems; it's very specific to the workload your computer is exposed to. The accepted answer here is what one would recommend to a casual user, not a power user.
Budgeting for max workloads: If you expect to max out your RAM usage, then at the very least you should be budgeting enough virtual memory to cover any worst case scenarios. I.e. if you have 32GB of RAM but often work with 50GB data sets, then you'll probably want a page file somewhere in the ballpark of 32GB to cover the difference and accommodate anything else that might be allocating memory.
Budgeting for Windows crash dumps: For complete memory dumps, you need a page file the size of your RAM + 1MB. Though complete memory dumps aren't typically needed since we also have kernel dumps, which will trim the file down by omitting information that is (probably) irrelevant to the crash. Kernel dumps are less demanding, but their size can vary considerably. According to Microsoft, kernel dumps will typically be around 1/3 the size of the RAM on your system.
Windows will use the page file even when RAM is available: This is important to keep in mind, especially if you're seeing unexpected slowdown with large page files. Windows will monitor memory usage and might page away processes with less activity to accommodate more active processes and also any processes that you may launch in the future. Take Windows Update vs your desktop, for example. The vast majority of the time Update is dormant while your desktop isn't, so it will page Update in favor of caching the desktop in active memory, i.e. giving RAM to the process that more actively needs it.
Windows is constantly making these decisions; managing a cache for hundreds of files that are constantly being written by background services whilst balancing it with the memory demands of active processes. Unfortunately Windows may not always get the priorities right, and we end up having to wait for the OS to page data back into active memory. It's possible, though I'm only assuming, that the amount of page space available plays some limited role in whether or not Windows decides something can be 'safely' paged without creating a dramatic impact on responsiveness.
Set it to your system's needs: Ideally, you'll want to be as helpful to your OS as possible by setting the page file size to nothing more or less than your system will potentially need. Setting it to some arbitrary value, like 1.5x your RAM, can either be overkill or underkill and may have a negative impact on system performance or reliability.


text:
Q: How to output result of a mysql query as a json file in node.js What i have her is this
app.post('/login', function (req, res){
  connection.connect();
  email = req.body.email;
  password = req.body.password;
  if(email && password ) {
    console.log(email);
    console.log(password);
   // connection.query('SELECT username FROM user WHERE email =? and password = ?', [email, password],
   // function (error, rows, fields) {
    connection.query('SELECT * FROM user ',
    function (error, rows, fields) {
      var str='';
      for (var i = 0;i < rows.length; i++) {
        str = str + rows[i].username;
        res.end(str);
      }
      connection.end();
    });
  }
});

so instead of just displaying the result i want it to be something like this:
{
 "username": "ABC",
 "username": "DEF",
 "username": "HIJ"
}

A: The first problem is you're not actually building the object you want. The second problem is you're not building an array of them. Finally, you need to convert that array into JSON if the res object doesn't have something like res.json.
var objs = [];
for (var i = 0;i < rows.length; i++) {
    objs.push({username: rows[i].username});
}
connection.end();
res.end(JSON.stringify(objs));

A: With Express 4.x, the output rows from mysql db is in json format.
For example, look at this

sqlConnect.connection.query('SELECT * from users', function(err, rows, fields){
  if (err)
  {
   console.log("Querying error");
  }
  else
  {
   console.log(rows);
  }
  sqlConnect.connection.end();
 });
});

The output is of the form

[ RowDataPacket {
    id: 1,
    username: 'shivkanth',
    password: '1q2w3e4r',
    verified: 0 } ]

So now you can get the individual values using the . operator. For example, console.log(rows[0].username)  will log the value 'shivkanth'


text:
Q: Who allocates the memory for control block of shared_ptr when using custom new() operator with a class Suppose I have a code like this:
class Foo
{
private:
    int x;
public:
    void* operator new(size_t size);
    void operator delete(void* p);
};

int main() {
    auto ptr = std::shared_ptr<Foo>(new Foo());
    return 0;
}

The shared_ptr will create separate control-block and object-block. I suppose the memory for the object block will be created using the Foo::operator new(). Is the memory for the control-block created using ::operator new() or Foo::operator new()? And in case of make_shared, would the entire single-block of memory be allocated using Foo::operator new()?

A:
The shared_ptr will create separate control-block and object-block.  I suppose the memory for the object block will be created using the Foo::operator new().

Nope. You already passed in the pointer to the object, so it only needs a control block. In fact, I believe no shared_ptr construction allocates a single object-block, they never need it.

Is the memory for the control-block created using ::operator new() or Foo::operator new()?

C++ spec doesn't specify, but the sane thing for an implementation to do is rebind the allocator to an Allocator<ControlBlock> and use its allocate member, which will almost certainly use ::operator new(). It's allocating a ControlBlock, not a Foo.

And in case of make_shared, would the entire single-block of memory be allocated using Foo::operator new()?

The C++ spec does specify this one:

3.11.3.6 ... The allocate_shared templates use a copy of a (rebound for an unspecified value_type) to allocate memory...
7 Remarks: (7.1) — Implementations should perform no more than one memory allocation. [ Note: This provides efficiency equivalent to an intrusive smart pointer. — end note ]>

In this case, the implementation will rebind the allocator to an Allocator<ControlAndObjectBlock> and use its allocate member, which will almost certainly again use ::operator new(), since it's allocating a ControlAndObjectBlock instead of a Foo.
summary: Since shared_ptr never actually allocates an object block by itself, it'll never use Foo::operator new. However, your std::shared_ptr<Foo>(new Foo()) expression allocates a Foo using Foo::operator new, and then constructs a std::shared_ptr<Foo> from that pointer.


text:
Q: DataPager, change count items I'm using a DataPager control, I want to change count items on each page.
For example :
the First page 6 rows, the second page 311, the third page 12, etc.
Is it possible? If so, how?

A: my advice is to do it manually, make your own sql query and customize the page size as you want
here are some tips that can help

*

*to get range of rows that are needed for pagination user the row number

MS-sql row number

*

*use the TOP to get the upper set of rows
select TOP 5 * from ....

*for sure you'll need to get specific row numbers that will be displayed in the current page
select (--get row number--) from tbl_smth where row_num>5 and row_num<10
were as i guess that you have the page sizes in an array so you have to count them to determine the two numbers {5,10}
hope this will help


text:
Q: what is the difference between 'order' and 'order line'? I was trying to understand degenerate dimensions. But I quite often encounters the term "order line" as grain in an transaction table. Could someone please explain the difference between the order and order-line ?

A: Generally, an order contains information about the order.  Who placed the order, what time they placed it, the shipping address associated, the billing address, payment method, when it was fulfilled, etc.  It often does not contain any information about what was ordered.
The order line generally contains information about what was ordered, this is done because a single order can have multiple items in it.  So the order line would specify the item ordered, the quantity ordered and the price charged, and there would be one line for each different item ordered.


text:
Q: UIView not showing outlets I have an iOS project which I moved from Xcode 4 to Xcode 5.
The problem is that when I run the project then some views don't show any UI elements like button, tableview which are also outlets. All the elements are present in ViewController Pane but they are not visible in View.
Please help me out.

A: I have updated my code from xcode 4 to 5 then the main view sizes have been modified . i.e it starts from 0,0,768,1024 to 768,0,768,1024 . So please check the main view frame.

A: Try deselecting Use Autolayout in the File Inspector pane for the XIB file.

A: iOS 7 uses Full layout for the view..Means Origin is behind the status bar.You can use the property and you can set like previous way as it use to work in iOS6.0
self.edgesForExtendedLayout=UIRectEdgeNone


text:
Q: How can I use induction to prove that this recursive definition is correct? How can I use induction to prove that this recursive definition is correct?
$f(n)=4n-2$ for $n≥1$
Recursive definition:
1) $f(1)=2$
2) $f(n)=f(n-1)+4$
Now I have to use induction to prove that the recursive definition is correct but I don't know how to do it since $f(n)$ is not equal to anything.

A: Let $f$ be defined as in your question and let $g$ be defined recursively by $g(1)=2$ and $g(n)=g(n-1)+4$.
Then it is enough to prove by induction that $g(n)=f(n)$ for positive integers.
The base case is just the observation that $g(1)=2=f(1)$.
Now the induction step:
If $g(n)=f(n)=4n-2$ then $g(n+1)=g(n)+4=4n-2+4=4n+2=f(n+1)$.

A: HINT
We have that for the base case

*

*$f(1)=2$ by recursive relation

*$f(1)=4-2=2$ by formula
for induction step we assume true

*

*$f(n)=f(n-1)+4=4n-2$

and we need to prove that

*

*$f(n+1)=f(n)+4=4(n+1)-2$


text:
Q: Multiple indices in ggplot label I would like to add a label containing multiple indices to a bar plot:
data<-as.data.frame(c("A"))
colnames(data)<-"A"
data$B<-5

ggplot(data, aes(x=A, y=B)) +
  geom_bar(stat="identity", colour="black", position="dodge", size=0.25, width=0.8, alpha=0.8) +
  annotate("text", x=1, y=2.5, label="some text")

I need to replace "some text" with "a1 a2 a3" where the numbers are in subscript. I tried the following but get errors:
annotate("text", x=1, y=0.4, parse=T, label=paste("a[1]","a[2]","a[3]",sep="     "))

A: The following does that:
ggplot(data, aes(x=A, y=B)) + geom_bar(stat="identity", colour="black", position="dodge", size=0.25, width=0.8, alpha=0.8) + annotate("text", x=1, y=2.5, label="~a[1]~a[2]~a[3]", parse=TRUE)


text:
Q: AWS EC2 Instance - Is it a single virtual image or single physical machine? Sorry, I had a few basic questions. I'm planning to use an AWS EC2 instance.
1) Is an EC2 instance a single virtual machine image or is it a
single physical machine? Documentation from Amazon states that it is
a "virtual server", but I wanted to clarify if it is an image
embedded inside one server or if it is an single physical server
itself.

2) Is an Elastic Load Balancer a single EC2 instance that handles
all requests from all users and simply forwards the request to the
least loaded EC2 instances?

3) When Auto-Scaling is enabled for an EC2 instance, does it simply
exactly replicate the original EC2 instance when it needs to scale
up?

A: *

*An EC2 instance is a VM that gets some percentage of the underlying physical host's RAM, CPU, disk, and network i/o. That percentage could theoretically be 100% for certain instance types, including bare-metal instances, but is typically some fraction depending on which instance type you choose.

*ELB is a service, not a single EC2 instance. It will scale on your behalf. It routes by round robin for TCP, and routes on fewest outstanding requests for HTTP and HTTPS.

*Auto Scaling is "scale out" (it adds new EC2 instances), not "scale up" (resizing an existing EC2 instance). It launches a new instance from a template called an AMI.

A: *

*It is a virtual server, a VM, as stated in the documentation.

*It's a little more complicated that that, based on the way AWS might scale the load balancer, or create a version in each availability zone, etc. It also provides more features such as auto-scaling integration, health checks, SSL termination. I suggest you read the documentation.

*It uses a machine image that you specify when you create the auto-scaling group (when you create the Launch Configuration used by the Auto-scaling group to be more precise). A common practice is to configure a machine image that will download any updates and launch the latest version of your application on startup.

You might also be interested in Elastic Beanstalk which is a PaaS that manages much of the AWS infrastructure for you. There are also third-party PaaS offerings such as OpenShift and Heroku that also manage AWS resources for you.


text:
Q: PHP How to Redirect to Another Page with Apache Server? I'm trying to redirect to another page:
The idea is to create a submit button for user to click on it, then redirect to another page that also has the database records (MySQL Database).
Update: I'm using SELF PROCESSING form and with SEVERAL SUBMIT BUTTONS that have different functionality.
Here's my code with problems:
//Redirect and for user to delete particular record(s)
if(isset($_POST['delete'])){
    $query="DELETE FROM Student WHERE StudentId='$id'";
    $qresult=mysqli_query($link,$query);
    if($qresult){
        header("HTTP/1.1 301 Moved Permanently");
        $redirect='/RedirectedPage.php';
        header('Location:'.$redirect,true,303);
        exit;
    }
}

As you can see, I'm doing it with header() but it doesn't redirect,
instead, the current page only refreshed itself.
The database linked successfully, query seems ok...
Therefore, I'm wondering what's wrong?

A: Just submit your form to another page

<form action="delete.php">

  <input name="delete" type="submit" value="delete">
</form>

so your php code should be in the delete.php file
you can also change your code to this

//Redirect and for user to delete particular record(s)
if(isset($_POST['delete'])){
    $query="DELETE FROM Student WHERE StudentId='$id'";
    $qresult=mysqli_query($link,$query);
    if($qresult){

        header("Location: RedirectedPage.php");
        exit;
    }
}


text:
Q: ajax retornando branco eu mais uma vez aqui. Vamos lá rs.
Bom, meu problema esta sendo o seguinte:
Estou passando valores para meu metodo no php via ajax, porém eles nao esta me retornando nada, fiz alguns teste e ele estra travando na seguinte linha
Vou postar o código do teste (onde ele me da retorno) e o que eu quero porém esta travando

Método PHP

public function listarCidade($id)
{
    $obj_cidade = $this->verTodos("est_id=$id");
    if( $obj_cidade )
    {
        $opt="";
        foreach ($obj_cidade as $key)
            $opt .= "<option value='{$key->id}'>{$key->cid_nome}</option>";

        echo json_encode($opt);
    }
}

Nesta linha:
$opt .= "<option value='{$key->id}'>{$key->cid_nome}</option>";

 -O problema está sendo apenas isso ( `$key->cid_nome` )

pois se eu remover este pequeno código ele me da o retorno porem sem nada escrito no
<option></option>
O que fazer em galera ?

A: json é para retornar array, seu código está criando uma string, então é só dar echo $opt e deve funcionar.
Agora se está retonando outra coisa, tem que postar o código de requisição do ajax e também os dados da página html que ele está pegando.


text:
Q: Blending together wav files using numpy in python 3 I'm trying to create a single audio file out of multiple wav files. Using tkinter and pygame.mixer, I've converted key presses into a dictionary that stores audio samples and the time they're invoked. {sound1:10000, sound2:10001, ect...}
So far I've devised a way to add blocks of silence:
def change_speed(seconds):
    '''modifies the metronome beat to loop at different speeds. This is done by creating a new wav file.'''
    #original wav file is 0.1 seconds long, so subtract that from time added
    seconds-=0.1
    #read the original wav file
    original = scipy.io.wavfile.read('Downloads\\sounds\\metronome_original.wav')
    #use sample rate of the original file (should be 44100) to create a new block of silence
    add_secs = np.array([[0]]*round(original[0]*seconds))
    add_secs.dtype='int16'
    #concatenate new block to original
    new = np.concatenate((original[1], add_secs))
    scipy.io.wavfile.write('Downloads\\sounds\\metronome.wav', original[0], new)

Is there some way to combine overlapping arrays like [[0,0,1,1,2,0], [0,0,0,3,2,1]] into a single wav file?
Update:
To be more specific, I'm trying to merge two audio samples that overlap in playtime, like a DJ who starts playing one song before the other one finishes. Is there a way to do this with integer or byte arrays generated in python?
Like so:

A: Here's how I'd do it:
wav1 = [0,0,1,1,2,0]
wav2 = [0,0,0,3,2,1]
combined = np.hstack([wav1, wav2])

from scipy.io import wavfile
import numpy as np

N = 2400  # Samples per second.

wavfile.write('combined.wav', rate=N, data=combined.astype(np.int16))


text:
Q: python - binary search stuck in infinite loop Could I please have advise on my binary search code? It is stuck in an infinite loop. I have gone through a code a couple of times but don't seem to be able to spot the problem. I have omitted the first part of the code as it works well. In short, the first part of the code reads a set of data into a dictionary list called 'bait_dict'.
import csv

def comparison (input_file, output_file):
    count = 0
    count_in = 0
    count_out = 0
    for line in input_file:
        count += 1
        chrom_file = line[0]
        base_file = int(line[1])
        if chrom_file in bait_dict:
            for value in bait_dict[chrom_file]:
                low = 0
                high = len (bait_dict[chrom_file]) - 1
            while low <= high:
                mid = (low + high)//2
                start, end = bait_dict[chrom_file][mid]
                if base_file < start:
                    high = mid - 1
                elif base_file > end:
                    low = mid + 1
                elif start <= base_file and base_file <= end:
                    count_in += 1
                    output_file.writerow(line)
                    break
            count_out += 1


text:
Q: How to serialize a object to CBOR with Newtonsoft.Json.Cbor Has anyone used Newtonsoft.Json.Cbor to serialize a .NET object to a CBOR array? How is its performance when serializing a big object to CBOR array with C# - I expect a LOH will be generated.
Could you provide the sample code that you have done?


text:
Q: How to flash.keep when devise redirects to login path After registration, which needs confirmation, my app redirects to an authenticated page so authentication fails and Devise redirects to the login path.
My flash message after registration is lost because of the second redirect.
Is there somewhere I can add a flash.keep before redirecting to the login path, in application_controller.rb or in a helper? I'd prefer not to override a devise controller for this if there's an alternative.

A: After registration, I store a flash message in the session before the redirection to the login path kicks in (because the user is unconfirmed it's "after_inactive_sign_up_path_for()")
Devise Registrations controller:
class RegistrationsController < Devise::RegistrationsController
  protected
    def after_inactive_sign_up_path_for(resource)
      # store message to be displayed after redirection to login screen
      session[:registration_flash] = flash[:notice] if flash[:notice]
      super
    end
end

Then I show this message if it's present during the login request.
Devise Sessions controller:
class SessionsController < Devise::SessionsController
  def new
    flash[:notice] = session.delete(:registration_flash) if session[:registration_flash]
    super
  end
end

A: Updating @rigyt's answer to newest devise using the Devise Failure App methodology
Create a custom failure app as shown in the link above.
lib/devise_failure.rb :
  def respond
    if http_auth?
      http_auth
    else
      # From original Devise Failure App
      store_location!
      if flash[:timedout] && flash[:alert]
        flash.keep(:timedout)
        flash.keep(:alert)
      else
        flash[:alert] = i18n_message
      end

      # Store flash temporarily in session because devise strips it
      session[:login_flash] = flash.to_hash

      redirect_to new_user_session_path
    end
  end

sessions_controller :
  def new
    flash_from_session
    super
  end

  def flash_from_session
    if session[:login_flash]
      session[:login_flash].each do |arr|
        flash[arr.first] = arr.last
      end
      session.delete(:login_flash)
    end
  end

This will set the flashes as expected and remove them from the session.  I've also found it works well with pivotal's cacheable_flash

A: Why not just change the default devise flash message to whatever you want your message to say? You can edit the flash message in the devise.en.yml file. I think the one you are looking for is under registrations signed_up_but_unconfirmed


text:
Q: How to resolve unwanted flickering of Controls when the Form has a background Image? Overview of problem
I am facing this issue when I try to hide some Labels, TextBoxes and a Button: all these Control flicker as they hide but other Control that are not involved are fine. I do not want this effect.
Also, this doesn't happen for Show(), only happens for Hide().

What I have tried:
Removing the background image resolved this problem but I do want my background image visible.
When I searched the Web, I learnt how to create this effect intentionally, however I could not find a solution to remove it.
Others stated that this is just a hardware limitation however I do have a capable CPU.
VB.NET Code:
Its just some <element>.Hide()s
Private Sub GetTaskNameButton_Click(sender As Object, e As EventArgs) Handles GetTaskNameButton.Click
    GetTaskNameButton.Hide()
    TaskInputTextBox.Hide()
    TaskNameInputLabel.Hide()
    TaskTimeLabel.Hide()
    TaskHourLabel.Hide()
    TaskHoursBox.Hide()
    TaskMinutesLabel.Hide()
    TaskMinsBox.Hide()
    TasksCheckedListBox.Items.Add(TaskInputTextBox.Text + " >Time: " + TaskHoursBox.Text + "Hr " + TaskMinsBox.Text + "Min")
    TaskInputTextBox.Text = ""
    TaskHoursBox.Text = ""
    TaskMinsBox.Text = ""
End Sub

A: Nothing to do with CPU limitations. This is related to the rendering of the Background of a Form and the content of its child Controls.
Read a description here: How to fix the flickering in User Controls.
(but WS_EX_COMPOSITED won't help you here).
Since you have some Controls that a combined functionality, you can build a UserControl to group the single Controls into a specialized entity that provide the functionality and contains all the logic required to perform this Task and notify when a choice has been made (all input values are validated and the submit Button is cliecked).
To handle the transparency of this UserControl, you have to tweak its standard behavior a little bit, since just setting BackColor = Color.Transparent is not enough when you have a Form with a background Image: the Transparency would be simulated considering the Form's Background Color, not the content of the background Image (an Image is not a Color).
You can make your UserControl actually transparent, preventing its background from being painted.

*

*Use SetStyle() to set ControlStyles.Opaque, so the background is not painted.

*Set ControlStyles.OptimizedDoubleBuffer to False: this UserControl cannot use DoubleBuffering of course, otherwise we're back at square one (the Parent Control's background is used to build the BufferedGraphcs object)

*Override CreateParams to add WS_EX_TRANSPARENT to the extended styles of the UserControl Window, so the System won't interfere, letting other windows behind the UserControl draw their content first (but we won't draw ours after).

*The WS_CLIPCHILDREN Style needs to be removed (since the base class, Control, adds it) otherwise the UserControls's child Controls may disappear when the Form is resized.

When the Add Task Button is clicked, the UserControl can raise a public event, passing in a custom EventArgs object - after validation - the values entered.
The Form can subscribe to this event and read the custom EventArgs Properties when the event is raised.

*

*Since your Form has a BackgroudImage, set DoubleBuffered = True.

This is how it looks like:

The Image shown here has a size of 3840x2560 (it's freely downloadable from the Web).
Try to resize the Form without double-buffering it :)
A PasteBin of the complete UserControl, in case it's needed:
Transparent UserControl

Assuming the UserControl (AddNewTask) added to a Form is named AddNewTask1, you can add an event handler to its AddTaskClicked event, using the Designer or in code, in the Form Constructor:
Public Class SomeForm
    Public Sub New()
        InitializeComponent()
        AddHandler AddNewTask1.AddTaskClicked, AddressOf OnTaskAdded
    End Sub

    Private Sub OnTaskAdded(sender As Object, e As AddNewTask.AddTaskEventArgs)
        Dim values As String = $"{e.TaskName}: Hours: {e.TaskHours}, Minutes: {e.TaskMinutes}"
    End Sub
End Sub

The AddNewTask UserControl:
Public Class AddNewTask

    Private Const WS_EX_TRANSPARENT As Integer = &H20
    Private Const WS_CLIPCHILDREN As Integer = &H2000000

    Public Event AddTaskClicked As EventHandler(Of AddTaskEventArgs)

    Public Sub New()
        SetStyle(ControlStyles.Opaque Or ControlStyles.ResizeRedraw, True)
        SetStyle(ControlStyles.OptimizedDoubleBuffer, False)
        InitializeComponent()
    End Sub

    Protected Overrides ReadOnly Property CreateParams As CreateParams
        Get
            Dim cp As CreateParams = MyBase.CreateParams
            cp.Style = cp.Style And Not WS_CLIPCHILDREN
            cp.ExStyle = cp.ExStyle Or WS_EX_TRANSPARENT
            Return cp
        End Get
    End Property

    Private Sub btnAddTask_Click(sender As Object, e As EventArgs) Handles btnAddTask.Click
        Dim hours As UInteger
        Dim sHours = If(String.IsNullOrEmpty(txtHours.Text.Trim()), "0", txtHours.Text)

        If (Not UInteger.TryParse(sHours, hours)) Then
            ShowInputErrorMessage("Invalid Hours", txtHours)
            Return
        End If

        Dim minutes As UInteger
        Dim sMinutes = If(String.IsNullOrEmpty(txtMinutes.Text.Trim()), "0", txtMinutes.Text)

        If (Not UInteger.TryParse(sMinutes, minutes)) Then
            ShowInputErrorMessage("Invalid Minutes", txtMinutes)
            Return
        End If

        Hide()
        Dim args = New AddTaskEventArgs(txtTaskName.Text, hours, minutes)
        RaiseEvent AddTaskClicked(Me, args)

        txtHours.Clear()
        txtMinutes.Clear()
        txtTaskName.Clear()
        ActiveControl = txtTaskName
    End Sub

    Private Sub ShowInputErrorMessage(msg As String, ctrl As TextBox)
        MessageBox.Show(msg)
        ctrl.Select()
        ctrl.SelectAll()
    End Sub

    Public Class AddTaskEventArgs
        Inherits EventArgs
        Public Sub New(sTaskName As String, hours As UInteger, minutes As UInteger)
            TaskName = sTaskName
            TaskHours = hours
            TaskMinutes = minutes
        End Sub
        Public ReadOnly Property TaskName As String
        Public ReadOnly Property TaskHours As UInteger
        Public ReadOnly Property TaskMinutes As UInteger
    End Class
End Class


text:
Q: Android Studio 3 appcompat resourses not found Hey I have a problem with Android Studio 3(Beta-2)
Every time I create new/open existing project it shows me following errors:

Clean, Rebuild, Restart Studio, Removing gradle files don't work.
In the studio 2.3, everything is fine.
My build.gradle file:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    dataBinding.enabled = true
    defaultConfig {
        applicationId "com.valentun.findgift"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
         exclude group: 'com.android.support', module: 'support-annotations'
    })

    annotationProcessor 'com.jakewharton:butterknife-compiler:8.7.0'
    compile 'com.jakewharton:butterknife:8.7.0'

    compile 'com.google.dagger:dagger:2.11'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.11'

    compile 'com.android.support:appcompat-v7:25.4.0'
    compile 'com.android.support:cardview-v7:25.4.0'
    compile 'com.android.support:design:25.4.0'

    compile 'com.google.firebase:firebase-storage:11.0.2'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.squareup.retrofit2:converter-jackson:2.3.0'
    compile 'com.github.aakira:expandable-layout:1.6.0@aar'
    testCompile 'junit:junit:4.12'

}

apply plugin: 'com.google.gms.google-services'

Project's graddle file:
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0-beta2'
    classpath 'com.google.gms:google-services:3.1.0'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
    maven {
        url 'https://jitpack.io'
    }
    maven {
        url "https://maven.google.com"
    }
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

A: Remove Gradle files (.gradle folder) from your project folder (C:\Users.....gradle) and try reopening the Android Studio.
Hope this will help.

A: Change version 25 to 26
apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
    applicationId "seesaa.vn.testandroidstudio"
    minSdkVersion 17
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:26.0.1'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.0'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.0'
}

A: Your compile SDK version must match the support library's major version.
Since you are using version 25 of the support library, you need to compile against version 25 of the Android SDK.

A: Try File -> invalidate caches / Restart. Hope this will help.


text:
Q: Upgrading gradle 4.5 to 7.2, throws error Could not get unknown property 'java' for SoftwareComponentInternal I am upgrading gradle 4.5 to 7.2. on build.gradle it throws exception "Could not get unknown property 'java' for SoftwareComponentInternal set of type org.gradle.api.internal.component.DefaultSoftwareComponentContainer." on line 118. The code at line 118 is as follows.
publishing {
repositories {
    maven {
        credentials {
            username=mvn_user
            password=mvn_pass
        }

        if (version.endsWith("-SNAPSHOT")) {
            url snapshotRepo
            println "Publishing to ${snapshotRepo}"
        }
        else {
            url releaseRepo
            println "Publishing to ${releaseRepo}"
        }
    }
}

publications {
    mavenJava(MavenPublication) {

        artifactId = mavenArtifactId

        from project(':server').components.java

        artifact project(':server').javadocJar
        artifact project(':server').sourceJar
        artifact examplePropertiesArtifact
        artifact exampleLog4jFileArtifact
        artifact windowsScriptFile
        artifact linuxScriptArtifact
        artifact aixScriptArtifact

A: MavenPublication should work with Gradle 7.x ...while it might not know about:
from project(':server').components.java

There was a change in Gradle 4.8, which requires to wrap with: afterEvaluate {}:

Prior to Gradle 5.0, the publishing {} block was (by default) implicitly treated as if all the logic inside it was executed after the project is evaluated. This behavior caused quite a bit of confusion and was deprecated in Gradle 4.8, because it was the only block that behaved that way.

A: Use plugin java-library instead of java as gradle have change java plugin to java-library plugin
apply plugin: 'java-library'


text:
Q: How to cotinuosly append data from DB2 server to sqlite using preferably django and if nothing else then python alone code I am writing a django website that has some reports that pulls data based on DB2 database. Since I have only read only access to that database, I want the data from DB2 to be continuosly appended (or appended at intervals of lets say 20 minutes) to sqlite database being used by django.
Now I am totally new to python as well hence I am blank with what should I use for this.
Is there any django method that can be implemented or should I write a python only script to copy the data.
Lets say I have a database with fields - DEAL,BUSINESS,CUSTID,REPID,REPNAME in DB2 (I don't have any primary key here since the database if very old). I want to continuisly copy this data from DB2 to Sqlite. What should be the simplest code?
Please help.

A: Sql alchemy module is what you need
And for peridocal tasks what you need is a cron job

A: Keep in mind that Db2 for Linux Unix windows, Db2 for zOS, Db2 for IBM i, and Db2 Warehouse are all different inside, so, if you need further information, specify type and version of Db2.
For moving data periodically you have many options. @Iakovos_Belonias suggestion is one of them.  Your main challenge will be recognizing new rows, rows being changed, and rows being deleted.  If source table is not very large, you can copy it completely, but if the source table is large, you will have to try a smarter mechanism.  If this is the case, please put comment or open a new question.
For moving data near-real-time, the best option is by using a Change Data Capture (CDC) application such as IBM Infosphere Data Replication or Oracle Golden Gate, among others.  I think there is not a free CDC application (except for licenses with limitations that will not cover your need), and commercial CDC applications are offered for Db2 versions still under supported.
I hope this help...


text:
Q: How to dynamically number theorems? I am writing an introduction. I want to reference theorems and so on which come later. I want to do something like the following.
\newtheorem*{thmcustom}[1]{Theorem #1}
Then \begin{thmcustom}[3.2.1] .. \end{thmcustom} would print out Thereom 3.2.1:... (In general I would have a \ref{thm:whatever} as opposed to the 3.2.1, but anyway.)
Of course, this doesn't work. Is there a way which I can do this?
(I have a hideous hack of doing \newtheorem*{thmA}{Theorem \ref{thm:thmA}} for each theorem I want to reference.
\documentclass[a4paper,10pt]{article}
\usepackage{amsthm}
\newtheorem{theorem}{Theorem}
\newtheorem*{thmA}{Theorem \ref{thm:thmA}}

\begin{document}
The same theorem which comes later:
\begin{thmA}
This is a theorem.
\end{thmA}

The original statement of the theorem.
\begin{theorem}
\label{thm:thmA}
This is a theorem.
\end{theorem}
\end{document}

This is awful! So anything will be better...)

A: Here's a (not so dirty) hack, based on the amsthm package.
The theoremff environment is used for "fast-forward" theorems.
The first (optional) argument is the theorem's name.
The second argument is the theorem's label.
Notice that theorems are not dynamically numbered, I don't think you would want that!  They are numbered as usual, but you are able to "fast-forward" some of them, using of course the same number that they will have later on.  (Indeed, "fast-forward" is probably misleading, as you may equally well use this for theorems that have already appeared.)  I hope I did not misinterpret your intentions.
\documentclass{article}
\usepackage{amsthm}

\newtheorem{theorem}{Theorem}
\newtheorem*{theoremaux}{Theorem \theoremauxnum}
\gdef\theoremauxnum{1}

\newenvironment{theoremff}[2][]{%
  \def\theoremauxnum{\ref{#2}}
  \begin{theoremaux}[#1]
}{%
  \end{theoremaux}
}

\begin{document}

\section{Introduction}
Here are the two theorems that we will prove:

\begin{theoremff}[Progress]{thm:progress}
Progress theorem.
\end{theoremff}

\begin{theoremff}[Preservation]{thm:preservation}
Preservation theorem.
\end{theoremff}

\section{Metatheory}
And here are their proofs:

\begin{theorem}[Progress]
\label{thm:progress}
Progress theorem.
\begin{proof}
Easy.
\end{proof}
\end{theorem}

\begin{theorem}[Preservation]
\label{thm:preservation}
Preservation theorem.
\begin{proof}
Trivial.
\end{proof}
\end{theorem}

\end{document}

This is what you get for the document above.


text:
Q: Transição reversa de slide, VUE JS Estou desenvolvendo uma single page aplication/app mobile, com VUE JS, quero efeito slide ao trocar de páginas, e já consigo fazer isso dessa maneira:
transition name="slide"
router-view
transition

Porém eu queria o efeito inverso do slide quando o usuário voltar a página, ou seja, quando o usuário abrir uma nova página, a página virá da direita, quando votar, a página virá da esquerda.
Tem um plugin para vue router, chamado vue-router-transition (Link) mas não funciona, está desatualizado, da erros, só funciona com  versões muito antigas do VUE.
Também tem tutorial de como fazer transições dinâmicas, mas só funciona quando for rotas filhas, como site.com/rota1/rota2/rota3, o que não é o meu caso: https://router.vuejs.org/en/advanced/transitions.html
Pensei na seguinte lógica, no before.each.router, definir a classe da transição, (slide-left ou slide-right) dependendo se o usuário clicou em algum botão de Go back, o problema é que eu não sei aplicar essa lógica no código, teria que passar o valor de uma variável que esta no main.js para o app.vue e eu não sei como fazer isso...


text:
Q: How do I get an Azure API App to work if published from Visual Studio 2019 without API Mgmt in between? I am using Visual Studio 2019 ver 16.7.2.
I have an API Project that is called JobBank.API.  In Visual Studio, my App URL in the project settings is http://localhost://6705.  I also have a Swagger file created and configured in my Startup.cs as: "/swagger/JobBankOpenAPISpecification/swagger.json".
I published the API Project using Visual Studio to an Azure API App Service.  The URL is "http://jobbank-api-demo.azurewebsites.net.  After I publish it, a browser windows comes up to that URL with a 500 error saying "jobbank-api-demo.azurewebsites.net can't currently handle this request.".
Also when I try that url with "/swagger.json" I get a 500 error.
What do I need to do?

A: There was a bug in the .net cores 2.0 version of this problem. The 3.1 version we are currently using, I personally tested it, and this problem should have been resolved.
I will post my screenshot first to see if it is the result you want.

From the pic, we can see I have deployed my test web on azure, and also can open swagger.json file, no 500 Error.
So, I think you should check your code. You can download my test code from github.
When you test my code, you should modify links in index.html file under wwwroot folder . And when you deploy the demo, you will get 404 error. Don't worry, you need to attach /index.html at the url.
When you finish all the operations, you will get the same result as mine.
Details encountered when trying to solve your problem:
When I modify default route in startup.cs file.

When I add these code in project, it will get 500 Error. So If your code has same configurations, I suggest you remove it, and use url rewrite.


text:
Q: NOT NULL constraint failed: posts_comment.post_id django I have the basics of a blogs app (I have been following Corey Schafer's tutorial, part 10, if that matters) and I am trying to post and display comments on the post that other users have wrote that only relate to that post. Similar to that of a comment section on Facebook or YouTube.
Currently I'm displaying all comments in the database on every post because I don't know how to filter the results to only show comments for the specific post and I also don't know how to post comments to a specific post, that's where I get the error.
My code is below:
Models.py
class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date_posted = models.DateTimeField(default=timezone.now)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('core:post-detail', kwargs={'pk': self.pk})

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.user.username

Views.py
class PostDetailView(DetailView):
    model = Post
    context_object_name = 'posts'

    def get_context_data(self, **kwargs):
        context = super(PostDetailView, self).get_context_data(**kwargs)
        context['comment'] = Comment.objects.all()
        return context

class CommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    fields = ['content']

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

urls.py (This is the urls.py file in my main app where I'm calling the blogs app views)
path('posts/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('posts/<int:pk>/comment', CommentCreateView.as_view(), name='comment-create'),

I then have this form in a file called comment_form.html that I can connect to when I got to http://127.0.0.1:8000/posts/5/comment but when I click reply I get
IntegrityError at /posts/5/comment NOT NULL constraint failed: posts_comment.post_id
<form method="POST">
  {% csrf_token %}
  <fieldset class="form-group">
    <legend class="border-bottom mb-4"> Reply to Post </legend>
    {{ form|crispy}}
  </fieldset>
  <div class="form-group">.
    <button type="submit" class="btn btn-success">Reply</button>
  </div>
</form>

If someone could throw their eye over it and let me know if you can find anything that I could do to get it to work, I would greatly appreciate it. Let me know if you need more information/code.
Thanks

A: the problem is that you're creation form is missing a non nullable field, that's why django is complaining about the "NOT NULL CONSTRAINT"
so you have to add the post field to the form fields, or you can add it in the form_valid method:
def form_valid(self, form):
        form.instance.post = Post.objects.get(pk=self.kwargs.get("pk"))
        form.instance.user = self.request.user
        return super().form_valid(form)

if you want to ignore the post field, you can put null=True in the Comment Model:
class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post,null=True,blank=True,on_delete=models.CASCADE)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)


text:
Q: Change blue frame around buttons in CSS I'm having a problem with styling Bootstrap buttons when I want to change/remove blue frame around them after they've been clicked. Here's the case:

I've already seen many posts regarding this issue, and almost every one of them concludes with "use outline:none". For some reason, this isn't working for me. CSS code:
    .btn {
    color: white;
    border-radius: 0px;
    background-color:rgba(124, 122, 119, 0.405);
    border-color: rgba(255, 165, 0, 0.405);
    margin: 15px;
    max-width: 30%;
    max-height: 30%;
    outline: 0;
}

.btn:hover{
    border-color: white;
    background-color: rgba(190, 123, 34, 0.514);
    outline: 0;
}

.btn:focus{
    border-color: white;
    background-color: rgba(255, 166, 0, 0.418);
    outline: none;
    border: 0;
}

.btn:active {
    border: 0;
    outline: 0;
}

As you can see, I've blindlessly put the outline property everywhere, mixing it's every possibility with trial and error method. Still nothing.
Here's my HTML code for this button if you find it useful:
<button type="button" class="btn btn-primary" (click)="decrementStep()">Back</button>

Also, would be nice if you could tell me how to change button's background color when its being clicked, for some reason it doesn't work for me either. I think the problem's reason lies somewhere within Bootstrap, but I'm totally new to frontend and just a beginner with it. Also, if it matters, I'm using Angular. Thanks in advance.

A: Your blue border is cause by the btn-primary class.  You need to override the border colour and box shadow to remove it (also removed the outline just in case):

.btn.btn-primary {
  border-color:transparent !important;
  box-shadow:none !important;
  outline:none !important;
}

Example bootply

A: You could try to make a reset to the Input...
Some HTML elements have their own properties set by default and is different for each browser.
This is some information about the "reset" process:
Reset Forms

A: To switch it off you need the following css rule:
.btn:focus {
    box-shadow: none;
}

Because it's not an "outline" that's being used for that blue frame but box-shadow instead.


text:
Q: Using single cursor for many instances I came across this info that not closing the cursor or database gobbles up memory. So as i use the cursor across a hundred test cases I might forget to close it somewhere. Can I declare a single cursor and reuse it again and again making different references and finally closing it in the OnDestroy() method.
Eg. Cursor a;

//Another function
a = as.rawQuery("select * from verse"+k, null);

//Another  function
a = bs.rawQuery("select * from hello", null); //Another database

//Another function
a =  cs.rawQuery("select * from chapter", null); //Another database

//OnDestroy()
a.close();

Is it a feasible solution??

A: You cannot use a single cursor; each rawQuery call creates a new cursor object.
When you assign a reference to the new cursor object to a, the old object is not closed (and you cannot anymore reach it).
To ensure that close is always called, use try/finally:
Cursor c = db.rawQuery(...);
try {
    ... read data ...
} finally {
    c.close();
}

If you have a helper function that returns a cursor, do this in the calling function.


text:
Q: Ask aspell to skip part of document I'm using aspell to spell check LaTeX documents on Linux. Very often my documents contain samples of code in various programming languages, and I would like aspell to simply skip those lines while spell checking.
Is there anything I can write in my document to turn aspell off on a section of text? Something like:
This line should be spell checked.

% Hey, aspell, don't check the following lines
\begin{lstlisting}
if (xyzzy > foobar) {
    doSomethingSilly();
}
\end{lstlisting}
% Hey, aspell, please check the following

This line should be spell checked.

A: aspell to skip part of document

spellcheck LaTeX documents
LaTeX documents require a little more work.
command
aspell --lang=en_GB --add-tex-command="mySkip op" -c teste.tex

*

*put at start \mySkip[ after { again a \mySkip[
teste.tex
\documentclass{article}

\makeatletter
\def\myComment{\@ifnextchar[{\@with}{\@without}}
\def\@with[#1]#2{Hello #1, have you met #2?}
\def\@without#1{Goodbye #1.}
\makeatother

\mySkip[
 if (xyzzy > foobar) {
\mySkip[
   doSomethingSilly();
   doSomethingOther();
   doSomethingExtra();
 }
]]
This liine should be spell checked.

Problem after every opening curly brace { in the code you need \mySkip[
\mySkip[
 if (abcdef > foobar) {
\mySkip[
   doSomethingSilly();
   if (test > 100) {
\mySkip[
     doSomethingOther();
   }
   doSomethingExtra();
 }
]]
This liine should be spell checked.

With a search and replace you can make the code ready
before replace

after replace

For sgml it's easier.
Step by step

*

*create a folder aspell60-7

*copy teste.html into.

teste.html
This line should be spell checked.

<nospell>
if (xyzzy > foobar) {
    doSomethingSilly();
}
</nospell>
<script>
if (xyzzy > foobar) {
    doSomethingSilly();
}
</script>

This line should be spell checked.

*

*change a letter in teste.html

*cd into folder aspell60-7

*

*enter following command

aspell --lang=en_GB --add-filter=sgml --add-sgml-skip=nospell --add-sgml-skip=script -c -S teste.html

after run the command

*

*after enter 1 for 1) line .

*aspell terminates.

*Gedit tells file teste.html was changed.

*after new load

*previously modified word liine is correct.

*all lines surrounded by <nospell> and <script> are ignored.

this also works in windows, but only with aspell6.


text:
Q: Retrieve elements in string with jQuery I have a string like that :
<fieldset>
<legend>Sondage</legend>
<input type="hidden" value="formulaire_test/poll1352736068616/testencode" name="pollpost">

Q1

<input id="R010101" type="radio" value="A" name="R0101">
R11

<input id="R010102" type="radio" value="B" name="R0101">
r12

Q2

<input id="R010201" type="radio" value="A" name="R0102">
r2

<input id="R010202" type="radio" value="B" name="R0102">
r22

<input type="submit" value="Votez">

</fieldset>

I want with jQuery retrieve for example value of <legend>, values of
 or all inputs values..
Do you have any idea ?
I can put this string into a jQuery object $(mystring) and after ?
Thanks !

A: You can use following code to push input values into an array:
var arr = new Array();
$(mystring).find('input').each(function() {
    arr.push($(this).val());
});

A: You can use
$(mystring).find('legend').text();

or
$(mystring).find('input').val();

A: just do
$('legend').html(); // Text inside Legend

var questions = new Array();
$('p.question').each(function(){
     questions.push( $(this).html() ) ; // Questions class text into array
});

var inputs = new Array();
$('input').each(function(){
     inputs.push(this.value) ; // Input values into array
});

If you want to find these inside $(mystring) just prepend the selector with
$('mystring').find( selector )


text:
Q: Proof for transformation of random variables formula Suppose we have $U=g_1(X,Y)$, $V=g_2(X,Y)$ for two random variables, X,Y.
I want to prove this formula:
$$f_{U,V}(u,v)=f_{X,Y}(h_1(u,v), h_2(u,v))|J|$$
Question 1 Is this right?

$$f_{U,V} = \frac{\partial}{\partial u \partial v} P(U < u, V < v)$$ by the FTC.
$$= \frac{\partial}{\partial u \partial v} \int_{\{(x,y) : \\ g_1(x,y) < u,\\ g_2(x,y) < v  \}} f_{X,Y}(x,y)dxdy$$
$$= \frac{\partial}{\partial u \partial v} \int_{\{(x,y) : \\h_1(g_1(x,y),g_2(x,y)) < u, \\ h_2(g_1(x,y),g_2(x,y)) < v  \}} f_{X,Y}(x,y)dxdy$$
$$= \frac{\partial}{\partial u \partial v} \int_{\{(x,y) : \\h_1(g_1(x,y),g_2(x,y)) < u, \\ h_2(g_1(x,y),g_2(x,y)) < v  \}} f_{X,Y}(x,y) \left|\frac{\partial(x,y)}{\partial(u,v)} \right| dudv$$
$$= \frac{\partial}{\partial u \partial v} \int_{\{(x,y) : \\h_1(g_1(x,y),g_2(x,y)) < u, \\ h_2(g_1(x,y),g_2(x,y)) < v  \}} f_{X,Y}(x,y) \left|J \right| dudv$$
$$= \frac{\partial}{\partial u \partial v} \int_{\{(u,v) : \\h_1(u,v) < u, \\ h_2(u,v) < v  \}} f_{X,Y}(h_1(u,v),h_2(u,v)) \left|J \right| dudv$$
$$=f_{X,Y}(h_1(u,v), h_2(u,v))|J|$$
Question 2 I don't really understand what's going on in the last step. I think it's a certain application of the FTC, but I'm not quite making sense of how it works on the specified region of integration.


text:
Q: Cannot find -lalleg (DEV C++ e Allegro) Pessoal toda vez q tento rodar esse codigo está dando este erro
segue o codigo abaixo:
#include <allegro.h>

int main()
{
    allegro_init();
    install_keyboard();

    set_color_depth(32);
    set_gfx_mode(GFX_AUTODETECT_WINDOWED, 800, 600, 0, 0);

    BITMAP *buffer = create_bitmap(800, 600);
    BITMAP *prota  = load_bmp("personaje.bmp",NULL);

    bool salir;
    int x,y;

    // inicializar vbles
    x = 10;
    y = 10;
    salir = false;

    while ( !salir )
    {
          clear_to_color(buffer, 0xaaaaaa);

          masked_blit(prota, buffer, 0,0, x, y, 32,32);

          // teclas control usuario
          if ( key[KEY_UP] )
          {
               y--;
          }
          if ( key[KEY_DOWN] )
          {
               y++;
          }
          if ( key[KEY_LEFT] )
          {
               x--;
          }
          if ( key[KEY_RIGHT] )
          {
               x++;
          }

          // limites
          if ( x < 0 ) x = 0;
          if ( x > 800 ) x = 800;
          if ( y < 0 ) y = 0;
          if ( y > 600 ) y = 600;

          blit(buffer, screen, 0, 0, 0, 0, 800, 600);

          rest(10);

          // tecla de salida
          if ( key[KEY_ESC] ) salir = true;

    }

    destroy_bitmap(prota);
    destroy_bitmap(buffer);

    return 0;
}
END_OF_MAIN();


text:
Q: mysql join in another join I have three tables:
t1:
id | t2_connect
-----------------
1  | 2
2  | 3
3  | 2

t2:
id | t3_connect
-----------------
1  | 2
2  | 3
3  | 1

t3
id | goal
-----------------
1  | 10
2  | 100
3  | 1000

and I want to select goal values through t2 table
something like:
SELECT
t1.id, t3.goal
FROM t1
JOIN t2 ON (t2.id=t1.t2_connect)
JOIN t3 ON (t3.id=t2.t3_connect)
WHERE 1

But it is not working.(Error: Unknown column 't2.t3_connect' in 'on clause' ) Can you please help me with that.
I expect:
t1.id | t3.goal
-----------------
1  | 1000
2  | 10
3  | 1000

Thanks


text:
Q: File not found in python (WORDCLOUD) When I try to run this it says file not found. Is there any misatkes I've made?
from wordcloud import  WordCloud
from wordcloud import STOPWORDS
import sys
import os
import matplotlib.pyplot as plt
os.chdir(sys.path[0])

text = open('pokemon.txt', mode='r', encoding='utf-8').read()
stop = STOPWORDS

print(stop)

A: Since your file is in the same folder as the Python program, use ./ before your pokemon.txt like this:
text = open('./pokemon.txt', mode='r', encoding='utf-8').read()