text:
Q: Show one result each ID and keep time order I've created the following query which works with a slight problem:
SELECT pe.*, cache.column1,p.column2,p.ID
  FROM events AS pe
  INNER JOIN cache ON pe.ID = cache.ID
  INNER JOIN places AS p ON pe.ID = p.ID
WHERE pe.createdTime > *NOW UNIX TIME*
  GROUP BY pe.ID
  ORDER BY pe.createdTime ASC LIMIT 6

It shows the latest records as excepted, unless there are multiple records of pe table of the same p.ID, it shows the farthest pe table record (farthest = latest pe.createdTime instead of the upcoming).
Tried some changes, it's still shows the farthest record of this place( p.ID). Looking for your help!

A: If I understand correctly, you just need to fetch the record with the latest pe time.  You can do this with aggregation and a join:
SELECT pe.*, c.column1, p.column2,p.ID
FROM events pe INNER JOIN
     cache c
     ON pe.ID = c.ID INNER JOIN
     places p ON pe.ID = p.ID INNER JOIN
     (SELECT pe.id, MIN(createdTime) as minct
      FROM events pe
      WHERE pe.createdTime > *NOW UNIX TIME*
      GROUP BY pe.id
     ) pemin
     ON pe.id = pemin.id and pe.createdTime = pemin.mminct
GROUP BY pe.ID
ORDER BY pe.createdTime ASC
LIMIT 6;

You probably don't need the group by but without knowing your data, that is hard to say for sure.


text:
Q: Я не понимаю как в Listbox добавить текст при нажатии на кнопку from tkinter import *

spisok = ['Черкаси', 'Чернігів', 'Чернівці']

win = Tk()

frame = Frame(win)

scrollbar = Scrollbar(frame)

scrollbar.pack(side=RIGHT, fill=Y)

listbox = Listbox(yscrollcommand=scrollbar.set, width=40)

def knopka():

    listbox.insert(i)

listbox.pack(side=LEFT, fill=BOTH)

scrollbar.config(command=listbox.yview)

btn = Button(win, text='Нажми на меня', command=knopka)

win.mainloop()

A: from tkinter import *

spisok = ['Черкаси', 'Чернігів', 'Чернівці']

win = Tk()

frame = Frame(win)

scrollbar = Scrollbar(frame)
scrollbar.pack(side=RIGHT, fill=Y)

listbox = Listbox(yscrollcommand=scrollbar.set, width=40)

def knopka():
    listbox.insert(0,*spisok)

listbox.pack(side=LEFT, fill=BOTH)

scrollbar.config(command=listbox.yview)

btn = Button(win, text='Нажми на меня', command=knopka)
btn.pack()

win.mainloop()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple check boxes toggling back and forth I have a table with two check boxes.

             Test2
             <input type="checkbox" class="" id="rv" name="Vn" />
             DV
              <input type="checkbox" class="" id="dv" name="Dv" />

          <input type="button" id="vList" value="Run Report" />

Jquery function processing the check boxes is
       $(document).ready(function () {
       $("#vList").click(function () {
                  if ($('#rv').prop('checked', $(this).is(':checked'))) {
                      fnloadrv(test);
                  }
                  else if ($('#dv').prop('checked',$(this).is(':checked'))) {
                      fnloaddv();
                  }
             });

It works fine only first time. Second itme If I check the box again it wont do anything. I believe it needs to be reset or something.
Please let me know how fix so it can toggle back and forth. Thanks

A: Here's the correct code:
$(document).ready(function () {
    $("#vList").click(function () {
        if ($('#rv').prop('checked')) {
            fnloadrv(test);
        } else if ($('#dv').prop('checked')) {
            fnloaddv();
        }
    });
});

*

*$('#rv').prop('checked') return true or false based on the rv element checked status on vList button click.

A: Try this,
   $(document).ready(function () {
           $("#vList").click(function () {
                  if ($('#rv').is(':checked')) {
                      //fnloadrv(test);
                      alert('test1');
                  }
                  else if ($('#dv').is(':checked')) {
                    //  fnloaddv();
                       alert('test2');
                  }
             });

   });

Working Demo


text:
Q: Delete file(s) from git repository without deleting it from local filesystem of all local filesystem I have made a mistake. I added a file to a git repository which should be deleted.
Ok, this question was asked multiple times on SO. The solution is:
git rm (-r) --cached myfiletodelete

If I do this, the file is not deleted on MY local system. But, if colleagues do a PULL, the file is deleted on their system.
How can I avoid this? In other words, I want to delete the file only in 'origin', but not in any other local repository and then put it on gitignore.

A: It's not possible to have Git do this for you (short of setting up Git hooks on every machine—not a good solution here). git pull is getting the latest changes, and those changes include deleting that file. You'll have to instruct others to manually put the file back. You'd have to provide some way for others who are pulling for the first time to get it as well anyway, so just instruct them in the same manner.


text:
Q: Generating a random sequence using Scala I need to get a random sequence of 100 values from 10^-10 to 10^10 and storing to an Array using Scala. I tried following but it didn't work
Array(scala.math.pow(10,-10).doubleValue to scala.math.pow(10,10).intValue by scala.math.pow(10,5).toLong)

Can anyone help me to figure out how to do this correctly?

A: So you need to fill() the array with Random elements.
import scala.util.Random

val rndm = new Random(1911L)
Array.fill(100)(rndm.between(math.pow(10,-10), math.pow(10,10)))
//res0: Array[Double] = Array(6.08868427907728E9
// , 3.29548545155816E9
// , 9.52802903383275E9
// , 7.981295238889314E9
// , 1.9462480080050848E9
// . . .

This works because the 2nd parameter to the fill() method is "by-name", i.e. re-evaluated for every element.

UPDATE
Things aren't quite as clean if you don't have the .between() method (Scala 2.13).
Array.fill(100)(rndm.nextDouble())
     .map(_ * math.pow(10,10))

Note that this actually has a floor of 0.0 instead of the desired 0.0000000001. It's very unlikely you'd have an entry that's too small, especially when taking only 100 samples. Still, there are steps you could take to insure that can't happen.


text:
Q: Unable to use Callback assert with a form without data_class I'm creating a custom FormType called IntervalType. My IntervalType will have two fields, start and end and will be of type integer. This custom FormType will always be used without data_class.
I want to add a constraint to guarantee that start is lower than end.
How do I use the Symfony\Component\Validator\Constraints\Callback directly in a FormType without data_class?
Here is my IntervalType, just for reference:
// src/AppBundle/Form/Type/IntervalType.php
namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Validator\Constraints\NotBlank;

class TaskType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('start', IntegerType::class, array(
                'constraints' => array(
                    new NotBlank(),
                ),
            ))
            ->add('end', IntegerType::class, array(
                'constraints' => array(
                    new NotBlank(),
                ),
            ))
        );
    }
}

A: When the form won't be using any data_class the only option seems to be the Callback constraint.
namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

class IntervalType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('start', IntegerType::class, array(
                'constraints' => array(
                    new NotBlank(),
                ),
            ))
            ->add('end', IntegerType::class, array(
                'constraints' => array(
                    new NotBlank(),
                    new Callback(array($this, 'validateInterval')),
                ),
            ))
            ->add('submit', SubmitType::class);
    }

    public function validateInterval($value, ExecutionContextInterface $context)
    {
        $form = $context->getRoot();
        $data = $form->getData();

        if ($data['start'] >= $value) {
            $context
                ->buildViolation('The end value has to be higher than the start value')
                ->addViolation();
        }
    }
}


text:
Q: How to do string substitution in expect? Say I have the following variable s:
set s [lindex $argv 0]
How can I make sure s does not contain any "-" characters?
So, basically I want to replace all occurrences of "-" in s with "".
How can I achieve it?

A: Use set s [string map { - {} } [lindex $argv 0]]
As pynexj says, details can be found at http://www.tcl-lang.org/man/tcl/TclCmd/string.htm#M34


text:
Q: httpx python request to webpage wont redirect Currently making a request to a webpage which redirects a user to another URL (after a few seconds) but my httpx request doesn't follow this redirect, it just stops after it has made the request to the original URL. I am using the follow redirects kwarg, which statesd that it should be redirected, but this doesn't work. print(request) outputs none.
I'm unsure how I can fix this?
import httpx
client = httpx.Client(follow_redirects=True)
request = client.build_request("GET", "example...")
while request is not None:
    response = client.send(request)
    request = response.next_request
    print(request)


text:
Q: How to remove indent from list in table? I've table with list as mentioned below:
\begin{center}
\begin{tabular}{|p{2cm}|p{3cm}|p{3cm}|p{3cm}|p{3cm}|}
\hline
 \textbf{Attribute} & \textbf{P1} & \textbf{P2} & \textbf{P3} & \textbf{P4} \\
\hline
Definition&\noindent{\begin{itemize} \item Critical break-fix. \item Production down with no workaround. \item Multiple users impacted. \item Unavailability of Systems. \end{itemize}}&\noindent{\begin{itemize} \item Urgent break-fix. \item Production issue with workaround. \item Multiple users impacted. \item Multiple records impacted. \item Unavailability of system interfaces. \end{itemize}}&\noindent{\begin{itemize} \item Small Maintenance Issues. \item Non critical Bug Fix with workaround. \item No immediate impact. \item Single user/record impacted.  \end{itemize}}&\noindent{\begin{itemize} \item Small Maintenance Issues. \item Not a break-fix. \item A nice to have feature. \item 1- 7 person days of effort. \end{itemize}}\\
\hline
Response Time &3 Business Hours&5 Business Hours&1 Business Day&4 Business Days\\
\hline
Resolution Time &1 Business Day&2 Business Days&5 Business Days&As per mutual agreement\\
\hline
\end{tabular}
\end{center}

It's giving output as
How can I remove extra space before list items?

A: Here is a solution using the leftmargin option from the enumitem package.
\documentclass{article}

\usepackage{enumitem}
\begin{document}

\begin{table}
\centering
\begin{tabular}{|p{2cm}|p{3cm}|p{3cm}|p{3cm}|p{3cm}|}
\hline
\textbf{Attribute} & \textbf{P1} & \textbf{P2} & \textbf{P3} & \textbf{P4}\\
\hline
Definition&\noindent{\begin{itemize}[leftmargin=0.3cm] \item Critical break-fix. \item Production down with no workaround. \item Multiple users impacted. \item Unavailability of Systems. \end{itemize}}&\noindent{\begin{itemize}[leftmargin=0.3cm] \item Urgent break-fix. \item Production issue with workaround. \item Multiple users impacted. \item Multiple records impacted. \item Unavailability of system interfaces. \end{itemize}}&\noindent{\begin{itemize}[leftmargin=0.3cm] \item Small Maintenance Issues. \item Non critical Bug Fix with workaround. \item No immediate impact. \item Single user/record impacted.  \end{itemize}}&\noindent{\begin{itemize}[leftmargin=0.3cm] \item Small Maintenance Issues. \item Not a break-fix. \item A nice to have feature. \item 1- 7 person days of effort. \end{itemize}}\\
\hline
Response Time &3 Business Hours&5 Business Hours&1 Business Day&4 Business Days\\
\hline
Resolution Time &1 Business Day&2 Business Days&5 Business Days&As per mutual agreement\\
\hline
\end{tabular}
\end{table}

\end{document}

And here is the output:

EDIT Here are some improvements to get a better output (using Daleif suggestions)
\documentclass{article}

\usepackage{enumitem}
\usepackage{ragged2e}

\begin{document}

\begin{table}
\centering
\begin{tabular}{|p{2cm}|p{3cm}|p{3cm}|p{3cm}|p{3cm}|}
\hline
\textbf{Attribute}&\textbf{P1}&\textbf{P2}&\textbf{P3}&\textbf{P4}\\
\hline
Definition&\RaggedRight
\noindent{
\begin{itemize}[leftmargin=0.3cm]
\item Critical break-fix.
\item Production down with no workaround.
\item Multiple users impacted.
\item Unavailability of Systems.
\end{itemize}}&\RaggedRight
\noindent{
\begin{itemize}[leftmargin=0.3cm]
\item Urgent break-fix.
\item Production issue with workaround.
\item Multiple users impacted.
\item Multiple records impacted.
\item Unavailability of system interfaces.
\end{itemize}}&\RaggedRight
\noindent{
\begin{itemize}[leftmargin=0.3cm]
\item Small Maintenance Issues.
\item Non critical Bug Fix with workaround.
\item No immediate impact.
\item Single user/record impacted.
\end{itemize}}&\RaggedRight
\noindent{
\begin{itemize}[leftmargin=0.3cm]
\item Small Maintenance Issues.
\item Not a break-fix.
\item A nice to have feature.
\item 1- 7 person days of effort.
\end{itemize}}\\
\hline
Response Time &3 Business Hours&5 Business Hours&1 Business Day&4 Business Days\\
\hline
Resolution Time &1 Business Day&2 Business Days&5 Business Days&As per mutual agreement\\
\hline
\end{tabular}
\end{table}

\end{document}

And its output:


text:
Q: Stopping Code until AJAX call completes inside $.each loop I have a function that loads HTML from an external file via an AJAX call using jQuery.
These ajax call runs inside of a $.each loop and I need this ajax call to finish before the loop continues. Here is my code:
$('img').each(function(){
    var cotainer_html = $('.cotainer_html').clone();
    /* Get Image Content */
    $.ajax({
       url: '/assets/ajax/get_studio_image.php',
       type:'GET',
       success:function(data){
          cotainer_html.find('.replaceme').replaceWith(data);
       }
    });
});

I know I can set async:false but I hear that is not a good idea. Any ideas?

A: To achieve this you can put each request in to an array and apply() that array to $.when. Try this:
var requests = [];
$('img').each(function(){
    var cotainer_html = $('.cotainer_html').clone();
    /* Get Image Content */
    requests.push($.ajax({
       url: '/assets/ajax/get_studio_image.php',
       type:'GET',
       success:function(data){
          cotainer_html.find('.replaceme').replaceWith(data);
       }
    }));
});

$.when.apply($, requests).done(function() {
    console.log('all requests complete');
});

Note that you're replacing the same content on each request, so the only one which will have any effect on the UI is the last request. The preceding ones are redundant.
Also note that you should never, ever use async: false. It locks the UI thread of the browser until the request completes, which makes it look like it has crashed to the user. It is terrible practice. Use callbacks.

The OP appears to want the calls to run in series, not in parallel

If this is the case you could use recursion:
function makeRequest($els, index) {
    var cotainer_html = $('.cotainer_html').clone();
    $.ajax({
       url: '/assets/ajax/get_studio_image.php',
       type:'GET',
       success:function(data){
          cotainer_html.find('.replaceme').replaceWith(data);
          if ($els.eq(index + 1).length) {
              makeRequest($els, ++index);
          } else {
              console.log('all requests complete');
          }
       }
    });
}

makeRequest($('img'), 0);

A: You can use a pseudo-recursive loop:
var imgs = $('img').get();

var done = (function loop() {
    var img = imgs.shift();
    if (img) {
        var cotainer_html = $('.cotainer_html').clone();
        /* Get Image Content */
        return $.get('/assets/ajax/get_studio_image.php')
         .then(function(data) {
            cotainer_html.find('.replaceme').replaceWith(data);
        }).then(loop);
   } else {
       return $.Deferred().resolve();  // resolved when the loop terminates
   }
})();

This will take each element of the list, get the required image, and .then() start over until there's nothing left.
The immediately invoked function expression itself returns a Promise, so you can chain a .then() call to that that'll be invoked once the loop has completed:
done.then(function() {
    // continue your execution here
    ...
});


text:
Q: TypeError when fitting keras model I am a new to tensorflow, I am trying to build a simple neural network. But every time I get close, there are a list of errors stopping me. I followed tutorials and documentations and kept most of the code and changed only things I need to.
Here is my code:
###
# Import
###

import tensorflow as tf
import pandas as pd
from tensorflow import keras

###
# Loading Data
###

# Training Data

# path of the training data
train_data_path = "C:/Users/User/Desktop/Machine_Learning/Neural_Network/addition_train_data.csv"
train_data = pd.read_csv(train_data_path)  # loads the data using pandas

# Evalution Data

# path of the evalution data
eval_data_path = "C:/Users/User/Desktop/Machine_Learning/Neural_Network/addition_eval_data.csv"
eval_data = pd.read_csv(eval_data_path)  # loads the data using pandas (again)

# Target Columns
train_target = train_data.pop("Sum")
eval_target = eval_data.pop("Sum")

###
# Creating the Model
###

model = keras.Sequential()
model.add(keras.layers.Flatten(input_shape=(35, 2)))
model.add(keras.layers.Lambda(
    lambda x: tf.expand_dims(model.output, axis=-1)))
model.add(keras.layers.Dense(10, activation="tanh"))
model.add(keras.layers.Dense(1, activation="tanh"))

###
# Compiling the Model
###

model.compile(
    optimizer='adam',
    loss='mean_absolute_error',
    metrics=['accuracy']
)

###
# Training the Model
###

model.fit(
    eval_data, eval_target, epochs=10
)

Console Output:
2020-05-25 10:53:35.491127: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not
load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-05-25 10:53:35.493137: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart
dlerror if you do not have a GPU set up on your machine.
2020-05-25 10:53:37.162913: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully
opened dynamic library nvcuda.dll
2020-05-25 10:53:37.194951: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1561] Found device 0 with
properties:
pciBusID: 0000:01:00.0 name: GeForce RTX 2060 computeCapability: 7.5
coreClock: 1.755GHz coreCount: 30 deviceMemorySize: 6.00GiB deviceMemoryBandwidth: 312.97GiB/s
2020-05-25 10:53:37.200604: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not
load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-05-25 10:53:37.206365: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully
opened dynamic library cublas64_10.dll
2020-05-25 10:53:37.212086: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully
opened dynamic library cufft64_10.dll
2020-05-25 10:53:37.214531: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully
opened dynamic library curand64_10.dll
2020-05-25 10:53:37.219340: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully
opened dynamic library cusolver64_10.dll
2020-05-25 10:53:37.224932: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully
opened dynamic library cusparse64_10.dll
2020-05-25 10:53:37.233220: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully
opened dynamic library cudnn64_7.dll
2020-05-25 10:53:37.235711: W tensorflow/core/common_runtime/gpu/gpu_device.cc:1598] Cannot dlopen some
GPU libraries. Please make sure the missing libraries mentioned above are installed properly if you would
like to use GPU. Follow the guide at https://www.tensorflow.org/install/gpu for how to download and setup
the required libraries for your platform.
Skipping registering GPU devices...
2020-05-25 10:53:37.241553: I tensorflow/core/platform/cpu_feature_guard.cc:143] Your CPU supports
instructions that this TensorFlow binary was not compiled to use: AVX2
2020-05-25 10:53:37.249295: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x1d9e0a5c5f0
initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-05-25 10:53:37.252889: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device
(0): Host, Default Version
2020-05-25 10:53:37.255179: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1102] Device interconnect
StreamExecutor with strength 1 edge matrix:
2020-05-25 10:53:37.258151: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1108]
Epoch 1/10
WARNING:tensorflow:Model was constructed with shape (None, 35, 2) for input Tensor("flatten_input:0",
shape=(None, 35, 2), dtype=float32), but it was called on an input with incompatible shape (None, 2).
WARNING:tensorflow:Model was constructed with shape (None, 35, 2) for input Tensor("flatten_input:0",
shape=(None, 35, 2), dtype=float32), but it was called on an input with incompatible shape (None, 2).
Traceback (most recent call last):
File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\execute.py", line 60, in
quick_execute
inputs, attrs, num_outputs)
TypeError: An op outside of the function building code is being passed
a "Graph" tensor. It is possible to have Graph tensors
leak out of the function building context by including a
tf.init_scope in your function building code.
For example, the following function will fail:
@tf.function
def has_init_scope():
my_constant = tf.constant(1.)
with tf.init_scope():
added = my_constant * 2
The graph tensor has name: dense_1/Identity:0
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "addition.py", line 58, in <module>
eval_data, eval_target, epochs=10
File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py", line 66, in
_method_wrapper
return method(self, *args, **kwargs)
File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py", line 848, in
fit
tmp_logs = train_function(iterator)
File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py", line 580, in
__call__
result = self._call(*args, **kwds)
File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py", line 644, in
_call
return self._stateless_fn(*args, **kwds)
File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 2420, in
__call__
return graph_function._filtered_call(args, kwargs)  # pylint: disable=protected-access
File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 1665, in
_filtered_call
self.captured_inputs)
File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 1746, in
_call_flat
ctx, args, cancellation_manager=cancellation_manager))
File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 598, in call
ctx=ctx)
File "C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\eager\execute.py", line 74, in
quick_execute
"tensors, but found {}".format(keras_symbolic_tensors))
tensorflow.python.eager.core._SymbolicException: Inputs to eager execution function cannot be Keras
symbolic tensors, but found [<tf.Tensor 'dense_1/Identity:0' shape=(None, 70, 1) dtype=float32>]

Any help, tips, and advice is greatly appreciated.

A: I think the issue is with the Lambda layer that was taking model.ouput.
based on your eval_data and eval_target, I updated the model. So, please check the following model.
model = tf.keras.Sequential()
# model.add(tf.keras.layers.Flatten(input_shape=(2,)))
# model.add(tf.keras.layers.Lambda(lambda x: tf.expand_dims(model.output, axis=-1)))
model.add(tf.keras.layers.Dense(10, activation="tanh",input_shape=(2,)))
model.add(tf.keras.layers.Dense(1, activation="tanh"))
model.summary()

Model: "sequential_2"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
dense_4 (Dense)              (None, 10)                30
_________________________________________________________________
dense_5 (Dense)              (None, 1)                 11
=================================================================
Total params: 41
Trainable params: 41
Non-trainable params: 0
_________________________________________________________________


text:
Q: pytube3" is not accessed Pylance I can't Import pytube3 library, although I can import the pytube.
although everything is in the right place, Pytube3 is installed, and it's in the right path, whene I check the pip file in the system it is there, whene I check the installation through cmd,
Requirement already satisfied: pytube3 in c:\users\kasba\appdata\local\programs\python\python311\lib\site-packages (9.6.4)
Requirement already satisfied: typing-extensions in c:\users\kasba\appdata\local\programs\python\python311\lib\site-packages (from pytube3) (4.4.0)

Everything is perfect I think, but still I can't import it.
When I try to Import it by "Import pytube3"
I get this "pytube3" is not accessed Pylance"

A: Importing pytube is sufficient. Pytube3 might have the 3 because it's for python3 specifically.
https://pypi.org/project/pytube3/
(See the documentation on their pip site. they just import pytube and not pytube3)
 >>> from pytube import YouTube
 >>> YouTube('https://youtu.be/9bZkp7q19f0').streams.get_highest_resolution().download()
 >>>
 >>> yt = YouTube('http://youtube.com/watch?v=9bZkp7q19f0')
 >>> yt.streams
  ... .filter(progressive=True, file_extension='mp4')
  ... .order_by('resolution')[-1]
  ... .download()

That's the documentation on the pytube3 site.


text:
Q: How to use constant/variable in a SQL Server CE 4 script? I have this script:
DELETE FROM [Tags] WHERE Id = CONVERT(uniqueidentifier, '7373D1A0-CB6A-4207-87C4-AE2939FD20C0');
GO
INSERT INTO [Tags] VALUES (CONVERT(uniqueidentifier, '7373D1A0-CB6A-4207-87C4-AE2939FD20C0'), 'Business');
GO

I want to declare a @businessId constant to hold the result from my
CONVERT(uniqueidentifier, '7373D1A0-CB6A-4207-87C4-AE2939FD20C0')

The end result should look cleaner:
DELETE FROM [Tags] WHERE Id = @businessId;
GO
INSERT INTO [Tags] VALUES (@businessId, 'Business');
GO

Is there a way to do this in SQL Server CE 4?
If no, is there a way to do this in SQL Server?
Thank you for your help.

A: In T-SQL (SQL Server) you would write
Declare @businessId UniqueIdentifier;
set @businessId = '7373D1A0-CB6A-4207-87C4-AE2939FD20C0';

I would imagine that it is the same in SQL Server CE but I will confirm it;


text:
Q: Audio is not playing in html I have music stored in a separate folder that I am trying to play, however the music won't play. Any idea why? All help is appreciated and thanks in advance. Also trying to do the same thing in Jade so if you guys tell me the code for that, it would be great too!

        <audio controls>
            <source src="./songs/Remember-The-Name.mp3" type="audio/mp3">
         </audio>

Path to html file :

/User/Desktop/music-app/views/test.html

Path to audio file:

/User/Desktop/music-app/songs/Remember-The-Name.mp3

A: Try this.. It works..
Add .. to goto previous directory and use type="audio/mpeg"

        <audio controls>
            <source src="../songs/Remember-The-Name.mp3" type="audio/mpeg">
         </audio>

A: You can dynamically generate an audio player, I believe your problem is getting the correct path to your mp3. Use this code and change the src value on line 6.
When in doubt, use the absolute path or in your case a relative path of ../songs/Remember-The-Name.mp3

var audio = document.createElement('audio');
var source = document.createElement('source');
var media = document.getElementById('media');
media.appendChild(audio);
audio.appendChild(source);
source.setAttribute('src', 'https://glpro.s3.amazonaws.com/_util/smpte/111.mp3');
source.setAttribute('type', 'audio/mpeg');
audio.setAttribute('controls', 'controls');

A: Make sure you link your audio correctly.
That is what helped me.


text:
Q: Present continuous vs Present perfect continuous
*

*I am waiting for you for almost an hour

*I have been waiting for you for almost an hour

What's the difference? Are both OK?

A: The first uses the imperfect progressive tense, which expresses an ongoing present action; it is used to answer the question, what is happening now? "I am singing"; "I am waiting"; "I am going." The second is the perfect progressive tense, which expresses an action that began in the past and which has continued to the present moment; it is used to answer the question, what has been happening? or What have you been doing? This is the one you want to use: "I have been singing for some time now"; "I have been waiting for you for almost an hour"; "I have been going there for three weeks." It's true that both of these tenses describe an ongoing action (they are both in the present tense), but only the perfect progressive is used to indicate that the action in question has a history. ("Imperfect" in this sense means continuing, not complete; "perfect" means complete. When you tell someone that you have been waiting for an hour, you are saying that, up until the moment you utter this sentence, you have waited an hour; this a completed action--which does not mean you won't continue waiting, but, if you do continue waiting, it will no longer be true that you have waited only an hour.)


text:
Q: Barchart with pgfplot in beamer slides I am trying to use a code in my beamer presentation for a barchart that I had previously used for an article type document. I am using TeXstudio as the editor. Everytime I try to compile, the application freezes. Seems to be a problem with pgfplotsstableread, however am not sure what it is.
I need to get the same chart on the presentation as well.
Here is the code:
\usepackage{pgfplots, pgfplotstable}

\usetikzlibrary{backgrounds}
% background color definition from pgfmanual-en-macros.tex
\definecolor{graphicbackground}{cmyk}{0.04,0.02,0.02,0.04}
% key to change color
\pgfkeys{/tikz/.cd,
    background color/.initial=graphicbackground,
    background color/.get=\backcol,
    background color/.store in=\backcol,
}
\tikzset{background rectangle/.style={
        fill=\backcol,
    },
    use background/.style={
        show background rectangle
    }
}

    \begin{center}

        % grid style
        %\pgfplotsset{grid style={solid, ultra thin,gray}}
        %\pgfplotsset{minor grid style={dashed,gray}}
        %\pgfplotsset{major grid style={dotted,green!50!black}}

        \begin{tikzpicture}[use background]

        \pgfplotstableread{ % Read the data into a table macro
            Label                                                      First   Second
            {\small \textbf{HTML Design}}                                5     15
            {\small \textbf{UI \/ UX PSD files}}                         2     7
            {\small \textbf{Wireframes}}                                 0     3
        }\datatable

        \begin{axis}[
        xbar stacked,   % Stacked horizontal bars
        xmin=0,  xmax=15,       % Start x axis at 0
        title={\large \textbf {Gantt Chart }},
        height=9cm, width=12cm,
        bar width=0.8cm,
        axis x line*=bottom,
        axis y line*=left,
        y axis line style={opacity=1},
        enlarge y limits=true,
        xmajorgrids={true},
        grid style={
            solid,
            ultra thin,
            gray
        },
        tick style={tickwidth=0cm,major tick length=0cm},
        xlabel={\textbf{No of Sprints }},
        xtick ={5,10,15},
                %xminorgrids={true},
                %grid style={
                            %dashed,
                        %   ultra thin,
                        %   gray
            %   },
        %minor xtick ={1,3,5,7,9,11,13,15},
        %grid =both,
        ytick=data,     % Use as many tick labels as y coordinates
        yticklabels from table={\datatable}{Label}  % Get the labels from the Label column of the \datatable
        ]
        \addplot [draw=none,fill=none] table [x=First, y expr=\coordindex] {\datatable};    % Plot the "First" column against the data index
        \addplot [draw=none,fill=levelfirst]table [x=Second, y expr=\coordindex] {\datatable};

        \end{axis}

        \end{tikzpicture}

        \end{center}

A: Use a line end marker like row sep=\\. And it is not a good idea to include formatting details inside a data table. Use it inside the axis options.
\pgfplotstableread[row sep=\\]{ % Read the data into a table macro
             Label                                      First   Second\\
            {HTML Design}                                5     15\\
            {UI \/ UX PSD files}                         2     7\\
            {Wireframes}                                 0     3\\
        }\datatable

and
yticklabel style={font=\small\bfseries},

The code:
\documentclass{beamer}
\usepackage{pgfplotstable}

\usetikzlibrary{backgrounds}
% background color definition from pgfmanual-en-macros.tex
\definecolor{graphicbackground}{cmyk}{0.04,0.02,0.02,0.04}
% key to change color
\pgfkeys{/tikz/.cd,
    background color/.initial=graphicbackground,
    background color/.get=\backcol,
    background color/.store in=\backcol,
}
\tikzset{background rectangle/.style={
        fill=\backcol,
    },
    use background/.style={
        show background rectangle
    }
}

\begin{document}

\begin{frame}

        % grid style
        %\pgfplotsset{grid style={solid, ultra thin,gray}}
        %\pgfplotsset{minor grid style={dashed,gray}}
        %\pgfplotsset{major grid style={dotted,green!50!black}}
\begin{centering}
        \begin{tikzpicture}[use background]

        \pgfplotstableread[row sep=\\]{ % Read the data into a table macro
             Label                                      First   Second\\
            {HTML Design}                                5     15\\
            {UI \/ UX PSD files}                         2     7\\
            {Wireframes}                                 0     3\\
        }\datatable

        \begin{axis}[
        xbar stacked,   % Stacked horizontal bars
        xmin=0,  xmax=15,       % Start x axis at 0
        title={\large \textbf {Gantt Chart }},
        height=7cm, width=8cm,
        bar width=0.8cm,
        axis x line*=bottom,
        axis y line*=left,
        y axis line style={opacity=1},
        enlarge y limits=true,
        xmajorgrids={true},
        grid style={
            solid,
            ultra thin,
            gray
        },
        tick style={tickwidth=0cm,major tick length=0cm},
        xlabel={\textbf{No of Sprints }},
        xtick ={5,10,15},
                %xminorgrids={true},
                %grid style={
                            %dashed,
                        %   ultra thin,
                        %   gray
            %   },
        %minor xtick ={1,3,5,7,9,11,13,15},
        %grid =both,
        yticklabel style={font=\small\bfseries},
        ytick=data,     % Use as many tick labels as y coordinates
        yticklabels from table={\datatable}{Label}  % Get the labels from the Label column of the \datatable
        ]
        \addplot [draw=none,fill=blue] table [x=First, y expr=\coordindex] {\datatable};    % Plot the "First" column against the data index
        \addplot [draw=none,fill=red]table [x=Second, y expr=\coordindex] {\datatable};

        \end{axis}

        \end{tikzpicture}

\end{centering}
        \end{frame}
\end{document}

Other minor things include the adjustment of width and height and the fill color, which, I have changed.
Similarly for title and xlabel, you may change the formatting like:
    title={Gantt Chart},
    title style={font=\large\bfseries},

and
    xlabel={No of Sprints},
    xlabel style={font=\bfseries},


text:
Q: 3D identity matrix to correctly set vertices Im playing around with matrices, with a view to doing 3D transformation in GDI (for the fun of it). At the moment i'm checking that im getting the right values from identity matrix given a representation of four vertices arranged in a square. I've been scratching my head as to why it's not giving expected output. I have done my research but can't see what i am doing wrong here.
Here's my definition of matrix.
typedef struct m{
    float _m01, _m05, _m09, _m13;
    float _m02, _m06, _m10, _m14;
    float _m03, _m07, _m11, _m15;
    float _m04, _m08, _m12, _m16;
}mat;

struct m matIdentity(struct m *m1){
   m1->_m01 = 1.0; m1->_m05 = 0.0; m1->_m09 = 0.0; m1->_m13 = 0.0;
   m1->_m02 = 0.0; m1->_m06 = 1.0; m1->_m10 = 0.0; m1->_m14 = 0.0;
   m1->_m03 = 0.0; m1->_m07 = 0.0; m1->_m11 = 1.0; m1->_m15 = 0.0;
   m1->_m04 = 0.0; m1->_m08 = 0.0; m1->_m12 = 0.0; m1->_m16 = 1.0;
}

Here's making use of matrix with
 struct m matrix;
 matIdentity(&matrix);

//represent 4 vertices(x,y,z,w);

float square[4][4] = {
        {0.0, 0.0, 0.0, 1.0},
        {0.0, 20.0, 0.0, 1.0},
        {20.0, 20.0, 0.0, 1.0},
        {20.0, 0.0, 0.0, 1.0}
    };

           float result[4][4];

           int i = 0;
           for(i = 0; i < 4; i++){
           result[i][1] = (matrix._m01 * square[i][0]) + (matrix._m05 * square[i][1]) +    (matrix._m09 * square[i][2]) + (matrix._m13 * square[i][3]);
           result[i][2] = (matrix._m02 * square[i][0]) + (matrix._m06 * square[i][1]) + (matrix._m10 * square[i][2]) + (matrix._m14 * square[i][3]);
           result[i][3] = (matrix._m03 * square[i][0]) + (matrix._m07 * square[i][1]) + (matrix._m11 * square[i][2]) + (matrix._m15 * square[i][3]);
           result[i][4] = (matrix._m04 * square[i][0]) + (matrix._m08 * square[i][1]) + (matrix._m12 * square[i][2]) + (matrix._m16 * square[i][3]);
           }

 char strOutput[500];
           sprintf(strOutput,"%f %f %f %f\n %f %f %f %f\n %f %f %f %f\n %f %f %f %f\n ",
           result[0][0], result[0][1], result[0][2], result[0][3],
           result[1][0], result[1][1], result[1][2], result[1][3],
           result[2][0], result[2][1], result[2][2], result[2][3],
           result[3][0], result[3][1], result[3][2], result[3][3]
           );

I have a feeling the problem is somewhere to do with multiplying a row based representation of vertices using a column major matrix. Can anyone please suggest how i should be doing this.

A: *

*I don't understand why you don't use array first, then start to use array and iteration, and in the end give up iteration. Please, such program can only cause confusion.

*The correct formula is C(i, j)=sigma(A(i, k)*B(k, j), k=1..n), where C=AB and n is 4 for your case.
(e.g., this line should be like: result[i][0] = (matrix._m01 * square[0][i]) + (matrix._m02 * square[1][i]) + (matrix._m03 * square[2][i]) + (matrix._m04 * square[3][i]); )Write a simple nested for-iteration to calculate this...

*This is not for one vector, but n vectors....

A: This is not matrix multiplication. Multiplying a vector by a matrix goes like this:
float mat[4][4];
float vec_in[4];
float vec_out[4];
// todo: initialize values
for (int j = 0; j < 4; ++j)
{
    vec_out[j] = 0.0f;
    for (int i = 0; i < 4; ++i)
    {
        vec_out[j] += vec_in[i] * mat[i][j];
    }
}


text:
Q: Split Character String at Underscore Using scan() Function in R - strsplit() vs. scan() Comparison I've noticed that the functions strsplit() and scan() handle underscores differently, and I'm wondering why this is the case.
Please consider the following example code:
x1 <- "string split"

strsplit(x1, " ")[[1]]
# [1] "string" "split"

scan(text = x1, what = " ")
# [1] "string" "split"

The outputs of strsplit and scan are the same when using " " as a separator.
However, when I use "_" as a separator, the output is different:
x2 <- "string_split"

strsplit(x2, "_")[[1]]
# [1] "string" "split"

scan(text = x2, what = "_")
# [1] "string_split"

Why is the output of strsplit and scan different when using underscores as a separator?

A: the argument what is not the separator but rather the data type. IN your case, you have character:
scan(text=x2, what = character(), sep='_', quiet = TRUE)
[1] "string" "split"


text:
Q: Can I get some clarity on ReleaseComObject? Can I ignore it? I have been developing office solutions in VBA for a while now and have fairly complete knowledge regarding office development in VBA. I have decided it is time to learn some real programming with .Net and am having some teething problems.
Having looked through a bunch of articles and forums (here and elsewhere), there seems to be some mixed information regarding memory management in .Net when using COM objects.
Some people say I should always deterministically release COM objects and others say I should almost never do it.
People saying I should do it:
The book 'Professional Excel Development' on page 861.
This stack exchange question has been answered by saying "every reference you make to a COM object must be released. If you don't, the process will stay in memory"
This blog suggests using it solved his problems.
People saying I should not do it:
This MSDN blog by Eric Carter states "In VSTO scenarios, you typically don't ever have to use ReleaseCOMObject."
The book 'VSTO for Office 2007' which is co-authored by Eric Carter seems to make no mention whatsoever of memory management or ReleaseComObject.
This MSDN blog by Paul Harrington says don't do it.
Someone with mixed advice:
Jake Ginnivan says I should always do it on COM objects that do not leave the method scope. If a COM object leaves the method scope then forget about it. Why can't I just forget about it all the time then?
The blog by Paul Harrington seems to suggest that the advice from MS has changed sometime in the past. Is it the case that calling ReleaseCOMObject used to be best practice but is not anymore? Can I leave the finer details of memory management to MS and assume that everything will be mostly fine?

A: I try to adhere to the following rule in my interop development regarding ReleaseComObject.
If my managed object implements some kind of shutdown protocol similar to IDisposable, I call ReleaseComObject on any child COM objects I hold references to. Some examples of the shutdown protocols I'm talking about:

*

*IObjectWithSite.SetSite(null)

*IOleObject.SetClientSite(null)

*IOleObject.Close()

*IDTExtensibility2.OnDisconnection

*IDTExtensibility2.OnBeginShutdown

*IDisposable.Dispose itself
This helps breaking potential circular references between .NET and native COM objects, so the managed garbage collector can do its job unobstructively.
Perhaps, there's something similar which can be used in your VSTO interop scenario (AFAIR, IDTExtensibility2 is relevant there).
If the interop scenario involves IPC COM calls (e.g., when you pass a managed event sink object to an out-of-proc COM server like Excel), there's another option to track external references to the managed object: IExternalConnection interface. IExternalConnection::AddConnection/ReleaseConnection are very similar to IUnknown::AddRef/Release, but they get called when a reference is added from another COM appartment (including apartments residing in separate processes).
IExternalConnection provides a way to implement an almost universal shutdown mechanism for out-of-proc scenarios. When the external reference count reaches zero, you should call ReleaseComObject on any external Excel objects you may be holding references to, effectively breaking any potential circular COM references between your process and Excel process. Perhaps, something like this has already been implemented by VSTO runtime (I don't have much experience with VSTO).
That said, if there is no clear shutdown mechanism, I don't call ReleaseComObject. Also, I never use FinalReleaseComObject.

A: You should not ignore it, if you are working with the Office GUI! Like your second link states:

Every reference you make to a COM object must be released. If you don't, the process will stay in memory.

This means, that your objects will remain in memory if you do not explicitly release them. Since they are COM objects, the garbage collector is responsible for releasing them. However, Excel and the other fancy tools are implemented with no knowledge of the garbage collector in .NET. They relate on deterministic release of memory. If you are requesting an object from excel and do not properly release it, it might be that your application does not close correctly, because it wait's until your resources are released. If your objects live long enought to get into gen1 or gen2, then this can take hours or even days!
All considerations about not releasing COM objects are targeting multithreaded scenarios or scenarios where you are forced to push around many com objects over multiple instances. As a good advice, allways create your com objects as late as possible and release them as soon as possible in the opposite order than created. Also you should think about keeping your interop instances private wherever possible. This reduces the possibility that other threads or instances are accessing the object while you have already released it.


text:
Q: Visual Studio Build in Azure DevOps pipeline errors on Microsoft.NET.Sdk.CrossTargeting.targets I am in the early stages of migrating my codebase from .NET Framework to .NET Standard.  I am converting some of the foundational projects in my solution to SDK Project types with target frameworks of net462 and netstandard2.0.
All of my applications and services are still .NET Framework.
To clarify, I have a library project targeting both frameworks, and then other library projects (.NET Framework only) that have the multi-target project as a reference, and then applications (.NET Framework only) that reference all of the above.
When I compile my solution in Visual Studio 2019, it compiles just fine.  If I do a manual publish, that also works just fine.  However, when I try to do a PR into Azure DevOps, my CI build pipeline errors with this error:
[error]C:\Program Files\dotnet\sdk\3.0.100\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Sdk.CrossTargeting.targets(27,5): Error : The 'Publish' target is not supported without specifying a target framework. The current project targets multiple frameworks, please specify the framework for the published application.
Google suggests that, if I were using dotnet -publish, I would need to provide a framework parameter.  However the VSBuild task doesn't seem to support that.
The relevant YAML for my pipeline is:
steps:
- task: VSBuild@1
  displayName: 'Check for Build Errors'
  inputs:
    solution: '$(SolutionName)'
    msbuildArgs: '/target:publish'
    platform: '$(BuildPlatform)'
    configuration: '$(BuildConfiguration)'
    maximumCpuCount: true

And ideas or clarifying questions?

A: Does specifying the MSBuild argument for the target framework in the msbuildArgs give you the results you're looking for?
    msbuildArgs: '/target:publish /p:TargetFramework=net462'

The reference for the dotnet msbuild command indicates the same MSBuild args are supported, and directs you (in a roundabout way ) here, where you can see the monikers used for the different target frameworks.


text:
Q: Finding all possible $n\times n$ matrices with non-negative entries and given row and column sums. What I am ultimately attempting to do is find the solution that maximizes a given equation so I need to find all possible solutions so I can check them. I need all possible solutions to an $n \times n$ matrix, given the row and column totals. All values must be non-negative. Other than that the row and sum columns are the only constraints.

A: It might be interesting to mention the RSK correspondence (although it might not be of sufficient help if $n$ is really very large). It gives an algorithmic bijection between the set of non-negative integer matrices with column and rows sums $\alpha,\beta$ respectively (these are vectors of non-negative integers) and pairs $(P,Q)$ of equal shape semistandard Young tableaux of respective weights $\alpha,\beta$. Therefore the number of matrices is given by
$$
  \sum_\lambda K_{\lambda,\alpha}K_{\lambda,\beta}
$$
where $\lambda$ is a partition of $\sum\alpha=\sum\beta$, and $K_{\lambda,\alpha}$ is the number of semistandard Young tableaux of shape $\lambda$ and weight $\alpha$, which is a Kostka number. This at least gives a method to count the number of matrices that is much more efficient than enumerating them all (because of the product in the formula and the fact that the $K_{\lambda,\alpha}$ are non-negative). There are no really simple formulas for computing Kostka numbers, but since they are weight multiplicities, there is a recursive formula that computes them again much more efficiently than by counting
semistandard Young tableaux.

A: In principle there is an "efficient" recursive procedure for generating all the possible non-negative integer $n \times n$ matrices with prescribed row and column sums (contingency tables), but we should be forewarned that the number of such solutions may be both enormous and difficult to estimate with precision.
The simpler (but still voluminous) generation of $2 \times n$ contingency tables is the subject of this earlier Question, and a more general problem with (essentially) $m \times k$ matrices was discussed here, including an informally stated recursive generating procedure.
Often authors contemplate the problem of randomly selecting solutions with uniform probability, but here the stated goal is an exhaustive search/brute-force determination of a maximized objective function.  If more were known about the structure of that objective function, likely some practical shortcuts could be found (e.g. exploiting symmetries of the search space).

The Question asks us to generate all possible matrices with prescribed row and column sums.  Counting them need not concern us directly.  Any algorithm that avoids duplication or unnecessary trial-and-error is "efficient".  Below we present Prolog code implementing such an algorithm, predicate contingencyTable/3, taking as input two lists, of row sums and column sums respectively, and producing on backtracking all possible non-negative integer matrices satisfying those constraints.
balanceCondition/2 Check that totals of row sums and column sums agree, a necessary and sufficient condition for solutions to exist.
generateTable/3 Select non-negative entries for the first row (see generateRow) to match its row sum and reduce the respective column sums (but not to less than zero). The "balance condition" is preserved, so the procedure can recursively fill the next row. When one row is left, selection there is unique, and at that point the sum of the last reduced column sums equals the last row sum.
generateRow/4 Entries for one row can also be selected recursively.  The first entry in a row will have two lower bounds and two upper bounds.  While one lower bound is trivial (non-negativity), the other is more subtle: assign enough that later column sums do not limit the row sum from being attained.  Both upper bounds are obvious; the entry cannot exceed the row sum or the column sum when the entry is selected.  Once an entry within the allowable bounds is chosen, reduce the row sum accordingly and apply the same procedure to the rest of the row.  The last row entry is uniquely determined.
/*
   Generate 2-way contingency tables with specified margins,
   non-negative matrices with prescribed row & column sums.
*/

/* contingencyTable(+RowSums,+ColSums,?Table) */
contingencyTable(RowSums,ColSums,Table) :-
    balanceCondition(RowSums,ColSums),       /* feasible? */
    generateTable(RowSums,ColSums,Table).

balanceCondition(RowSums,ColSums) :-
    sum(RowSums,0,Total),
    sum(ColSums,0,Total).

generateTable([_],ColSums,[ColSums]) :- !.
generateTable([RowSum|RowSums],ColSums,[Row|Rows]) :-
    generateRow(RowSum,ColSums,ReducedColSums,Row),
    generateTable(RowSums,ReducedColSums,Rows).

generateRow(RowSum,[ColSum],[ColRed],[RowSum]) :-
    !,
    ColRed is ColSum - RowSum.
generateRow(RowSum,[ColSum|ColSums],[ColRed|ColReds],[R|Rs]) :-
    sum(ColSums,0,Sum),
    (Sum > RowSum -> RMin = 0 ; RMin is RowSum - Sum),
    (ColSum > RowSum -> RMax = RowSum ; RMax = ColSum),
    between(RMin,RMax,R),
    RowRed is RowSum - R,
    ColRed is ColSum - R,
    generateRow(RowRed,ColSums,ColReds,Rs).

/* helper predicates sum/3 and between/3 */
sum([ ],Sum,Sum).
sum([H|T],Start,Total) :-
    SoFar is Start + H,
    sum(T,SoFar,Total).

/* argument order compatible with SWI-Prolog builtin */
between(X,Z,X) :- X =< Z.
between(X,Z,_) :- X > Z, !, fail.
between(X,Z,K) :-
    Y is X+1,
    between(Y,Z,K).


text:
Q: How to use assert in OCaml? I am trying to learn OCaml and I am having trouble with the assertion statement. In the interpreter I can use it:
Zameers-MacBook-Air:~ zmanji$ ocaml
        OCaml version 4.01.0

# let x = 1;;
val x : int = 1
# assert(x > 2);;
Exception: Assert_failure ("//toplevel//", 1, 0).
# ^D

However when I put the code in a file that looks like this:
let x = 1
assert(x > 2)

I get the following error:
Zameers-MacBook-Air:Q4 zmanji$ ocaml test.ml
File "test.ml", line 2, characters 0-6:
Error: Syntax error

What am I doing wrong?

A: If you put the ;; in the file it will work. Without that, it doesn't make sense syntactically. An expression 1 followed by the keyword assert doesn't make sense.
I don't particularly like using ;; in actual code (not at top-level, i.e., the interpreter). If you wanted to avoid it too, you could write
let x = 1
let () = assert (x > 2)


text:
Q: Apache Flink: Watermark does not progress with Broadcast stream There is 1 high throughput Kafka stream defined as follows
val stream: DataStream[A] = flinkEnv
  .addSource(kafkaStreamSource)
  .assignTimestampsAndWatermarks(
     WatermarkStrategy
        .forBoundedOutOfOrderness[A](Duration.ofSeconds(0))
        .withIdleness(Duration.ofSeconds(5))
        .withTimestampAssigner(new SerializableTimestampAssigner[A] {
            override def extractTimestamp(element: A, recordTimestamp: Long): Long = {
                element.lastUpdatedAt
              }
            }
        )
  )
  .window(TumblingEventTimeWindows.of(Time.minutes(1)))
  .reduce(.......)

The watermark for the above window operator forwards properly.
The DataStream[A] from the above window operator need to be enriched with some info kept in some S3 files. The S3 files updates very rarely.
S3 file is read as a stream and then broadcasted to enrich the elements from DataStream[A].
 val textInputFormat = new TextInputFormat(new Path("s3 path...."))
 val enrichWithElements: BroadcastStream[EnrichWithElement] = flinkEnv.readFile(textInputFormat, "s3 path ...", FileProcessingMode.PROCESS_CONTINUOUSLY, 30)
    .map(s3Element => {
      EnrichWithElement(.....)
    })
    .broadcast(new MapStateDescriptor......)

The 2 streams are then connected to enrich all elements of type A with elements of type EnrichWithElement.
class EnrichedAProcess
    extends BroadcastProcessFunction[A,EnrichWithElement,EnrichedAElement] {
  override def processElement(
      value: A,
      ctx: Context,
      out: Collector[EnrichedAElement]): Unit = {
      .....
      out.collect(EnrichedAElement(....))
  }

  override def processBroadcastElement(
      value: EnrichWithElement,
      ctx: Context,
      out: Collector[EnrichedAElement]): Unit = {
      .........
  }
}
stream
  .connect(enrichWithElements)
  .process(new EnrichedAProcess)

The EnrichedAProcess has 2 inputs. One of them is constantly forwarding the watermark but the broadcasted stream does not have any time info or the watermark. This leads to the EnrichedAProcess's watermark not forwarding at all since one of its inputs is not passing in the watermark.
Is there a way to specify that EnrichedAProcess's watermark be only dependent on non broadcasted input.

A: An operator with multiple input channels sets its own watermark to the minimum of the latest watermarks received from all active channels.
What you can do is to apply a WatermarkStrategy to the broadcast stream that always returns MAX_WATERMARK as its watermark. (You don't need to worry about assigning timestamps for that stream.)


text:
Q: Set user setting value with another user setting value If I create user setting variables called var1 and var2, is it possible to put the value of var2 inside of var1?
For exemple:

Properties.Settings.Default.var2 = "stackoverflow";
Properties.Settings.Default.var1; // //path/stackoverflow/morepath
Properties.Settings.Default.var2 = "test";
Properties.Settings.Default.var1; // //path/test/morepath

A: Settings is essentially just an XML file, so there is no way you can dynamically inject a variable value into an entry.
However, you can achieve what you want at runtime by dynamically updating var1 based on var2's value using the Properties.Settings.Default.Properties object.
Here is an article that has some examples of dynamically updating entries:
https://codedocu.com/Net-Framework/WPF/Basics/Settings/WPF_colon_-Create,-write-and-read-settings-dynamically?2045
Properties.Settings.Default.Properties["var2"].DefaultValue  = "your updated value goes here"

A: The short answer to your question is no.
A string is just a string and there is no piece of built-in functionality that will dynamically replace %var2% in your first variable with the actual value of the second or any other variable.
If you want to somehow change the values of the variables, you will have to write some code that does this for you.


text:
Q: How to append byte to byte array in golang? Not byte array to byte array slices etc var a byte
var b []byte
i know how to do this
c := append(b,a...)

but how do i do this elegantly?
c := append(a,b...) <-- what's the solution does anyone knows?
Would like to have the c[0] == a, c[1:] == b for checking next time

A: You can make a a slice as well then append it with b.
c := append([]byte{a}, b...)

A: You can use the bytes.Buffer to make this cleaner:
var a byte
var buf bytes.Buffer

buf.WriteByte(a)// For a single byte
buf.Write([]byte{a})// For byte slice


text:
Q: How can I include an svg graphic into a tufte-book document? I've used Inkscape to create this figure (though perhaps not to a sane scale). I can edit this and export it to whatever file format might make things easiest. I'm also willing to use other tools to do further conversion if that is necessary.
The figure is a single color, and uses a handful of paths, but I don't think I could recreate it with the tikz stuff, at least not by hand. I'd like to do it as a margin figure (it looks sort of bad scaled up large), but margin figures seem to do /input{file_no_extension] and it doesn't seem to be compatible with export-latex option. There's also a save option with Latex+PSTricks which saves it as a .tex file, the results of which are smaller than I figured (and somewhat human-readable). My skill level's pretty low, and I'm mostly working off the tufte-book example, so I don't know where to go from here.


text:
Q: clipsToBounds / masksToBounds not working for image view in table view cell? So I had done it several times, it worked fine, but i don't know what am I missing this time. The Problem is that image inside image view is not being clipped to bounds.
In simulator it is shown like this:

Inside the table view cell class, in my awakeFromNib() method i have following code:
override func awakeFromNib()
{
        super.awakeFromNib()

        profileImageView.layer.masksToBounds = true
        profileImageView.clipsToBounds = true
        profileImageView.layer.cornerRadius = profileImageView.frame.size.width / 2

        profileImageView.layer.borderWidth = 2
        profileImageView.layer.borderColor = UIColor.black.cgColor
}

but still as you see in the image, the image inside image view is coming out of the bounds, whereas circular border is correctly applied.
I have tried to put this code inside layoutSubviews() method in tableViewCell class, as well as i have also tried to apply this cornerRadius inside cellForRowAt method of table view.
Moreover, i have also tried changing the properties of image view to Aspect Fit and Scale To Fit from storyboard.
Nothing is working, The image is still shown outside the circular bounds! why ?
EDIT: Screenshot of my storyboard, where i had a prototype cell, with image view in it

A: As per the OP...
In cellForRowAt you're setting:
cell.imageView?.image

where you should be setting:
cell.profileImageView.image

A UITableViewCell has "built-in" .textLabel, .detailTextLabel and .imageView elements. We have to be careful not to use those objects if we've created a custom cell with our own labels / imageViews / etc.


text:
Q: Families of Hessenberg varieties for $GL_n$ In short, the question is

What do we know about the sheaf $\pi_*\underline{\bar{\mathbb{Q}}_{\ell}}$ given by the family of (very original, see below) Hessenberg varieties for $GL_n$? As a sum of shifted perverse sheaves, does every component have full support?

Fix a choice of Borel $B\subset GL_n$ (over any field of preference, say $\mathbb{C}$), and $\mathfrak{b}=\operatorname{Lie} B$. Let $\mathfrak{h}\subset\mathfrak{gl}_n$ be the sum of $\mathfrak{b}$ and the negative simple root subspaces. Consider the family of Hessenberg varieties
$$\tilde{\mathfrak{g}}_{\mathfrak{h}}:=\{(g,\gamma)\in GL_n/B\times\mathfrak{gl}_n\;|\;g^{-1}\gamma g\in\mathfrak{h}\}$$
with the natural map $\pi:\tilde{\mathfrak{g}}_{\mathfrak{h}}\twoheadrightarrow\mathfrak{gl}_n$ by $(g,\gamma)\mapsto\gamma$. The fibers of $\pi$ are the very original, so-called Hessenberg varieties. They are paved by affine spaces, see e.g. [1]. The generic fiber is the toric variety given by the Weyl chamber decompositions (where torus is the centralizer in $PGL_n$) [2, $\S$IV].
[1] Tymoczko, Julianna, Linear conditions imposed on flag varieties, Am. J. Math. 128, No. 6, 1587-1604 (2006). ZBL1106.14038.
[2] De Mari, F.; Procesi, C.; Shayman, M. A., Hessenberg varieties, Trans. Am. Math. Soc. 332, No. 2, 529-534 (1992). ZBL0770.14022.


text:
Q: Does ruby have the array method select! or not? > a = %w(a b c)
 => ["a", "b", "c"]
> a.select!{|e| !e.nil?}
NoMethodError: undefined method `select!' for ["a", "b", "c"]:Array
    from (irb):2

ruby 1.8.7 (2010-04-19 patchlevel 253) [i686-darwin10.5.0], MBARI 0x6770, Ruby Enterprise Edition 2010.02

The doc says there is a method called select! in array.
http://www.ruby-doc.org/core/classes/Array.html#M000252

A: The docs you linked to are for Ruby 1.9.2. Ruby 1.8.7 Arrays don't have select!.
EDIT: As a future reference, you can view documentation for the different versions of Ruby that are out there.

A: Array#select! was introduced in Ruby 1.9.2.
To get it in older Ruby versions and stop worrying about which versions of Ruby have which methods, you can require "backports/1.9.2/array/select".
You can also use Array#reject! or combine #replace and #select instead.

A: Ruby 1.8.7 does have Array#reject!, though:
>> a = [1, 2, nil]
=> [1, 2, nil]
>> a.reject! &:nil?
=> [1, 2]

A: The code works for me, but I'm running Ruby 1.9.2 (which is the same version of the document you linked).
Here is the 1.8.7 documentation. Notice only select is available, not select!

A: The problem is that you are using Ruby 1.8.7 . The docs you refer to are for Ruby 1.9.2 . 1.8.7 does not include Array#select!, as you can see here:

*

*http://www.ruby-doc.org/core-1.8.7/


text:
Q: ssh with keys work on one Ubuntu box bot not on another Ubuntu box This is driving me nuts :)
I'm trying to ssh from a Synology diskstation to a Ubuntu server. I've created a keypair on the Synology box:
ssh-keygen -v -t rsa -f ~/.ssh/backup-ubuntubox2 -P ""

and copied the ~/.ssh/backup-ubuntubox2.pub from the Synology box to ~/.ssh/authorized_keys on the Ubuntu box.
It works just fine.
Now, I did the exact same things for/on the other Ubuntu box, but ssh keeps prompting me for a password:
why???
backupsvc@NAS9:~/.ssh$ ssh rsyncuser@ubuntubox2 -i /var/services/homes/backupsvc/.ssh/backup-ubuntubox2 -v
OpenSSH_7.4p1, OpenSSL 1.0.2o-fips  27 Mar 2018
debug1: Connecting to ubuntubox2 [10.0.0.2] port 22.
debug1: Connection established.
debug1: identity file /var/services/homes/backupsvc/.ssh/backup-ubuntubox2 type 1
debug1: key_load_public: No such file or directory
debug1: identity file /var/services/homes/backupsvc/.ssh/backup-ubuntubox2-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.4
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.8
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.8 pat OpenSSH* compat 0x04000000
debug1: Authenticating to ubuntubox2:22 as 'rsyncuser'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:dNwmsFmQw2apTUYZWTBy6G0pd9hVA+OKS/Q5G1bmlfI
debug1: Host 'ubuntubox2' is known and matches the ECDSA host key.
debug1: Found key in /var/services/homes/backupsvc/.ssh/known_hosts:2
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /var/services/homes/backupsvc/.ssh/backup-ubuntubox2
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: password
rsyncuser@ubuntubox2's password:


text:
Q: ¿Por qué no puedo agregar la referencia Visual CompilerServices? Necesito usar esta librería para mi programa pero no aparece por ninguna parte.
La libreria es: Visual CompilerServices
Los errores que obtengo son:

The name 'CallType' does not exist in the current context (CS0103) -
C:\Users\Silvul\Documents\SharpDevelop Projects\Wero\MyClass.cs:34,549
The name 'Versioned' does not exist in the current context (CS0103) -
C:\Users\Silvul\Documents\SharpDevelop Projects\Wero\MyClass.cs:34,61
The name 'CallType' does not exist in the current context (CS0103) -
C:\Users\Silvul\Documents\SharpDevelop Projects\Wero\MyClass.cs:35,299
The name 'Versioned' does not exist in the current context (CS0103) -
C:\Users\Silvul\Documents\SharpDevelop Projects\Wero\MyClass.cs:35,61

A: Trata de usar los espacios de nombres:
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;

Documentación: Versioned y CallType


text:
Q: New Xcode 7.3: Swift NSDate extension with nullable convenience init crashes EXC_BAD_ACCESS I have this NSDate extension with nullable init, which worked fine all the time, until I updated to newly released Xcode 7.3.
Now it crashes with EXC_BAD_ACCESS.
extension NSDate
{
    convenience init?(dateString:String, formatString:String?)
    {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = formatString

        let newDate:NSDate? = dateFormatter.dateFromString(dateString)

        if let newNewDate = newDate
        {
            self.init(timeInterval:0, sinceDate:newNewDate)
            return
        }

        print("ERROR: Wrong format [\(formatString)] for date [\(dateString)]")
        return nil
    }
}

let d1 = NSDate(dateString: "2016-01-01 11:00:00", formatString: "yyyy-MM-dd hh:mm:ss") // OK
let d2 = NSDate(dateString: "qq123", formatString: "qwe") // EXC_BAD_ACCESS

Do you have any possible solution for this?
Cannot figure out - am I abusing extension of NSDate somehow?

A: As dan mentioned in his comment already, making sure to always initialize the object before returning nil from a failable initializer (or throwing from a throwing initializer) fixes this issue.
For more information on the underlying issue, see SR-704: EXC_BAD_ACCESS on returning nil from a failable initializer of NSObject subclass. Looks like it was fixed in the mainline branch, but didn't make it into the final Swift 2.2 release. Expect it to be fixed in the next point update.


text:
Q: Learn Python the hard way, exercise 10.4 #Combine %r with double-quote and single-quote escapes and print them out.
#Compare %r with %s. Notice how %r prints it the way you'd write it in your file,
#but %s  prints it the way you'd like to see it?

This is what I wrote for the exercise:
1) mybugs1 = "Guido said: %r and moved on." %'I \'love\' \"my\" bugs'

2) mybugs2 = "Stallman said: %s and moved on." % 'I \'love\' \"my\" bugs'

3) print mybugs1

4) print mybugs2

Output
Guido said: 'I \'love\' "my" bugs' and moved on.

Stallman said: I 'love' "my" bugs and moved on.

Question
%r doesn't print everything the way I'd write it in my .py file (for example it prints "my" instead of \"my\" at line 1). Why?

A: there are several ways to write string literals in python, with single or double quotes, single-line or multiline, raw or normal.  None of that is preserved in the string itself, though; once the parser parses it, no information remains about how it was presented in the source;  it doesn't even need to be in the source, you could generate the string dynamically, say, by reading it from a file, asking the user, or turning a number into a string.
So when you repr() a string, python guesses which way to format it to look like a literal.  The rules it uses are simple, if the string contains single quotes but no double quotes, it uses a single-line, double-quote, non-raw literal;  In all other cases, it uses a single-line, single-quote, non-raw literal;  Stated another way, python prefers single quotes, but if it's formatting a string that has single quotes, but not double quotes, it can repr() that string without backslash escaping the quotes by using a double quoted string.
remember, repr() doesn't return what you typed, because it doesn't know what you typed; you might never have typed it all.  It returns something that can be parsed back into the same value.  The identity* is:
x == eval(repr(x))

not
x == repr(eval(x))

* repr() is not magical for this either, not all objects implement __repr__ in a way that preserves this constraint.  repr is mostly used for providing useful debugging information, not for generating python code

A: Double-quotes inside single-quotes don't have to be escaped, and vice versa.
The parser removes the backslash.
Example
>>> s = 'I \'love\' \"my\" bugs'
>>> s
'I \'love\' "my" bugs'
>>>


text:
Q: Best way to chill a cup of coffee with cold water and 5 minutes Initial data

*

*1 x 3/4 full cup of hot coffee / tea / your favorite morning beverage

*cold water

*5 minutes

Considering that it's starting to get hot outside, and we all want to drink reasonably cold coffee / tea (well, in any case, not scalding hot), I have the following options:
1. Wait for 5 minutes
So the hot coffee releases as much energy as possible in the 5 minutes, then add cold water to fill the coffee cup
2. Add cold water
So the temperature is lowered as fast as possible in the start, then let the air do the rest.
Question
Which option cools the coffee more ? Are there other, better options
   ?
From what I can figure out, waiting 5 minutes first is the most obvious choice, but I noticed that physics isn't always as intuitive as we may think.
PS: Would a spoon to stir the beverage have any impact on the difference between the two ?

A: Option 1 is the way to go. To a good approximation the cooling process has an exponentially decaying temperature, so the rate of cooling is proportional to the temperature itself. If you add the cool water first, you will reduce the cooling effect of waiting 5 minutes.
We did this experiment back in high school. The assumption that enters here is that the temperature drop caused by the addition of cold water is approximately independent of the beverage's temperature. This is justified as long as the temperature difference between cold water and hot beverage is large. I guess one could put more detail into the simulation by calculating the mixing temperature explicitly, though...

A: If you have an additional mug, then the most effective way to cool the coffee will be to run the empty mug under cold water to chill it, dry it, then pour your coffee into that mug. Then repeat with cooling the empty mug with water and pouring your coffee back into it.
Or you could just pour the coffee between the two cups continuously to aid cooling by exposing it to their air.
Stirring will help too, as it will keep the coffee at a constant temperature rather than the top layer being a colder temperature than the rest (which will reduce the rate of cooling.)
For actually mixing cold water with your drink, this should be done last for the reasons mentioned in Nijankowski V's answer; you will lose more heat in the same time by being at a higher temperature.

A: Lets take each case and make some calculation. So, the first case, waiting for 5 minutes than adding some cold water. Assume the following values:
The initial "hot" temperature of the coffee $T_H=80^{\circ}C$
The temperature of the surrounding medium $T_m=23^{\circ}C$
Using Newtons cooling law
$$\frac{dT}{dt}=-k(T-T_m)$$
and after a simple integration we get
$$T_c=T_m+(T_H-T_m)\mathrm{e}^{-kt}$$
Taking $k=0.05$ we find $T_c$ to be $T_c\simeq63^{\circ}C$. Now we have to add some cold water. Lets say we add $1/4^{th}$ of a cup at $T_{cold}=10^{\circ}C$.
$$-Q_{coffee}=Q_{water}$$
$$-cm_{c}\Delta T_{coffe}=cm_{w}\Delta T_{water}$$
$$-\frac{3}{4}(T_f-T_{c})=\frac{1}{4}(T_f-T_{cold})$$
And we find $T_f$ to be $T_f\simeq49^{\circ}C$
Now lets look at the second method, mixing them from the start. We just have to replace the numerical value for $T_c$ in the above formula with the initial temperature of the coffee $T_H$. Doing this, we find that the temperature after mixing is $T_{f}'\simeq 62^{\circ}C$.
Thus, as Neuneck already said, the first method is the best one. These are at best some approximate calculations, but even so, the difference is clearly visible.
Edit:
As a response to the comments, if you add hotter and hotter water to your coffee the final temperature after mixing will be higher (it will grow linearly with the temperature of the water you add.) Here is a plot for it.


text:
Q: How to do regular expressions with all lines There is a text like this (many lines)

ABCD
TEST(aa
  bb
  cc
  dd)
EFG

i want
"TEST(aa
bb
cc
dd)"

but
TEST\(.*\) =>
"TEST(aa"
How can I get results that include all the lines?

A: After TEST(, try selecting characters other than ) until you come to a ). By default, . does not match a newline, but an excluded character set will.
TEST\([^)]*\)

https://regex101.com/r/454Kvg/1

A: The dot does not match line break characters. You could use a modifier (?s) to make the dot match line breaks.
The .* should then be non greedy .*? to match the first closing )
(?s)TEST\(.*?\)


text:
Q: Unexpected argument warning on mixin with Python 3.6, Flask, and PyCharm I'm trying to implement a custom mixin in Python 3.6. Child classes would inherit its methods as well as base class.
db = flask_sqlalchemy.SQLAlchemy()

class CustomMixin(object):
    # {... __init__ is not being explicitly called, instance and class methods go here ...}

class UserModel(CustomMixin, db.Model)
    # {... class variables, own and inherited methods go here ...}

However, although my solution works, it gives a weak warning in PyCharm Community 2019.2:
user = UserModel(class_var_1=value_1, class_var_2=value_2) # Here the warning appears

Full warning text is the following:
Unexpected argument(s)
Possible callees:
object(self: object)
object.__new__(cls: object)

What are possible reasons of this warning? Could it be an issue related to inheritance chain?


text:
Q: In 3 level JqGrid, get the first table's primary key when the 2nd table's "+" sign is pressed I am new to JqGrid and please help me with this request.
I have a 3 level hierarchical JqGrid setting as shown in the link. It is not exactly the same, but very similar. My requirement is to have the CustomerGrid's primary key also passed when OrderGrid is expanded.
Or in short, I would like to have
    public void SetUpThreeLevelGrids(ThreeLevelHierarchyJqGridModel model)
    {
        var customersGrid = model.CustomersGrid;

        // code here

        int cId;
        //cId = <CustomerId from the CustomerGrid>; //*****How to get this******
        ordersGrid.DataUrl = Url.Action("ThreeLevel_OrdersDataRequested", new { customerId =  cId });

        // code here
    }

I would like to use that variable passed to the ThreeLevel_OrderDetailsDataRequested method:
public JsonResult ThreeLevel_OrderDetailsDataRequested(int customerId, string parentRowID)
{
    // code here
}

A: I created a static variable named CustomerId in my Controller. I do not know whether this can break anything or not. I just wanted to make it work.
public static int customerId = 0;

In the Action method for the second grid, I assigned the CustomerId value.
public JsonResult ThreeLevel_OrdersDataRequested(string parentRowID)
{
    var northWindModel = new NorthwindDataContext();
    var model = new ThreeLevelHierarchyJqGridModel();
    customerId = int.Parse(parentRowID);
    SetUpThreeLevelGrids(model);

    //code
}

Accessed the global static variable in the third level grid.
public JsonResult ThreeLevel_OrderDetailsDataRequested(string parentRowID)
{
    //Code
    var orderDetails = from o in myDbModel.MyCustomerOrderDetails
         where o.OrderID == Convert.ToInt32(parentRowID)
         and o.CustomerId == customerId //static global variable
         select o;

    //Code
}

If anyone has a better suggestion to get the 1st level table's selected primary key in the third level grid, please let me know.


text:
Q: Convert PHP's password_verify to Ruby on Rails We're in the process of converting our site from an old PHP framework to Rails, and would really like for users to continue being able to login with their old password. On the old site, we're using password_hash and password_verify to hash and verify the passwords. However, on Rails I can't seem to get it to verify the old password.
Here is what we have in PHP:
Hash:
password_hash($user['salt'] . $password . $user['salt'], PASSWORD_DEFAULT);

Verify:
password_verify($user['salt'] . $password . $user['salt'], $user['password'])

On the new Rails framework we're using Devise and have built a custom migration script to move everything over and identify the correct password hashing method based on a password_version stored in the db, and this is what I'm using inside my User model:
def valid_password?(password)
  if password_version == 'legacy'
    hash = BCrypt::Password.new(encrypted_password)
    hash_str = password_salt+password+password_salt

    return hash.is_password? hash_str
  end

  super(password)
end

Any ideas would be greatly appreciated

A: The format of a PHP password_hash password looks roughly like this:
$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a

The default Ruby Bcrypt method produces passwords of the form:
$2a$10$GtKs1Kbsig8ULHZzO1h2TetZfhO4Fmlxphp8bVKnUlZCBYYClPohG

For a clean solution here you can always differentiate between the two by the $2y or $2a prefix. There's no need for a format column when it's already baked into the format.
For example:
case (encrypted_password[0,3])
when '$2y'
  # Legacy PHP password
  BCrypt::Password.new(encrypted_password.sub(/\A\$2y/, '$2a')).is_password?(salt + password + salt)
when '$2a'
  # Ruby BCrypt password
  BCrypt::Password.new(encrypted_password).is_password?(password)
else
  # Unexpected type?
end

What you'll want to do on a successful verification of password is re-write the password to the database using Ruby's method to gradually replace all the old PHP formatted ones.


text:
Q: DML operation Update not allowed on PresenceUserConfig public static void changeChatCapacity() {
        PresenceUserConfig maxCapacity = [
            SELECT Id, Capacity, OptionsIsDeclineEnabled
            FROM PresenceUserConfig
            WHERE DeveloperName = 'AgentChat'
        ];
        maxCapacity.OptionsIsDeclineEnabled = true;
        try {
            update maxCapacity;
        } catch (DmlException e) {
            System.debug('The following exception has occurred: ' + e.getMessage());
        }
    }

This code returns the error:

DML operation Update not allowed on PresenceUserConfig

Salesforce documentation sites that DML operations is available on this object. Does anyone know why this happens?

A: The SOAP/REST/Tooling/etc documentation tells you if you can perform a given operation in that API. Apex is not allowed to perform DML on some types of objects that are otherwise createable/updateable in an API. These objects are usually restricted because the data can't be properly completed atomically within an Apex transaction or could otherwise cause "weird" behavior in the transaction. Unfortunately, the documentation doesn't explain why Apex cannot perform a particular operation, so all we usually have is the error message from the runtime itself. As such, it appears you will need to use a REST API call from Apex in order to achieve your goals.


text:
Q: If I add url "http://www.yahoo.com" in iframe, it is giving error "Refused to display, set 'X-Frame-Options' to 'DENY' ". so how to solve? I have a iframe in page , and whatever url I type to address bar, it renders that url in the iframe, but for http://www.yahoo.com , it is showing blank iframe and giving me error "Refused to display 'https://in.yahoo.com/?p=us' in a frame because it set 'X-Frame-Options' to 'DENY'"
Now i want to handle this error, May be i can redirect user to directly to www.yahoo.com...
Please Give me Some Solution.How Can i solve it?
THANKS

A: You can't; Yahoo has used the X-Frame-Options header to "opt out" of having their site displayed in a frame. This header cannot be overridden by your page.
Pick another site to put in your iframe.


text:
Q: Permalink Problem with Custom Post Type First Please open this link: http://www.infoproductexpert.com .
Now you will find Multiple category in the left panel.
I have created a custom post_type. This post_type name is "product". Under this post_type I have added category under each product. So that as per product, I can separate the link.
Requirement 1
If you click any category, it is showing something like this: http://www.infoproductexpert.com/category/green-energy-products/
But I want to change this to http://www.infoproductexpert.com/green-energy-products/ . Thats mean, I do not want to show this post_type.
Requirement 2
Also if you click any product under each category, it is showing something like this: http://www.infoproductexpert.com/product/diy-home-energy/ . But I want to see this : http://www.infoproductexpert.com/green-energy-products/diy-home-energy/. It's meaning product must be showing under each category and do not want to show post_type here also.
Can anyone please help me, how can I do this?
This is really important to me.
Waiting for your reply.

A: To remove category from your URL do:

*

*Go to Setting > Permalinks

*Select Custom Structure

*Add /%category%/%postname%/ after your domain

*Change Category Base to period/dot.

Read this blog https://jonnyjordan.com/blog/how-to-remove-category-from-your-urls-in-wordpress/


text:
Q: Do the first two arguments in exec* functions contain redundant information? I seem to miss something about those exec* functions.
The first argument is the filename or pathname of  the executable to be executed.
The second argument (when l) or the first element of the second argument (when v) is also something similar. For example, here.
Do we really need to repeatedly duplicate redundancy? Thanks.

A: They often do have the same information but it's not redundant. The first is the name of the executable, but the second is what the executable sees as the name. For example, BusyBox uses links to provide different functionality based on the name with which the executable is called. So sometimes you want to give a different name to the called binary than the one on disk.

A: By convention, the first argument to a program (i.e. argv[0]) is the name of the program being executed, however it doesn't necessarily have to be.
For example:
execl("/bin/ls", "ls", "-l", (void *)NULL);

In this case, the program to run is the full path to the executable, while the first argument is just the executable name without the path.

A: You can give anything you want as arg (the second argument).
Even "nothing" (arg = [NULL]).
The only effect it will have is that the program called will have as argv exactly what you give it throught arg.
However, some program expect to always have argv[0] and doesn't check if argv[0] is NULL or not. If you give nothing, you can break the program called.
Other than that, it should not cause any problem has any sane program will check his argument.

A: If you feel you won't ever want the first array member to differ from the first argument, you can always wrap the function to avoid the repetion:
int my_execvp(char const *argv) { return execvp(argv[0],argv); }