text:
Q: git diff: many patches with three '@' symbol I am writing an automatic tool based on git show, which relies on git diff command. I wrote a small parser which takes the output of git show as the text to parse, and in most situations in the result the lines start with '@@' indicates which lines it will compare.
However, I met an situation like this:
@@@ -460,22 -415,8 +460,22 @@@

What does that mean? Is it possible that there will be even more (4 or more) '@' symbols with even more subtle meanings?

A: It looks to me like you're doing a show on a merge, and this hunk differs from both parents; could that be the explanation?

A: You are showing a merge in combined diff format. If you look at the man-page of git show, it has a complete section about combined diff format, when it is used and how it looks like. Also in the initial description of git show it says that merges will be shown like git diff-tree --cc which also refers to the combined diff format.
And yes, there can be more than three @ symbols. There will be one per parent commit + 1. So if you have a merge with three parents (a so-called octupus merge), there will be four at signs. If you have four parents, there will be five at signs and so on.


text:
Q: Overflow error for encryption I am getting an overflow error in the following code:
    Public Shared Function AESFileEncrypt(inputFilename As String, outputFilename As String) As Boolean

    'Create SymmetricAlgorithm object and specify the Key and IV.
    Dim AES As RijndaelManaged = New RijndaelManaged

    AES.Key = objKeys.aesKey
    AES.IV = objKeys.aesIV

    'Create an ICryptoTransform (Encryptor) object.
    Dim Encryptor As ICryptoTransform

    Encryptor = AES.CreateEncryptor

    'Read the unencrypted file.
    Dim InputFileStream As FileStream
    InputFileStream = New FileStream(inputFilename, FileMode.Open, FileAccess.Read)

    Dim InputFileData(CType(InputFileStream.Length, Integer)) As Byte
    InputFileStream.Read(InputFileData, 0, CType(InputFileStream.Length, Integer))

    Dim OutputFileStream As FileStream
    OutputFileStream = New FileStream(outputFilename, FileMode.Create, FileAccess.Write)

    'Create a CryptoStream object using the Stream and ICryptoTransform objects.
    Dim EncryptCryptoStream As CryptoStream
    EncryptCryptoStream = New CryptoStream(OutputFileStream, Encryptor, CryptoStreamMode.Write)
    EncryptCryptoStream.Write(InputFileData, 0, InputFileData.Length)
    EncryptCryptoStream.FlushFinalBlock()

    'Clear any sensitive data from the cyptographic object.
    AES.Clear()

    'Close stream objects.
    EncryptCryptoStream.Close()
    InputFileStream.Close()
    OutputFileStream.Close()

    Return True

    'Catch ex As Exception
    'Debug.Print("AESFileEncrypt", ex.Message)
    'Return False
    'End Try

End Function

The error is at this line:
        Dim InputFileData(CType(InputFileStream.Length, Integer)) As Byte

This happens on large files. I know it is because the byte array cannot be that large. Can I please have some help to modify this code to get it working?
Thanks
EDIT
This is my current work on this function:
    Public Function AESFileEncrypt(inputFilename As String, outputFilename As String, Password As String, Salt As String) As Boolean

    Dim AES As RijndaelManaged = New RijndaelManaged

    Dim HashAlgorithm As String = "SHA1" 'Can be SHA1 or MD5
    Dim PasswordIterations As String = 2
    Dim InitialVector As String = "WinStorePassword" 'This should be a string of 16 ASCII characters.
    Dim KeySize As Integer = 256 'Can be 128, 192, or 256.

    Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector)
    Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(Salt)
    Dim DerivedPassword As PasswordDeriveBytes = New PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations)
    Dim KeyBytes As Byte() = DerivedPassword.GetBytes(KeySize / 8)

    Dim Encryptor As ICryptoTransform

    Encryptor = AES.CreateEncryptor(KeyBytes, InitialVectorBytes)

    Dim InputFileStream As FileStream
    InputFileStream = New FileStream(inputFilename, FileMode.Open, FileAccess.Read)

    Dim OutputFileStream As FileStream
    OutputFileStream = New FileStream(outputFilename, FileMode.Create, FileAccess.Write)

    Dim EncryptCryptoStream As CryptoStream
    EncryptCryptoStream = New CryptoStream(OutputFileStream, Encryptor, CryptoStreamMode.Write)

    Const BUFFER_SIZE As Integer = 4096
    Dim buffer(BUFFER_SIZE - 1) As Byte
    Dim Position As Long

    Do

        If (Position + BUFFER_SIZE) > InputFileStream.Length Then
            InputFileStream.Read(buffer, Position, InputFileStream.Length - Position)
            EncryptCryptoStream.Write(buffer, Position, BUFFER_SIZE)
            Exit Do
        Else
            InputFileStream.Read(buffer, Position, BUFFER_SIZE)
            EncryptCryptoStream.Write(buffer, Position, BUFFER_SIZE)
        End If

        Position += BUFFER_SIZE

    Loop

    EncryptCryptoStream.FlushFinalBlock()

    AES.Clear()

    EncryptCryptoStream.Close()
    InputFileStream.Close()
    OutputFileStream.Close()

    Return True

End Function

Is this correct? I did a test an a small file, and the output was a lot larger than i expected?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Distributed, error-handling, copying of TB's of data We have a box that has terabytes of data (10-20TB) each day, where each file on the drive is anywhere from megabytes to gigabytes.
We want to send all these files to a set of 'pizza boxes', where they will consume and process the files.
I can't seem to find anything that is built to handle this amount of data besides distcp (hadoop). Robocopy/etc won't do.
Anyone know of a solution that can handle this type of delegation (share the work amongst the pizza boxes) and has reliable file transferring?

A: Take a look at Flume http://archive.cloudera.com/cdh/3/flume/UserGuide.html
Flume is a distributed, reliable, and available service for efficiently collecting, aggregating, and moving large amounts of log data. It has a simple and flexible architecture based on streaming data flows. It is robust and fault tolerant with tunable reliability mechanisms and many failover and recovery mechanisms. The system is centrally managed and allows for intelligent dynamic management. It uses a simple extensible data model that allows for online analytic applications.
To install it https://wiki.cloudera.com/display/DOC/Flume+Installation

A: As already mentioned the Hadoop is the answer cause it's exactly made for such kind of large data. You can create Hadoop cluster and store the information there and use the core's of the boxes to analyze the information by using map/reduce.


text:
Q: Naming computer after install I'm having a hard time even searching for the topic. I'm trying to install Lubuntu on an old PC I have. What I would like to do is install the OS, but leave the name and password empty. I'm going to be giving this PC away, and I would like to have the recipient turn on the pc and have it ask them to create a name and a password. This is basically what Windows does when you buy it new, right?
Is there a way to make this happen in L/Ubuntu?

A: Go on reading about the OEM Installer.


text:
Q: Como fazer uma aplicação ASP.NET Core MVC para português? Eu gostaria de poder fazer uma aplicação em português. Já fazia isso com o ASP.NET MVC 5 de uma forma super simples através de uma instalação NuGet.
Porém não achei nada parecido para a versão CORE. Já utilizei a configuração:
        var supportedCultures = new[] {
            new CultureInfo("pt-BR")
        };

        app.UseRequestLocalization(new RequestLocalizationOptions {
            DefaultRequestCulture = new RequestCulture("pt-BR"),
            // Formatting numbers, dates, etc.
            SupportedCultures = supportedCultures,
            // UI strings that we have localized.
            SupportedUICultures = supportedCultures
        });

para tratar os requests localizados em português, mas as mensagens de erros automáticas ainda estão em inglês:

The Descrição field is required.

Como posso configurar minha aplicação para português?

A: Para localizar as mensagens de erro você precisa adicionar outro serviço: AddDataAnnotationsLocalization.
Exemplo:
public void ConfigureServices(IServiceCollection services)
{
    services.AddLocalization(options => options.ResourcesPath = "Resources");

    services.AddMvc()
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
    .AddDataAnnotationsLocalization();
}

No caso de cima, é usado um Resource seguindo o caminho \Resources\Caminho\Do\Model.resx
Model
[Display(Name = "Name")]
[Required(ErrorMessage = "Required")]
public string Name { get; set; }

Resource
Name: Name
Value: Nome

Name: Required
Value: O campo {0} é obrigatório.


text:
Q: C++ and mktime: 26/6/1943 and 27/6/1943 are the same day It's a strange situation. Check out this Coliru code:
#include <iostream>
#include <utility>
#include <ctime>

using namespace std;

#define SEGS 60
#define MINS 60
#define HOURS 24

int days(tm* date1, tm* date2)
{ return (mktime(date1) - mktime(date2)) / SEGS / MINS / HOURS; }

tm mkdate(int day, int mon, int year)
{
    tm date = {0, 0, 0};

    date.tm_mday = day;
    date.tm_mon = mon - 1;
    date.tm_year = year - 1900;

    return date;
}

int main()
{
    tm date1 = mkdate(31, 12, 2030);
    tm date2 = mkdate(1, 1, 2000);

    cout << days(&date1, &date2) << endl;
    // 11322... OK 30 * 365  (1/1/2000 - 1/1/2030)
    // + 8 (leap years) + 364 (from 1/1/2030 - 31/12/2030).

    date1 = mkdate(31, 12, 2030);
    date2 = mkdate(1, 1, 1930);
    cout << days(&date1, &date2) << endl;
    // 36889... OK; but in my machine, it returns 36888.

    date1 = mkdate(31, 12, 1943);
    date2 = mkdate(1, 1, 1943);
    cout << days(&date1, &date2) << endl;
    // 364... OK: but in my machine, it returns 363.

    date1 = mkdate(30, 6, 1943);
    date2 = mkdate(1, 6, 1943);
    cout << days(&date1, &date2) << endl;
    // 29... OK; but in my machine, it returns 28.

    date1 = mkdate(27, 6, 1943);
    date2 = mkdate(26, 6, 1943);
    cout << days(&date1, &date2) << endl;
    // 1... OK; but in my machine, it returns 0.

    return 0;
}

The comments after each example are those from Coliru and my laptop. The Coliru outputs are corrects, but my machine is who prints the wrong numbers.
If you read the code, the difference between days is correctly computed (first example, from 1/1/2000 to 31/12/2030).
But if year 1943 is in the middle of a date interval, it seems a day is lost. Second example: 1/1/1930 - 31/12/2030.
After lots of tests, I found out the problem was in Juny/1943. Third example: 1/6/1943 - 30/6/1943, returning 28 days instead of 29.
More concretly, it seems 26th and 27th are the same day. Fourth example: 26/6/1943 - 27/6/1943, returning 0 days.
My machine is a Ubuntu 14.02.2 LTS with Linux 3.13.0-52-generic x86_64, using gcc (g++) 4.8.2.
What does the problem come from? Some kind of bug of GNU libc implementation?

A: It is a timezone issue. Add this at the beginning of main():
// set the timezone to UTC
setenv("TZ", "", 1);
tzset();

Also your days() function should be written like this:
double days (tm *date1, tm *date2) {
  return difftime (mktime(date1), mktime(date2)) / 86400;
}

The root cause is that time_t represents seconds since the epoch in UTC whereas mktime() interprets its argument as a date in the local timezone. Hence it must convert it to UTC to produce a time_t. Thus if there are discontinuities relative to UTC between the two dates in the local timezone the result might be wrong.
The real solution though is not to use mktime(). It is not intended for your application (and in addition to DST there are other issues like leap seconds).
What your are trying to do is calculate the number of days between two dates in the (proleptic) gregorian calendar. You should implement this yourself, for example by converting them to julian day numbers.

A: This is not a timezone problem, even if the problem does not manifest with UTC.
There are several issues with this program, but the key one one is the fact that tm_isdst fields are not initialized. This field affect the behaviour of mktime, which introduces an adjustment in the tm_hour fields.
With this particular dates (26/6/1943, 27/6/1943), timezone (Europe/Madrid) and 0 as the content of both tm_isdst fields, you get a difference of 23 hours (82800 s) between both dates instead of 24 hours (86400 s). Then, in function days, 82800 is divided by 86400 with an integer division. The result is 0 and the day off is totally lost.
Plese, just add:
date.tm_isdst = -1;

to your mkdate function to avoid this, by telling mktimeto check the dates against the timezone for DST before computing the number of seconds since the epoch.

A: On Ubuntu 15.04, 32 bit, I get
edd@don:/tmp$ ./mkdate
11322
-12821
364
29
1
edd@don:/tmp$

where as on Ubuntu 15.04, 64 bit, I get
edd@max:/tmp$ ./mkdate
11322
36889
364
29
1
edd@max:/tmp$

That is g++ 4.9.2 in both cases.  The difference is due to time_t being four and eight bytes, respectively, so that the date difference calculation in your code gets an overflow.  But I do not see what may be a library bug in your older release.


text:
Q: Can´t use selenium on vba I'm used to running a script on vba using selenium in windows 7 with no problem, and since I installed Windows 10 a just can not open the Google Chrome automated window.
Already installed google chromedriver and the selenium library
Put the C:\....\AppData\Local\SeleniumBasic on the environmental path
The Google Chrome is version 78.0.3904.108 and the chromedriver 78.0.3904.105, and people don't seem to have problems with that...
This is the start of the code, where crashes...
   Dim bot As New Selenium.ChromeDriver, posts As WebElements, post As WebElement, i As Integer,
   mysheet As Worksheet, keys As Selenium.keys
   bot.Start "chrome", "https://valor.globo.com/impresso" **'it gots the error right here**
   bot.Get "/"

Anyone having this problem, knows what to do?

A: Check your version of Chrome, then download the ChromeDriver for your version.
This code should open Google.
The browser will close as soon as the Sub ends, so either declare the ChromeDriver on a global variable, or don't let the Sub end.
Option Explicit
Dim MyChromeDriver As ChromeDriver

sub MyCD
    Set MyChromeDriver = New ChromeDriver
    MyChromeDriver.Get "https://www.google.com/"
End Sub


text:
Q: How to fetch large API data in react and send back request to server? Let me explain what I want to achieve?

*

*This is the fetched data to get the image links and save it to setImageLinkData state which is over 100,000 links

*Since, I want to do something after the imageLinkData state is updated so, I use the useEffect hook to do it

const [ imageLinkData, setImageLinkData ] = useState([]);
const [ imageLink, setImageLink ] = useState([]);
const [ additionalImageLink, setAdditionalImageLink ] = useState([]);

useEffect(() => {
        const checkLink = async () => {
            if (imageLinkData.length > 0) {
                checkMainImage(imageLinkData, (resultImg) => setImageLink(resultImg)); // test main image link
                checkAdditionalImage(imageLinkData, (resultImg) => setAdditionalImageLink(resultImg)); // test additional image link
                const response = await getSuggList();
            }
        }
        checkLink();
    }, [imageLinkData])

*

*I tested the link if the image exists with the two function one for imageLink and another for additionalImageLink

*After I test the link I get validated links from the callback function and save it to setImageLink and setAdditionalImageLink state respectively.

 const checkMainImage = (linkArray, callback) => {
        linkArray.map(element => {
            const img = new Image();
            img.src = element.imageLink;
            img.onload = () => {
                setImageLink(element.imageLink);
                callback(element.imageLink);
            };
            img.onerror = () => {
                callback('donot');
            };
        });
    }

const checkAdditionalImage = (linkArray, callback) => {
        linkArray.map(element => {
            element.additionalImageLink.map(addImage => {
                const img = new Image();
                img.src = addImage;
                img.onload = () => {
                    return callback(addImage);
                };
                img.onerror = () => {
                    return callback('donot');
                };
            })
        });
    }

*

*So, what happening in my code next is when I try to access the imageLink state(not from the json data) and additionalImageLink state(not from the json data) I only get one or two value

useEffect(() => {
        // if (imageLink.length > 0 || additionalImageLink.length > 0)
            console.log(imageLink);
    }, [imageLink])

*

*The result

A: checkMainImage(imageLinkData, (resultImg) => setImageLink(resultImg)); // test main image link
checkAdditionalImage(imageLinkData, (resultImg) => setAdditionalImageLink(resultImg)); // test additional image link

In this setImageLink(resultImg) and setAdditionalImageLink(resultImg), you are setting only the last value that is available in the json data.
Shouldn't it be pushing the value to the imageLink and additionalImageLink array?
Like setImageLink([...imageLink, resultImg])?


text:
Q: Logical block size on SSD I'm currently working on a custom test/benchmark for SSD (CFast card) that runs on Win10 (written in C++). Part of the job is to read and interpret the S.M.A.R.T. attributes reported by the SSD. The one I'm interested in now is called "Total Host LBAs written", i.e. the number of LBAs written by the host system. The information I'm missing is "what is the size of memory one LBA refers to, in bytes?".
I have done some homeworks on how SSDs internally work, but I'm a bit confused in here and would hope somebody could shed some light on this, I am obviously missing something:

*

*The FTL (Flash Translation Layer) in the SSD performs, amongst other operations (wear-leveling, garbage-collection etc.), LBA-to-physical address mapping.

*The smallest memory unit that is individually readable/writable in SSD is a page. In my case, the page is said to have 16KiB of size. From this I would naively conclude that the LBA size will be the same as page size, i.e. 16KiB (or its integer multiple).

*On the other hand, I would expect that the LBA will have the size of "sector" reported by GetDiskFreeSpace() from WinAPI, which reports 512B (with "SectorsPerCluster" = 8).

So, where am I thinking wrong and what is the real LBA size I can count with (or how can I get its value)? If the LBA size would be 512B (or 8*512 = 4KiB), the LBA would refer to 1/32 (1/4) of my flash page, which seems inefficient. I understand there's a need of emulation of older storages, but if it's allowed to write a single LBA, what does the SSD do then? Does it cache the whole page, rewrite the 1/32 part corresponding to the LBA, write it to empty block and update the LBA-physical address table?
Edit: sorry for using "LBA size", I know it's not semantically 100% correct, hopefully it's understandable...


text:
Q: Combine two character vectors I would like to combine two objects (type_1 and type_2) of character class.
type_1
[1] "FSV1_3h_s1" "FSV1_3h_s1" "FSV1_3h_s1" "FSV1_3h_s1" "FSV1_3h_s1" "FSV1_3h_s1" "FSV1_3h_s1" "FSV1_3h_s1"
   [9] "FSV1_3h_s1" "FSV1_3h_s1" "FSV1_3h_s1" "FSV1_3h_s1" "FSV1_3h_s1" "FSV1_3h_s1" "FSV1_3h_s1" "FSV1_3h_s1"

type_2

[1] "E14_5_AAACCCAAGAGGCTGT" "E14_5_AAACCCACAAATGATG" "E14_5_AAACCCACAAGGCGTA" "E14_5_AAACCCACATCGGCCA"
   [5] "E14_5_AAACCCAGTTAATGAG" "E14_5_AAACCCATCAACCTTT" "E14_5_AAACCCATCCGCAAAT" "E14_5_AAACCCATCTCCCATG"
   [9] "E14_5_AAACCCATCTTCCACG" "E14_5_AAACGAAAGGAGAGTA" "E14_5_AAACGAAAGGCGAACT" "E14_5_AAACGAAAGTAACGTA"
  [13] "E14_5_AAACGAACAAACTAGA" "E14_5_AAACGAACAATTGAAG" "E14_5_AAACGAACACGACAGA" "E14_5_AAACGAACATAGGCGA"

Let's say type_1 has 16 values and type_2 has 20. I Want to create a character vector that will contain 36 in total.


text:
Q: Cómo filtrar una petición GET mediante la url de Firebase Estoy recién empezando con Firebase. Antes he estado practicando con json-server para crear una api falsa, la cual me permite mediante la url filtrar datos de un json.
Con json-server hacía algo como esto: http://localhost:3001/test/?id=1&id=2&id=5 con lo que podía filtrar y traer los datos de mi archivo json con los id especificados en la url.
Mi pregunta es si se puede hacer algo igual de simple o similar con Firebase. Estoy usando la "Realtime Database"
Gracias.

A: Solucionado.
Como dice A. Cedano, lo que tengo que usar es una petición cURL donde le puedo especificar parámetros de filtro.
Muchas gracias.
En mi caso, no encontré nada que filtrara por múltiples id en especifico como con json-server pero hay opciones que se asemejan bastante.
Esta documentación me ayudó a solucionar mis dudas


text:
Q: Edge tile Bug in Dwarf Fortress Last time I played Dwarf Fortress, I tried to reroute a river through a
dolomite block canal, but two tiles produced a "to near to edge" warning while trying to build the walls.
That shouldn't happen since tiles are underground and next to an edge wall, not free edge.
After testing for some time, I figured out that it should be a new bug. As far as I know, building walls within four tiles near an free edge (above ground) is forbidden, though it works undergound next to an edge wall.
Bug: If you channel natural floor four tiles next to free edge or if floor is missing, (due to river, cut tree over hall, etc.) the tile one z-level below is marked as next to free edge and walls cannot be build on it either. This can continue for multiple z-levels if you continue to channel natural floor. Due to some reason ice floors are regarded as missing natural floor and can create the same problem even if not channeled.
I guess creating new "natural floor" would work, but I don't even know whether "natural" floors can be built.
Any idea how to solve this problem?

A: According to the DF wiki, "You're not allowed to wall within five squares of the edge of the map... but this rule has more loopholes than the US federal income tax code."
Although you can channel to the second square/tile from the map edge, this doesn't solve your problem since the last (map edge) tile still blocks your outgoing water flow/canal. You can either have your dwarves dig a hole downward at that point, hoping that a cavern layer under that hole is open to the map edge so the water drains out there, or else smooth and then fortify an edge tile prior to filling your drain canal with water. Liquids such as water and magma will flow through fortifications; so you don't need to actually channel or dig the last tile.
Some tactics allowed by DF that may apply to this problem:
1) You can build floors all the way to map edge. A floor built over a ramp that is then removed, removes the ramp.
2) You can smooth un-mined stone and then fortify it even if at the map edge.
3) You can build a drawbridge at map edge. A raised drawbridge acts as a wall.
4) You can channel to the 2nd tile from the edge.


text:
Q: Getting data related through multiple models I need some help with laravel relations. I have multiple models and I want to get results of one related trough others.
First model: Branch
class Branch extends Model
{
    protected $table = 'branches';
    protected $primaryKey = 'id';
    public $timestamps = false;
    protected $fillable = ['name'];
}

Second model: User
class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function branches() {
        return $this->belongsToMany('App\Branch');
    }
}

There is Pivot table branch_user
Third Model: Cars
class Cars extends Model
{
    protected $table = 'cars';
    protected $primaryKey = 'car_id';
    protected $fillable = ['car_model_id', 'car_make_id', 'car_modification_id', 'car_registration', 'car_vin', 'owner', 'phone', 'branch_id'];

    public function make() {
        return $this->hasOne('App\CarMakes', 'car_make_id', 'car_make_id');
    }

    public function model() {
        return $this->hasOne('App\CarModels', 'car_model_id', 'car_model_id');
    }

    public function modification() {
        return $this->hasOne('App\CarModifications', 'car_modification_id', 'car_modification_id');
    }

    public function getFullName() {
        return $this->make->name . " " . $this->model->name . " " . $this->modification->name;
    }

    public function branch() {
        return $this->belongsTo('App\Branches', 'branch_id');
    }
}

Here I want to get all cars available to user. (User can have multiple branches assigned).
class CarsController extends Controller
{
    public function __construct() {
        $this->middleware('auth');
    }

    public function index() {
        $cars = Cars::all();
        return View::make('cars.list', ['cars' => $cars]);
    }
}

Hope you guys understood me. Should I use HasManyThrough or there is any other more correct way for doing this?

A: You can see hasManyThrough relation in laravel and it will feed you.
https://laravel.com/docs/5.8/eloquent-relationships#has-many-through


text:
Q: apt upgrade exits with code 137 inside docker container I am trying to upgrade the packages in a Python:3.9 based docker image, before adding my own files. I have tried running the apt upgrade -y command both in an interactive container with the base image, and as part of the Dockerfile build.
The python:3.9 image is built on Debian 11 - bullseye OS.
In both cases I get the following error INSIDE the docker environment.
$ docker run -it --name python_te
st python:3.9 sh
# apt update
Get:1 http://deb.debian.org/debian bullseye InRelease [116 kB]
Get:2 http://security.debian.org/debian-security bullseye-security InRelease [44.1 kB]
Get:3 http://deb.debian.org/debian bullseye-updates InRelease [39.4 kB]
Get:4 http://security.debian.org/debian-security bullseye-security/main amd64 Packages [121 kB]
Get:5 http://deb.debian.org/debian bullseye/main amd64 Packages [8183 kB]
Get:6 http://deb.debian.org/debian bullseye-updates/main amd64 Packages [2596 B]
Fetched 8506 kB in 3s (2606 kB/s)
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
6 packages can be upgraded. Run 'apt list --upgradable' to see them.
# apt upgrade -y
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Calculating upgrade... Done
The following packages will be upgraded:
  libexpat1 libexpat1-dev libssl-dev libssl1.1 linux-libc-dev openssl
6 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Need to get 5919 kB of archives.
After this operation, 24.6 kB of additional disk space will be used.
Get:1 http://security.debian.org/debian-security bullseye-security/main amd64 libssl-dev amd64 1.1.1k-1+
deb11u2 [1810 kB]
Get:2 http://security.debian.org/debian-security bullseye-security/main amd64 libssl1.1 amd64 1.1.1k-1+d
eb11u2 [1554 kB]
Get:3 http://security.debian.org/debian-security bullseye-security/main amd64 libexpat1-dev amd64 2.2.10
-2+deb11u3 [141 kB]
Get:4 http://security.debian.org/debian-security bullseye-security/main amd64 libexpat1 amd64 2.2.10-2+d
eb11u3 [98.5 kB]
Get:5 http://security.debian.org/debian-security bullseye-security/main amd64 linux-libc-dev amd64 5.10.
103-1 [1466 kB]
Get:6 http://security.debian.org/debian-security bullseye-security/main amd64 openssl amd64 1.1.1k-1+deb
11u2 [850 kB]
Fetched 5919 kB in 2s (2652 kB/s)
debconf: delaying package configuration, since apt-utils is not installed
(Reading database ... 23373 files and directories currently installed.)
Preparing to unpack .../libssl-dev_1.1.1k-1+deb11u2_amd64.deb ...
Unpacking libssl-dev:amd64 (1.1.1k-1+deb11u2) over (1.1.1k-1+deb11u1) ...
Preparing to unpack .../libssl1.1_1.1.1k-1+deb11u2_amd64.deb ...
Unpacking libssl1.1:amd64 (1.1.1k-1+deb11u2) over (1.1.1k-1+deb11u1) ...
Setting up libssl1.1:amd64 (1.1.1k-1+deb11u2) ...
debconf: unable to initialize frontend: Dialog
debconf: (No usable dialog-like program is installed, so the dialog based frontend cannot be used. at /u
sr/share/perl5/Debconf/FrontEnd/Dialog.pm line 78.)
debconf: falling back to frontend: Readline
(Reading database ... 23373 files and directories currently installed.)
Preparing to unpack .../libexpat1-dev_2.2.10-2+deb11u3_amd64.deb ...
Unpacking libexpat1-dev:amd64 (2.2.10-2+deb11u3) over (2.2.10-2+deb11u2) ...
Preparing to unpack .../libexpat1_2.2.10-2+deb11u3_amd64.deb ...
Unpacking libexpat1:amd64 (2.2.10-2+deb11u3) over (2.2.10-2+deb11u2) ...
Preparing to unpack .../linux-libc-dev_5.10.103-1_amd64.deb ...
Unpacking linux-libc-dev:amd64 (5.10.103-1) over (5.10.92-1) ...
Killed
      #

The interactive container then becomes unresponsive and the docker build fails with the additional information:
...
Unpacking linux-libc-dev:amd64 (5.10.103-1) over (5.10.92-1) ...
Killed
The command '/bin/sh -c apt update && apt upgrade' returned a non-zero code: 137

I have tried setting the memory limit to 16g as I saw something saying that 137 is out of memory but it still fails.
Any suggestions on how to get the updates installed?

A: There are multiple obvious errors which could easily be fixed:
Error 1:
debconf: delaying package configuration, since apt-utils is not installed

Fix by:
sudo apt -y install apt-utils

Error 2:
No usable dialog-like program is installed

Fix by:
sudo apt -y install dialog


text:
Q: Serialização de uma lista grande em JSON.Net Pessoal estou com um problema para conseguir fazer a serialização de um objeto (uma lista de uma classe com aproximadamente 5000 itens).
estou usando o JSON.NET para gerar a string Json porém a mesma está ficando com o seguinte problema, no meio da mesma fica um texto assim:
,{"State":0,"DataAlteracao":null,"Id":0,"IdDadosRastreamento":0,"CodigoPeriferico":"0","ValorPeriferico":"0"}
,{"State":0,"DataAlteracao":null,"Id":0,"IdDadosRastreamento":0,"CodigoPeriferico":"0","ValorPeriferico":"0"}
,{"State":0,"DataAl:..."0","ValorPeriferico":"1840"}
,{"State":0,"DataAlteracao":null,"Id":0,"IdDadosRastreamento":0,"CodigoPeriferico":"0","ValorPeriferico":"1380"}
,{"State":0,"DataAlteracao":null,"Id":0,"IdDadosRastreamento":0,"CodigoPeriferico":"0","ValorPeriferico":"62"}

Observem em negrito que ele cortou o nome da tag bem como colocou "..." e depois seguiu criando normalmente o arquivo.
alguém sabe o que pode ser este problema e como posso resolver? o código para realizar a serialização é o seguinte:
string jsonReq = Newtonsoft.Json.JsonConvert.SerializeObject(request);

Onde request é a lista com 5000 posições.

A: Como comentado, acredito que se você está retornando uma lista muito grande, o ideal é você adicionar em seu servidor as seguintes propriedades:

*

*Receber variáveis para paginação: número da página solicitada, número de registros por página (o cliente pode especificar isso, mas no servidor você verificar se tanto o número da página começa com 1 e não passa do número de registros existentes e também que o número de registros por página não é maior que, por exemplo, 100 registros, ou algo que permita que o response não seja muito grande);

*Estipular uma ordenação padrão mesmo que o cliente não tenha autoridade de perguntar por esta informação. Em geral, depende do contexto. Mas supondo que é uma lista incremental, pode ser legal ordenar por data descrescente. Se o cliente perguntar a primeira página com 100 registros, ele pega os 100 primeiros mais recentes. Aí se verficar que ele não tinha nenhuma destas informaçãos ele as usa, e daí passa para a página seguinte. Até chegar num registro que ele tem localmente. Daí ele não precisa perguntar pelas páginas anteriores. Em Geral esta abordagem faz mais sentido que começar da data mais antiga pra mais recente. Se a lista de retorno nunca for ordenada, seu cliente nunca poderá realizar esta operação.

*Em geral é legal você adicionar estas informações com os Headers de resposta da sua requisição. Assim seu cliente pode verificar, por exemplo, que ele perguntou pelos primeiros 100 registros mas o servidor retornou que o X-Record-Count do response diz que existem 1 milhão de registros. Se a ideia é sempre paginar até o final, você terá ideia do quanto ainda falta pra terminar. Usando Headers também facilita ao não precisar encapsular o resultado num outro objeto com estas informações.

A: Pessoal consegui descobrir era devido o tamanho do POST que estava sendo feito, configurei o web.config conforme a documentação da Microsoft:
coloquei os seguintes itens adicionais no web.config:
<system.web>
<httpRuntime maxRequestLength="2147483647" targetFramework="4.5" />
</system.web>

e
  <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="50000000"/>
      </webServices>
    </scripting>
  </system.web.extensions>


text:
Q: BST : Increment each key value by sum of all other greater keys Problem statement : Given a Binary Search Tree (BST), convert it to a Binary Tree such that every key of the original BST is changed to key plus sum of all greater keys in BST.
Input:  BST
              5
            /   \
           2     13
                /  \
               11  14

Output: The given BST is converted to following Binary Tree

              43
             /  \
            45   27
                /  \
               38   14

I was able to dig out this piece of code online which works, but I couldn't really grasp it. Passing a variable to maintain the previous sum so far further complicates my understanding.
Please care to explain to explain with a better code. Or make the below code more intuitive.
public class BSTWithInts
{
    private Node root;

    private class Node
    {
        Node leftChild;
        Integer item;
        Node rightChild;
    }

    public void addsNodes()
    {
        addSumUtil(root, 0);
    }

    private int addSumUtil(Node node, int sum)
    {
        if(node == null)
            return 0;

        if ( node.rightChild != null )
        {
            sum = addSumUtil(node.rightChild, sum);
        }
        if ( node.leftChild != null )
        {
            sum = addSumUtil(node.leftChild, sum);

            // why are we doing this here, shouldn't we just
            // traverse right tree only first
        }

       node.item += sum;
       sum = node.item;
       return sum;
    }
}

EDIT: I just realised the code is not working the way it should.
              5
            /   \
           2     13

    should give

             18
            /   \
          20     13

    and not
             20
            /   \
          15    13

A: To understand what's going on in the above code you need to understand how the recursion works.
The simple way start understanding this would be to use a System.out.println statement within the processing for the left and right children to understand better what is happening:
        if ( node.rightChild != null )
        {
            System.out.println("Accessing right child: "+node.rightChild.item);
            sum = addSumUtil(node.rightChild, sum);
        }
        if ( node.leftChild != null )
        {
            System.out.println("Accessing left child: "+node.leftChild.item);
            sum = addSumUtil(node.leftChild, sum);

            // why are we doing this here, shouldn't we just
            // traverse right tree only first
        }

You will find the output of the print statements to be in the following order thus confirming that the right child of every node is evaluated before its left child.
Accessing right child: 13
Accessing right child: 14
Accessing left child: 11
Accessing left child: 2

A: Imagine the simplest way you'd do this, remembering that it's a search tree, so everything's in order.  You'd want to start with the highest number.  Record it and leave it alone.  Then the 2nd-highest number: add the highest number to it, and keep a copy, because that's also "the sum of all numbers higher than the 3rd highest number".  Add that to the 3rd highest number and keep the sum because that will be added to the 4th highest.  You drag that sum around, each time increasing it by the current number (and vice versa).  When you get to the smallest number, you've got the sum of the rest ofthe tree there, ready to add to it.
Also, I think the code you found is wrong, even if it does work on the sample tree.  It should look more like:
private int addSumUtil(Node node, int sum)
{
    if (node == null) {
        return sum;
    }

    sum = addSumUtil(node.rightChild, sum);
    sum = node.item += sum;
    sum = addSumUtil(node.leftChild, sum);

    return sum;
}

Note that sum = addSumUtil(null, sum); is a noop.


text:
Q: Error:no such file when using fs.outputJsonSync I have a problem like this. I have created a compile.js file to compile my solidity Contract. In there to handle file I am using the fs-extra module.
This is my compile.js file
const path = require('path');
const solc = require('solc');
const fs = require('fs-extra');

const buildPath = path.resolve(__dirname,'build');
fs.removeSync(buildPath);

const campaignPath= path.resolve(__dirname,'contracts','Campaign.sol');
const source = fs.readFileSync(campaignPath,'utf8');
const output= solc.compile(source,1).contracts;

fs.ensureDirSync(buildPath);

for(let contract in output){
    fs.outputJsonSync(
        path.resolve(buildPath,contract),
        output[contract]
    );
}

It works everything finely, without for each loop. When I compile this file with for loop it gives me an error saying that
C:\Users\tharindusa\WebstormProjects\Campaign\node_modules\solc\soljson.js:1
(function (exports, require, module, __filename, __dirname) { var Module;if(!Modu
le)Module=(typeof Module!=="undefined"?Module:null)||{};var moduleOverrides={};fo
r(var key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[k
ey]}}var ENVIRONMENT_IS_WEB=typeof window==="object";var ENVIRONMENT_IS_WORKER=ty
peof importScripts==="function";var ENVIRONMENT_IS_NODE=typeof process==="object"
&&typeof require==="function"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;var EN
VIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WOR
KER;if(ENVIRONMENT_IS_NODE){if(!Module["print"])Module["print"]=function print(x)
{process["stdout"].write(x+"\n")};if(!Module["printErr"])Module["printErr"]=funct
ion printErr(x){process["stderr"].write(x+"\n")};var nodeFS=require("fs");var nod
ePath=require("path");Module["read"]=function read(filename,binary){filename=node
Path["normalize"](filename);var ret=nodeFS["readFileSy

Error: ENOENT: no such file or directory, open 'C:\Users\tharindusa\WebstormProje
cts\Campaign\ethereum\build\:Campaign.json'
    at Object.fs.openSync (fs.js:646:18)
    at Object.fs.writeFileSync (fs.js:1299:33)
    at Object.writeFileSync (C:\Users\tharindusa\WebstormProjects\Campaign\node_m
odules\fs-extra\node_modules\jsonfile\index.js:117:13)
    at Object.outputJsonSync (C:\Users\tharindusa\WebstormProjects\Campaign\node_
modules\fs-extra\lib\json\output-json-sync.js:15:12)
    at Object.<anonymous> (C:\Users\tharindusa\WebstormProjects\Campaign\ethereum\compile.js:15:8)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)

Can someone help me to solve this problem? .Thank you

A: Your filename (:Campaign.json) contains a colon, which is invalid in Windows, where colons are only used with drive letters.

A: I had run into the same problem while compiling my contracts.The issue with your code is that it tries to create a file named :Campaign which is not allowed in windows.
I used the following code to get around it
for(let contract in output){
    fs.outputJSONSync(
        path.resolve(buildPath,contract.replace(/:/g,'')+'.json'),
        output[contract]
    );
}


text:
Q: How can we open my website only chrome browser? Should not open in firefox, uc browser etc I want that my website only open in chrome browser.
It should not open in any other browser like uc browser ,firefox etc.

A: You can keep your launch function in below snippet which checks if browser is chrome or not.
if(/Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor)) {

}


text:
Q: Switching between PreferenceFragment and android.support.v4.app.Fragment; I have a BottomNavigationView where I can navigate between fragments. The third fragment is a PreferenceFragment while the other two extend Fragment. I have a simple switch case for replacing fragments but I get an error that SettingsFragment cannot be converted to Fragment.
How can I navigate between these fragments?
  BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Fragment selectedFragment = null;
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    toolbar.setTitle("Home");
                    selectedFragment = HomeFragment.newInstance();
                    break;
                case R.id.navigation_dashboard:
                    toolbar.setTitle("Dashboard");
                    selectedFragment = DashboardFragment.newInstance();
                    break;
                case R.id.navigation_settings:
                    toolbar.setTitle("Settings");
                    selectedFragment = SettingsFragment.newInstance();
                    break;
            }
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.fragmentContainer, selectedFragment);
            transaction.commit();
            return true;
        }
    };

A: Unless you're using the support preference library, PreferenceFragment extends android.app.Fragment, so you need to also extend android.app.Fragment for your other Fragments.
However, since Fragment and PreferenceFragment have been deprecated in API 28, you might want to just convert to the support Fragment and PreferenceFragmentCompat. Be aware that this will mean any Preference libraries you might be using will probably not work until they've been updated.


text:
Q: HTTP::Daemon::SSL auto-fetch and serve intermediate certs I've create a secure server in Perl using HTTP::Daemon::SSL on Windows 8.1
It works fine with Chrome and IE.  It fails under Firefox – ISSUER UNKNOWN.
I can append to the SSL_cert_file the issuer's chain cert and Firefox can then connect.
I've notice Firefox has no problems WITHOUT the issuer's chain cert appended to the SSL_cert_file when using as a secure server Apache on Windows or Python on a Raspberry Pi.
Is there any way to tell Perl's HTTP::Daemon::SSL to fetch and serve the required chain certificate(s) without having to manually add them to SSL_cert_file?

A: There is no builtin way to make HTTP::Daemon::SSL automatically get the missing certificates. Also, your observation that such thing is done with Apache or Python is wrong. In general the server need to be properly configured to send the necessary certificates.
Some browsers can work around misconfigured servers and sometimes these workarounds work only in specific situations. For example Firefox will cache intermediate certificates it has seen and use these to fill in missing chain certificates in other connections later. But this will fail if the intermediate certificate was not seen before by Firefox which can be easily tried with a newly created profile. What you've saw with Apache and Python is likely the use of already cached certificates.
Some browsers can also use the CA Issuers attribute in the Authority Information Access extension of the certificate to download a missing certificate. I think Chrome can do this. But this will of course impact the load time of the page since the missing certificate need to be retrieved first from some other server.


text:
Q: How can I show a list of objects that have "Review" as the parent object in Visualforce email template? I am trying to create an email where it will show the recipient a list of the "Review Accounts" associated with the "Review" object. Where "Review Accounts" is a Child object for "Reviews". Below is what I have but it keeps giving me the "Error: Invalid field LLC_BI__Review_Account__r for Object LLC_BI__Review__c"
<messageing:emailTemplate subject="testing email" recipientType="User"
                          relatedToType="LLC__BI_Review__c">
  <messaging:htmlEmailBody>
    <apex:repeat var="ra" value="{!relatedTo.LLC_BI__Review_Account__r}">

    </apex:repeat>
  </messaging:htmlEmailBody>
</messaging:emailTemplate>

A: Because you are using a managed package here, it looks like your definition of the relationship name has the incorrect name space LLC_BI
You have:
value="{!relatedTo.LLC_BI__Review_Account__r}"

But the namespace looks like it is LLC based on the relatedToType
So you want:
value="{!relatedTo.LLC__BI_Review_Account__r}"

assuming that is the true relationship name; more likely, it is plural
value="{!relatedTo.LLC__BI_Review_Accounts__r}"

Check your configuration to get the correct relationship name


text:
Q: C Replace Printed Text So I have this script and I want to replace printed "Dont" with "Lets". I don't want to use system() since the effect is different.
#include <stdio.h>

int main(){
    printf("Dont do this");
    /* Replace printed "Dont" with "Lets" */
    return 0;
}

A: Try \r:
#include <stdio.h>

int main(){
    printf("Dont do this");
    printf("\rLets");
    printf("\n");
    return 0;
}


text:
Q: How do you draw a line from the last position of the mouse to the present position of the mouse? So, I'm creating some drawing maker thing, but when I move the mouse it doesn't draw circles in a line. I don't know how to say it well, but I want it to draw a line from point A (last position of mouse) to point B (present position of mouse).
Start drawing here and you will understand:

const c = document.getElementById('c')
const ctx = c.getContext('2d')

c.height = window.innerHeight
c.width = window.innerWidth

function pen(e, colorHEX) {
    let mouseX = e.clientX
    let mouseY = e.clientY

    ctx.fillStyle = colorHEX
    ctx.beginPath()
    ctx.arc(mouseX, mouseY, 2, 0, Math.PI * 2)
    ctx.fill()
    ctx.closePath()
}

$('body').mousedown(function(eObj){
    $('body').mousemove(function(e) {
        pen(e, '#000000')
    })
})

$('body').mouseup(function(eObj) {
    $('body').unbind('mousemove')
})
body {
    margin: 0;
    overflow: hidden;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="style.css" rel="stylesheet" type="text/css"/>

    <canvas id="c"></canvas>

A: I think you're trying to draw a contiguous line (you don't need to do that by painting circles). You'll need to store the last mouse position, and then draw a line from there to the current mouse position.

const c = document.getElementById('c')
const ctx = c.getContext('2d')

c.height = window.innerHeight
c.width = window.innerWidth

let lastPos // state variable

function pen(e, colorHEX) {

    const pos = {x:e.clientX, y: e.clientY}
    lastPos = (lastPos || pos) // Default to current pos

    ctx.beginPath()
    ctx.strokeStyle = colorHEX
    ctx.lineWidth = 1
    ctx.moveTo(lastPos.x, lastPos.y)
    ctx.lineTo(pos.x, pos.y)
    ctx.stroke()
    ctx.closePath()

    // Update the state variable
    lastPos = pos
}

$('body').mousedown(function(eObj){
    $('body').mousemove(function(e) {
        pen(e, '#000000')
    })
})

$('body').mouseup(function(eObj) {
    $('body').unbind('mousemove')
    lastPos = undefined
})
body {
    margin: 0;
    overflow: hidden;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="style.css" rel="stylesheet" type="text/css"/>

    <canvas id="c"></canvas>

A: You can use the lineTo method
To make it move while you are dragging the line will take an extra script that includes angles and math.

const c = document.getElementById('c')
const ctx = c.getContext('2d')

c.height = window.innerHeight
c.width = window.innerWidth

let startX;
let startY;

function pen(e, colorHEX) {
    let endX = e.clientX
    let endY = e.clientY

    ctx.fillStyle = colorHEX
    ctx.beginPath()
    ctx.moveTo(startX, startY)
    ctx.lineTo(endX, endY)
    ctx.fill()
    ctx.closePath()
    ctx.stroke()
}

$('body').mousedown(function(e){
    startX = e.clientX;
    startY = e.clientY;
})

$('body').mouseup(function(e) {
    pen(e, "#000000");
})
body {
    margin: 0;
    overflow: hidden;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="style.css" rel="stylesheet" type="text/css"/>

    <canvas id="c"></canvas>

A: Drawing with mouse
You have two options.

*

*Draw a line segment from A to B setting the line width to match the circles diameter and the line cap to round.

*Interpolate the points from A to B drawing a circle (or any shape) at points 1px apart.

*I said two but there are a zillion ways to do this type of thing, but that would put this answer in the TLDR category.
Which method you use will depend on the finer details of your needs. The two example below drawing using the most basic solid line look identical.
What I think you may be having a problem with is because you are turning the event listeners on and off, the last mouse position you have is the last mouse up.
I have added two examples. One for each of the drawing options, and the top one uses an always on mouse listeners and a second turns on and of the mouse listeners as needed.
Examples
The mouse has its state put into an object called mouse.
Each time the mouse changes position the last position is put into mouse.lastX, mouse.lastY.
If the mouse event.type is mousedown the mouse.button is set to true and to false if mouseup
Mouse up and down are also used to turn on and off things like cursor, add and remove events (second example)
At the bottom of the listener it checks if the mouse is down  (mouse.button is true) and draws a line from the last position to the current position.
Using line segments

*

*Draws by using 2D API's stroke function.

*Use always on mouse listeners.

const ctx = c.getContext('2d');
const BORDER = 1;  // I added a 1px border to canvas.
c.height = innerHeight - BORDER * 2;
c.width = innerWidth - BORDER * 2;
const mouse = {x: 0, y: 0, lastX: 0, lastY: 0, button: false};
function drawLine(xA, yA, xB, yB, col, width) {
    ctx.strokeStyle = col;
    ctx.lineCap = "round";
    ctx.lineWidth = width;

    ctx.beginPath()
    ctx.lineTo(xA, yA);
    ctx.lineTo(xB, yB);
    ctx.stroke();
}

function mouseEvent(e) {
    if (e.type === "mousedown") {
        mouse.button = true;
        c.classList.add("hideMouse");
    } else if (e.type === "mouseup") {
        mouse.button = false;
        c.classList.remove("hideMouse");
    }

    mouse.lastX = mouse.x;
    mouse.lastY = mouse.y;
    mouse.x = e.clientX - BORDER;
    mouse.y = e.clientY - BORDER;

    if (mouse.button) {
        drawLine(mouse.lastX, mouse.lastY, mouse.x, mouse.y, "#000", 4);
    }
}
addEventListener("mousedown", mouseEvent);
addEventListener("mouseup",   mouseEvent);
addEventListener("mousemove", mouseEvent);
body {
    margin: 0;
    overflow: hidden;
    font-family: arial;
}
canvas {
    border: 1px solid black;
    cursor: crosshair;
}
.hideMouse {
    cursor: none;
}
div {
    background: #FFF8;
    position: absolute;
    top: 4px;
    left: 4px;
}
<canvas id="c"></canvas>

Click and drag mouse to draw

Interpolate line

*

*Replaces drawLine function body with interpolation algorithum.

*Adds mouse listeners mousemove and mouseup, on mousedown. Note that the up listener has the option {once:true} when added so does not need to be manually removed.

const ctx = c.getContext('2d');
const BORDER = 1;  // I added a 1px border to canvas.
c.height = innerHeight - BORDER * 2;
c.width = innerWidth - BORDER * 2;
const mouse = {x: 0, y: 0, lastX: 0, lastY: 0, button: false};

function drawLine(xA, yA, xB, yB, col, width) {
    var i = 0;
    const dx = xB - xA;
    const dy = yB - yA;
    const length = Math.hypot(dx, dy);
    const stepX = length > 0 ? dx / length : 0;
    const stepY = length > 0 ? dy / length : 0;
    ctx.beginPath();
    ctx.fillStyle = col;
    while (i <= length) {
        ctx.moveTo(xA + width / 2, yA);
        ctx.arc(xA, yA, width / 2, 0, Math.PI * 2);
        xA += stepX;
        yA += stepY;
        i ++;
    }
    ctx.fill();
}

function mouseEvent(e) {
    if (e.type === "mousedown") {
        mouse.button = true;
        c.classList.add("hideMouse");
        addEventListener("mouseup",   mouseEvent, {once: true});
        addEventListener("mousemove", mouseEvent);

        // Set mouse pos so last pos is not where the last mouse up was
        mouse.x = e.clientX - BORDER;
        mouse.y = e.clientY - BORDER;
    } else if (e.type === "mouseup") {
        mouse.button = false;
        c.classList.remove("hideMouse");
        removeEventListener("mousemove", mouseEvent);
    }

    mouse.lastX = mouse.x;
    mouse.lastY = mouse.y;
    mouse.x = e.clientX - BORDER;
    mouse.y = e.clientY - BORDER;

    if (mouse.button) {
        drawLine(mouse.lastX, mouse.lastY, mouse.x, mouse.y, "#000", 4);
    }
}
addEventListener("mousedown", mouseEvent);
body {
    margin: 0;
    overflow: hidden;
    font-family: arial;
}
canvas {
    border: 1px solid black;
    cursor: crosshair;
}
.hideMouse {
    cursor: none;
}
div {
    background: #FFF8;
    position: absolute;
    top: 4px;
    left: 4px;
}
 <canvas id="c"></canvas>

Click and drag mouse to draw

Side note...
jQuery is dead
BTW jQuery is not needed, it became irrelevant about 5 years ago.
Using it puts you many years behind modern front end development.
In the past 5 years the demand for jQuery experience coders has dropped a significant amount. A trend that will continue as jQuery has painted its self into a corner from which the only way out is via re branding and re targeting its purpose.
Every time you use jQuery you are investing your most valuable asset, time. Time spent learning and gaining experience. Be wise and direct that time learning what is applicable and growing in the future, and not into what started dying over a decade ago.
For more details Should you use or learn jQuery in 2020?


text:
Q: Orthogonal polynomials in the complex domain A source tells me that a set $P_n: \mathbb{C} \to \mathbb{C}$ of polynomials are orthogonal over a contour if
$$
\frac{1}{2\pi} \int_{\Gamma} P_n(z) \overline{P_m(z)}h(z)d|z|=\delta_{nm},
$$
where h is the weight...
Could someone please continue this sentence and introduce the concept of orthogonal polynomials over contours. Possibly provide an example or refer me to some suitable source. Do examples usually come with one contour or several for the same set of polynomials?

A: An important example is $\Gamma=S^1$ (the unit circle) and $h(z)=1$. Then $P_n(z)=z^n$ satisfy your requirement. Since the integrand is not holomorphic (there is a complex conjugation involved) and you integrate against $d|z|$ measure, this will no longer be true if you deform $\Gamma$.
Another important example is given by $\Gamma=\mathbb R$, $h=e^{-x^2}$ and Hermite polynomials.
All these are useful for example because they can be used to solve important differential equations, e.g. Laplace equation in various domains.


text:
Q: how to get the details of a tab when mouse is kept on a link i am trying to design a website. i have some tabs in the home page i wanted to do as shown in the screenshot. In the screenshot when i am placing the pointer in the javaL it is displaying the contents.Please suggest me how to do that

A: Try this
HTML CODE

Box

CSS
li.nav-item:hover + .box, .box:hover {
    display: block;
}
.box {
    display: none;
    list-style: none;
    opacity: 0.3;
}
.box:hover {
    opacity: 1;
}

Take A look at this
http://jsfiddle.net/4unLH/

A: You can try it with div and javascript with z-index property of css.


text:
Q: How can I retrieve the published Artifacts from Artifactory into my jenkins pipeline script I try to get the list of published Artifacts from my deploy onto my Artifactory.
I tried to do so over the BuildInfoAccessor, but the current version is lacking the getDeployedArtifacts() function.
I even tried to read the jenkins build.log object, but it somehow misses the prints from artifactory-plugin on which artifacts are deployed.
Can someone give me a hint on where to look at or an example ?

A: Am not sure is there any better way to print the BuildInfo from the artifactory-jenkins plugin itself. You can get the published info of the jenkins build via artifactory rest api.
Artifactory Rest Api
You can get the build number from the jenkins environment variable ${BUILD_NUMBER} and make a http get call via sh curl/other suitable step if any in your pipeline script.
sh "curl http://artifactory.org.net/api/build/my-build/${BUILD_NUMBER}"

Make use of withCredential step to pass username/password.
Caution: I have just made answers from my theoretical knowledge.


text:
Q: Outlook Add-In in Angular 5: Can't resolve all parameters for component I'm using Angular 5 to create an Outlook add-in. I used Yeoman to generate the files, not angular-cli. I have a service that I wrote, MeetingsService, that I'm trying to inject into one of my components, BehaviorsSearchComponent. I listed my service as a provider in AppModule, and I imported it in BehaviorsSearchComponent. When I run my add-in, I get the error
Can't resolve all parameters for BehaviorsSearchComponent: (?)

It works if I do
constructor (@Inject(MeetingsService) meetingsService: MeetingsService)

But I'd like to be able to do it without the @Inject. I also tried importing core-js/es7/reflect in my taskpane.ts file, which is my root file. I checked my webpack.config and babel/polyfill is specified for my entry polyfill. I don't think it's a circular dependency issue; I installed that package and I didn't get any warnings in the build.
Is there something I'm missing? Is there some issue with a dependency in my package.lock.json? My @angular packages are either 5.2.11 or 5.2.5.
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
...
import { MeetingsService } from './meetings.service';
import AppComponent from './app.component';
import { BehaviorsSearchComponent } from './behaviors-search/behaviors-search.component';
import { EnableAddInComponent } from './enable-addIn/enable-addIn.component';

@NgModule({
  imports: [
    BrowserModule,
    ...
  ],
  providers: [
    MeetingsService
  ],
  declarations: [
    AppComponent,
    BehaviorsSearchComponent,
    EnableAddInComponent
  ],
  bootstrap: [AppComponent]
})
export default class AppModule { }

meetings.service.ts
import { Injectable } from '@angular/core';

@Injectable()
export class MeetingsService {
  constructor() {}
}

behaviors-search.component.ts
import { Component } from '@angular/core';
import { MeetingsService } from '../meetings.service';
...

@Component({
  templateUrl: 'src/taskpane/app/behaviors-search/behaviors-search.component.html',
  styleUrls: ['src/taskpane/app/shared.css']
})

export class BehaviorsSearchComponent {

  constructor(private meetingsService: MeetingsService) {}

  ...
}

webpack.config.js
const devCerts = require("office-addin-dev-certs");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const fs = require("fs");
const webpack = require("webpack");

module.exports = async (env, options) => {
  const dev = options.mode === "development";
  const config = {
    devtool: "source-map",
    entry: {
      polyfill: "@babel/polyfill",
      taskpane: "./src/taskpane/taskpane.ts",
      commands: "./src/commands/commands.ts"
    },
    resolve: {
      extensions: [".ts", ".tsx", ".html", ".js"]
    },
    module: {
      rules: [
        {
          test: /\.ts$/,
          exclude: /node_modules/,
          use: "babel-loader"
        },
        {
          test: /\.tsx?$/,
          exclude: /node_modules/,
          use: "ts-loader"
        },
        {
          test: /\.html$/,
          exclude: /node_modules/,
          use: "html-loader"
        },
        {
          test: /\.(png|jpg|jpeg|gif)$/,
          use: "file-loader"
        }
      ]
    },
    plugins: [
      new CleanWebpackPlugin(),
      new HtmlWebpackPlugin({
        filename: "taskpane.html",
        template: "./src/taskpane/taskpane.html",
        chunks: ["polyfill", "taskpane"]
      }),
      new CopyWebpackPlugin([
        {
          to: "taskpane.css",
          from: "./src/taskpane/taskpane.css"
        }
      ]),
      new HtmlWebpackPlugin({
        filename: "commands.html",
        template: "./src/commands/commands.html",
        chunks: ["polyfill", "commands"]
      })
    ],
    devServer: {
      headers: {
        "Access-Control-Allow-Origin": "*"
      },
      https: (options.https !== undefined) ? options.https : await devCerts.getHttpsServerOptions(),
      port: process.env.npm_package_config_dev_server_port || 3000
    }
  };

  return config;
};

A: Injecting as constructor (@Inject(MeetingsService) meetingsService: MeetingsService) seems to be the only way, because the project generated with Yeoman (yo office) uses webpack instead of Angular CLI
https://github.com/OfficeDev/Office-Addin-TaskPane-Angular/issues/45#issuecomment-586167019


text:
Q: How to remove arrow from the Pgfplot pin option? I was wondering how to remove arrow from pgfplots pin option. I do not want any line and want only text.
Many Thanks in advance!

Edit: Added MWE:

I would like to remove the two arrows but want to keep the text only. I am also attaching the output.
\documentclass{standalone}
    \usepackage{amsmath, amssymb}
    \usepackage{pgfplots}
    \usepackage{tikz}
    \usepackage{lmodern}
    \usepackage[T1]{fontenc}
    \begin{document}
    \begin{tikzpicture}[every mark/.append style={mark size=1pt}]
    \begin{axis}[xmin=0, xmax=0.2, ymin=-0.01, ymax=1, width = 8cm, height = 7cm, xtick align =inside, ytick align =inside, ytick distance=0.2, xtick distance = 0.05, minor x tick num={1}, minor y tick num={1}, xlabel = Volume fraction , ylabel= {Area disorder (AD)}, legend style= {nodes={scale=0.5, transform shape}, legend pos= north east, legend cell align={left}}, y tick label style = {/pgf/number format/.cd,
            use comma,
            1000 sep={}, set decimal separator={.}, fixed,
                fixed zerofill,
                precision=1,
            /tikz/.cd}, x tick label style = {/pgf/number format/.cd,
            use comma,
            1000 sep={}, set decimal separator={.}, fixed,
                fixed zerofill,
                precision=2,
            /tikz/.cd}]

    \addplot [only marks, red, mark=square*,mark options={solid, scale=0.6}] coordinates{(0.056,0.3759)};%\addlegendentry{6 wt\% CTBN};
    \addplot [color= red, mark=square*,mark options={solid, scale=0.6}] coordinates{(0.097,0.4418)}; %\addlegendentry{9 wt\% CTBN};
    \begin{scope}[
      every pin edge/.style={<-,>=latex},
      pin distance=1.5 cm,
      every pin/.append style={font=\small}
    ]
    \node[coordinate, pin={[fill=white, pin distance = 5 mm, inner sep=2pt]90:{9R}}]
                at (axis cs:0.097,0.4418) {};
    \node[coordinate, pin={[fill=white, pin distance = 5 mm, inner sep=2pt]90:{6R}}]
                at (axis cs:0.056,0.3759) {};
    \end{scope}
    \end{axis}
    \end{tikzpicture}

    \end{document}

A: Just put draw=none for every pin edge/.style:
\documentclass{standalone}
    \usepackage{amsmath, amssymb}
    \usepackage{pgfplots}
    \pgfplotsset{compat=1.14}
    \usepackage{tikz}
    \usepackage{lmodern}
    \usepackage[T1]{fontenc}
    \begin{document}
    \begin{tikzpicture}[every mark/.append style={mark size=1pt}]
    \begin{axis}[xmin=0, xmax=0.2, ymin=-0.01, ymax=1, width = 8cm, height = 7cm, xtick align =inside, ytick align =inside, ytick distance=0.2, xtick distance = 0.05, minor x tick num={1}, minor y tick num={1}, xlabel = Volume fraction , ylabel= {Area disorder (AD)}, legend style= {nodes={scale=0.5, transform shape}, legend pos= north east, legend cell align={left}}, y tick label style = {/pgf/number format/.cd,
            use comma,
            1000 sep={}, set decimal separator={.}, fixed,
                fixed zerofill,
                precision=1,
            /tikz/.cd}, x tick label style = {/pgf/number format/.cd,
            use comma,
            1000 sep={}, set decimal separator={.}, fixed,
                fixed zerofill,
                precision=2,
            /tikz/.cd}]

    \addplot [only marks, red, mark=square*,mark options={solid, scale=0.6}] coordinates{(0.056,0.3759)};%\addlegendentry{6 wt\% CTBN};
    \addplot [color= red, mark=square*,mark options={solid, scale=0.6}] coordinates{(0.097,0.4418)}; %\addlegendentry{9 wt\% CTBN};
    \begin{scope}[
      every pin edge/.style={draw=none}, % instead of ={<-,>=latex},
      pin distance=1.5 cm,
      every pin/.append style={font=\small}
    ]
    \node[coordinate, pin={[fill=white, pin distance = 5 mm, inner sep=2pt]90:{9R}}]
                at (axis cs:0.097,0.4418) {};
    \node[coordinate, pin={[fill=white, pin distance = 5 mm, inner sep=2pt]90:{6R}}]
                at (axis cs:0.056,0.3759) {};
    \end{scope}
    \end{axis}
    \end{tikzpicture}

    \end{document}

A: i don't understand why you use pin option if you actually like to have (simple) label. also you set some options which are default for pgfplots diagrams. shorter version with use of labels is:
\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.14}
\usepackage{lmodern}
\usepackage[T1]{fontenc}

\begin{document}
    \begin{tikzpicture}[
every label/.style={label distance=5mm, font=\small}
                   ]
\begin{axis}[
    width = 8cm, height = 7cm,
    xmin=0, xmax=0.2,
    ymin=-0.01, ymax=1,
    minor tick num={1}, %minor y tick num={1},
    xlabel = Volume fraction ,
    ylabel= {Area disorder (AD)},
    legend pos= north east,
    legend cell align=left,
    y tick label style = {/pgf/number format/.cd, fixed,
                          fixed zerofill, precision=1},
    x tick label style = {/pgf/number format/.cd, fixed,
                           fixed zerofill,precision=2},
    mark size=1pt,
    mark=square*,
                    ]
\addplot [only marks, red, ] coordinates{(0.056,0.3759)
                                         (0.097,0.4418)};
\coordinate[label=90:{9R}] (x) at (axis cs:0.097,0.4418);
\coordinate[label=90:{6R}] (x) at (axis cs:0.056,0.3759);
\end{axis}
    \end{tikzpicture}
\end{document}

which gives:

A: You can achieve the desired result in a much simpler way when you use the PGFPlots nodes near coords feature. For details please have a look at the comments in the code.
% used PGFPlots v1.15
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
    \begin{axis}[
        xmin=0,
        xmax=0.2,
        ymin=-0.01,
        ymax=1,
        % -----
        % (removed a lot of key--values irrelevant to the question)
        % -----
        % moved common options here
        only marks,
        mark options={
            solid,
            scale=0.6,
        },
        %%% added stuff to achieve what you want using PGFPlots `nodes near coords' feature
        % just state that you want to use the feature
        nodes near coords,
        % by using the following key you can change the style of the nodes near coords
        nodes near coords style={
            font=\small,
            yshift=3mm,
            black,
        },
    ]
        % either you can use it using the `coordinates' syntax ...
        \addplot [
            red,
            mark=square*,
            % last you have to state the "type" of data you want to use
            % for the `nodes near coords'. Here you you don't want to
            % display numeric data, thus you have to use this value
            point meta=explicit symbolic,
        ] coordinates {
            (0.056,0.3759) [{6R}]
            (0.097,0.4418) [{9R}]
        };

        % or which is even simpler to write using the `table' syntax
        % (with the above explanations this here hopefully is pretty much
        %  self-explanatory)
        \addplot [
            blue,
            mark=square*,
            point meta=explicit symbolic,
        ] table [
            x=x,
            y=y,
            meta=meta,
        ] {
            x       y       meta
            0.076   0.3759  6R
            0.117   0.4418  9R
        };
    \end{axis}
\end{tikzpicture}
\end{document}


text:
Q: how to manipulate textwidth of footnote? I am using custom margins so I can include figures in the right margin and references in the footer. I would like the footer to span the linewidth of the text body and the margin.
Here is my minimal example:
\documentclass[10pt,letterpaper]{article}
\usepackage[left=36pt,right=233.28pt,top=2cm,bottom=2cm, marginparwidth=66mm]{geometry}
\usepackage{marginnote}
\usepackage{lipsum}

\begin{document}

\section{A title goes here}

\lipsum[1-2]

\marginnote{\footnotesize An image goes here in the right margin.}

\lipsum[1-2]\footnote{A footnote goes here in the footer and should stretch right across the page to include the right margin.}

\end{document}

I have google for a \footnotewidth but haven't had any luck with that search.
thanks

A:
\documentclass[10pt,letterpaper]{article}
\usepackage[left=36pt,right=233.28pt,top=2cm,bottom=2cm, marginparwidth=66mm]{geometry}
\usepackage{marginnote}
\usepackage{lipsum}

\begin{document}

\section{A title goes here}

\lipsum[1-2]

\marginnote{\footnotesize An image goes here in the right margin.}

\lipsum[1-2]\footnote{\hsize=\dimexpr\columnwidth+\marginparsep+\marginparwidth\relax
A footnote goes here in the footer and should stretch right across the page to include the right margin.}

\end{document}

A: Here, I add a negative \rightskip inside each footnote.  The actual value is -\marginparsep-\marginparwidth.
\documentclass[10pt,letterpaper]{article}
\usepackage[left=36pt,right=233.28pt,top=2cm,bottom=2cm, marginparwidth=66mm]{geometry}
\usepackage{marginnote}
\usepackage{lipsum}
\let\svfootnote\footnote
\def\footnote#1{\svfootnote{\rightskip\dimexpr
  -\marginparsep-\marginparwidth #1}}
\begin{document}

\section{A title goes here}

\lipsum[1-2]

\marginnote{\footnotesize An image goes here in the right margin. Adding
i i i i more to test margination.  An image goes here in the right margin.
Adding  more to test margination.  An image goes here in the right margin.
Adding more to test margination.  }

\lipsum[1]\footnote{A footnote goes here in the footer and should stretch right across the page to include the right margin.  Adding a bit more
to check the margination.}

\lipsum[2]\footnote{Testing another footnote.}

\end{document}

A: You can use LaTeX boxes to claim more width. Note that I am using \rlap which sets the width of the box to 0. This is just to avoid the "overfull" box warning. It's a bit hacky, but hey, it's LaTeX.
\newcommand{\widefootnote}[1]{%
    \footnote{\rlap{\parbox{\dimexpr\paperwidth-72pt\relax}{#1}}}%
}

Now use \widefootnote instead of \footnote. Alternatively you could do
\let\oldfootnote\footnote

\renewcommand{\footnote}[1]{%
    \oldfootnote{\rlap{\parbox{\dimexpr\paperwidth-72pt\relax}{#1}}}%
}

and use \footnote everywhere instead.


text:
Q: Poststratification and estimation I have a dataset about corn farmers in a certain region with informations like farm size, mean cost per planted hectare, number of employees, etc. Furthermore I also have from another source an estimated value for total corn area in this region.
Suppose that total estimated value is 300,000 acres and I have a sample of 26 farmers that corresponds to 4000 acres. I splitted this data based in the farm size to have more consistent estimations since there is different farmer profiles. Let F be the farm size then
Profile1: F <= 100, n1 = 14, Total area = 300 acres
Profile2: F > 100 and F <= 500, n2=10, Total area = 2100 acres
Profile3: F > 500 , n3=2, Total area = 1600 acres

Since I have that $300/4000*100=7.5\\%$ of the sampled area is from farmers with area less or equal to 100 acres, is reasonable to say that 22,500 acres(7.5 percent of total area) are from farmers with this profile?


text:
Q: Restricting View Permissions I created a user with db_dataread permission and I want to make sure the user can only run views and not see the script to how the view was created. What is the best way of doing this. I want to make sure I have all the angles covered and make sure this user doesn't have access to the script. I am using MS SQL 2008.
Thanks in advance.

A: @Djbril if you have given the user a db_dataread permission only then that should do the trick for not being able to click Design or use the Create To / Alter To options which obviously will show the underlying code that makes up the view.
Edit: I would also DENY his "View Definition" permission on the tables that the SQL View is using because he/she might be able to figure out where the data is coming from and creating his own view directly from the tables if the user has access to those.
Please mark as the answer if this helped :-)


text:
Q: Calling a function exported from C (swig interface) from C# I have a function in C language with definition like
uint8 *callme (uint8 a, uint8 b, uint8 c)

In interface.i file I have defined function as
%module abc
%{
.... C Header files (.h)
%}
extern void uint8 *callme (uint8 a, uint8 b, uint8 c);

I have generated .a file with XCode Cocoa touch library and .dll file from generated .cs files.
I am trying to call this callme function from my C# code in Xamarin iOS app.
But I am not sure how to pass the value to this function. Every time I am getting error as "Cannot convert from datatype to abc.SWIGTYPE_p_uint8"

A: Every type for which SWIG creates a *SWIGTYPE_p_** is a type that is not understood by SWIG.
You need to look arround Typemaps.
You have some example of C# typemaps in the typemaps.i you can find in [swig_file]/lib/csharp.
When you will have the correct typemaps for an uint8, your problem should be fixed.


text:
Q: How to Add sorter in my custom product collection page     my block is
public function getPagerHtml()
{
    return $this->getChildHtml('pager');
}

public function getToolbarHtml()
{

    return $this->getChildHtml('toolbar');

}

<?php echo $this->getPagerHtml(); ?> //using this for pager
<?php echo $this->getToolbarHtml(); ?>//ushing this for sorting

it's only display paging block i want to display both pager and sorter

A: Need to call sortable parameter  at your theme.
Or can call like this way as well
<div class="toolbar-bottom">
    <?php echo $this->getToolbarBlock()->setTemplate('catalog/product/list/toolbar-bottom.phtml')->toHtml() ?>
</div>

A: did u set all the sort paramters on your toolbar? like
 // use sortable parameters
        if ($orders = $this->getAvailableOrders()) {
            $toolbar->setAvailableOrders($orders);
        }
        if ($sort = $this->getSortBy()) {
            $toolbar->setDefaultOrder($sort);
        }
        if ($dir = $this->getDefaultDirection()) {
            $toolbar->setDefaultDirection($dir);
        }
    public function getDefaultDirection(){
        return 'asc';
    }
    public function getAvailableOrders(){
        return array('date_creation'=> 'Date de Création','title'=>'titre','id'=>'ID');
    }
    public function getSortBy(){
        return 'id';
    }


text:
Q: What's the best way to restrict insert/update queries when using ExecuteSqlCommand? I'm inheriting a class that has this public virtual method
public virtual int ExecuteSqlCommand(string query, params SqlParameter[] parameters)
{
    return _context.Database.ExecuteSqlCommand(query, parameters);
}

I want to override it and provide read-only access to the database, so any Insert/Update commands should be restricted
I can do it by searching for the insert/update keywords in the query, but I'm not sure this is 100% proof.
Is there any better way to achieve this?

A: Let the database security handle it. Run the queries with a user account that only has read permission to the database.
You could use your method of searching for insert/update if you want to warn the user in advance, but I wouldn't rely on it as a security mechanism. At that point you may as well run the query and handle the error if they have insufficient permissions.

A: Searching for INSERT/UPDATE/DELETE is not 100% proof if consumers want really to misuse it
They can execute something like:
EXEC('DE' + 'LETE ' + 'FROM Users')

Another way that also basically works but not proof is to create a transaction and roll it back at the end.
The best way would be to create a new user with only read-only access and connect to the database using that user account.


text:
Q: Observable.just for rxdart: ^0.26.0 I have the new rxdart: ^0.26.0 version, and I know Observable got deprecated and you can use Stream instead, question is, how do I use Observable.just for the newer version?

A: I found it on package's changelog

Observable.just has been replaced with Stream.value


text:
Q: DataValidation filters Table I have a situation where a defined table structure changes based on a control type (for my instance it is a Product Brand).  In that Table there are two column/fiels that will need to be used to populate two Data-Validation cells on the same worksheet.  These cells are above the Table, and "ideally" would be used to filter the Table's information based on the data populating the Data-Validation cells.
Data-Validation List Method Logic:
  Dim str As String
  str = Join(UniqueValues(ws,srcrng), ",")
  Dim val As Excel.Validation
  Set val = range(destrng).Validation
  val.Delete
  val.Add xlValidateList, xlValidAlertStop, xlBetween, str

*

*ws: Worksheet where @srcrng is located

*srcrng: Range to extract the Unique values from

*destrng: Range where the Data-Validation will be attached to.  This will be controlled to be only a single cell and error out if has more than 1 row and 1 column.

The Above method is encapsulated in a method which is passed two parameters Table1[Column1] and DataValidationCell1 in VBA.
Just to stave off any questions, here is the method UniqueValues logic:
Function UniqueValues(ws As Worksheet, col As String) As Variant

   Dim rng As range: Set rng = ws.range(col)
   Dim dict As New Scripting.Dictionary

   If Not (rng Is Nothing) Then
      Dim cell As range, val As String

      For Each cell In rng.Cells
         val = CStr(cell.Value)
         If InStr(1, val, ",") Then
            val = Replace(val, ",", Chr(130))  <-- Handles the fact i have commas in the field
         End If

         If Not dict.Exists(val) Then
            dict.Add val, val
         End If

      Next cell
   End If

   'Return value as Variant Array
   UniqueValues = dict.Items
End Function

Questions:

*

*How do i account for Data-Validation changes?

*Can i use Data-Validation to Filter a Table?

*Since Pivot-Table is not a plausible option, due to the nature of the information, and if Data-Validation Filtering is not functionally possible, what alternative do i have?

On #3, i would like to not place a Drop-Down List, if at all possible.

A: Data-Validation is a way to restrict what kind of data can be entered in a cell (or a range of cells) http://office.microsoft.com/en-us/excel-help/apply-data-validation-to-cells-HP010072600.aspx
So your question is not specific to data validation. Your question seems to be about filtering a table based on the values entered in two cells at the top of that table (that happen to have data validation applied to them). Am I correct? If so: you are going to need to run a macro everytime those data validation cells are changed. You could make this automatic with Sub Worksheet_Change(ByVal Target As Range) or you could have an "update filters" button that would be slightly less "cool". Either way, you simply need to link in a macro with those two cells and have them update the filter on the table based on the values of those two cells.
Here is an example of a macro that would do something like I described:
Sub Worksheet_Change(ByVal Target As Range)

    ActiveSheet.AutoFilterMode = False
    Range("A3:H20").AutoFilter
    Range("A3:H20").AutoFilter Field:=2, Criteria1:=Range("A1").Text

End Sub

This is from: http://www.ozgrid.com/forum/showthread.php?t=85547
Hope this helps. Good Luck.


text:
Q: If statements in aspx files I have some code that essentially looks like this:

    <% if(Something) { %>

            This markup should not be output if Something==true.

            <units:MyUserControl runat="server"/>

    <% }
    else { %>
        <units:MyUserControl runat="server" />
    <% } %>

Depending on Something, one of them is hidden, and that is fine. But if I set break points in the user control, I notice it's being loaded twice (once for each of the controls above) and all it's logic is being run twice. I could of course control this with placeholders or multiviews, but the same thing seems to apply - OnLoad/Page_Load etc is run once for each control that is actually on the page.
EDIT:
The reason why im showing/hiding this is because I need to include some markup around the control if Something == true. I could wrap the "unique markup" itself in if-else before and after the control, but that just seems dirty for something that really should be as simple as I've imagined above. The user control itself should be exactly the same in both scenarios, sorry for the confusing property it had.
Is it just me, or is this just a really unintuitive interface? And is it actually possible to not load/execute a user control at all as long as it's on the page?

A: Since you have two controls on the page it will render them both. The if-check you create, only determines whether it's included in the output. The easiest way to prevent this is to change your code like this:

    <units:MyUserControl runat="server" SomeSetting="<%= Something %>" />

EDIT: Answer to edit in the original post:

    <% if(Something) { %>

            This markup should not be output if Something==true.

            <asp:placeholder id="phItemInDiv" runat="server" />

    <% }
    else { %>
        <asp:placeholder id="phItemOutsideDiv" runat="server" />
    <% } %>

MyUserControl ctrl = (MyUserControl)LoadControl("/pathtousercontrol.ascx")
if (something){
    phItemInDiv.Controls.Add(ctrl);
}
else{
    phItemOutsideDiv.Controls.Add(ctrl);
}

This way you will only have the user control emitted (and loaded) if Something is true

A: The best way, in my opinion, is to declare your user control once in the ASPX.
In the code behind, on PageLoad, apply the logic you see fit:
if(something)
    MyUserControl.SomeSettings = ...

If there is a problem in the chronology, do the above logic in PreLoad since it will fire before Page Load of the page and all of its related user controls.
EDIT:
You can put two different IDs on the user controls with Enabled = false.
In Page_load, set Enabled to one of them based on the logic you desire.


text:
Q: How to use the result of the previous row and sub it with the minimum of the result and given value enter image description here
Please find image of the table. column E and F are my resultant columns. I am new to R so need some help here. I am able to do it in excel not able to do it in R.
formula for column E: =IF(A2=A1,MIN(C2,F1),MIN(D2,C2))
formula for column F: =IF(A2=A1,F1-E2,D2-E2)
After 1st row of calculation which is simple. From next row It takes the result of previous row within a group(lag(remaining)-excess at batch level) and for column E it takes min(totalvalue,lag(remaining)) and continue this till it reaches the end of that group.
please guide me how to approach this in r
example data
       group totalQty totalValue Excess_at_national_level Excess.at.batch.level Remaining
1 3MCAVSB01A        1        987                     4935                   987      3948
2 3MCAVSB01A        1        987                     4935                   987      2961
3 3MCAVSB01A        1        987                     4935                   987      1974
4 3MCAVSB01A        1        987                     4935                   987       987
5 3MCAVSB01A        2       1974                     4935                   987         0
6 3MCAVSB01A        1        987                     4935                     0         0
7 3MCAVSB01A        1        987                     4935                     0         0

my_data <- data.frame(
          stringsAsFactors = FALSE,
                     group = c("3MCAVSB01A",
                               "3MCAVSB01A","3MCAVSB01A","3MCAVSB01A",
                               "3MCAVSB01A","3MCAVSB01A","3MCAVSB01A"),
                  totalQty = c(1L, 1L, 1L, 1L, 2L, 1L, 1L),
                totalValue = c(987L, 987L, 987L, 987L, 1974L, 987L, 987L),
  Excess_at_national_level = c(4935L, 4935L, 4935L, 4935L, 4935L, 4935L, 4935L),
     Excess.at.batch.level = c(987L, 987L, 987L, 987L, 987L, 0L, 0L),
                 Remaining = c(3948L, 2961L, 1974L, 987L, 0L, 0L, 0L)
)

A: While it is possible to create a loop that fills in the cells iteratively using very similar formulas, I think this would be a more idiomatic R approach, and would be much faster than a loop if you were working with larger data than Excel is built for.
library(dplyr)
my_data %>%
  group_by(group) %>%
  mutate(cuml_totalValue = cumsum(totalValue),
         Remaining_new = pmax(0, Excess_at_national_level - cuml_totalValue),
         Excess.at.batch.level_new = if_else(row_number() == 1, totalValue + 0,
                                             pmin(totalValue, lag(Remaining_new, default = 0)))) %>%
  ungroup()

Output (not that the last two new columns match the desired output)
  group    totalQty totalValue Excess_at_national_l… Excess.at.batch.le… Remaining cuml_totalValue Remaining_new Excess.at.batch.leve…
  <chr>       <int>      <int>                 <int>               <int>     <int>           <int>         <dbl>                 <dbl>
1 3MCAVSB…        1        987                  4935                 987      3948             987          3948                   987
2 3MCAVSB…        1        987                  4935                 987      2961            1974          2961                   987
3 3MCAVSB…        1        987                  4935                 987      1974            2961          1974                   987
4 3MCAVSB…        1        987                  4935                 987       987            3948           987                   987
5 3MCAVSB…        2       1974                  4935                 987         0            5922             0                   987
6 3MCAVSB…        1        987                  4935                   0         0            6909             0                     0
7 3MCAVSB…        1        987                  4935                   0         0            7896             0                     0


text:
Q: Auto update app desktop python with Pyqt5 and AWS RDS I want to launch a desktop application to run customer records for my sister at work,

*

*We are actually using local storage with sqlite3, but I will switch to AWS RDS sql

The application uses these packages:
from PyQt5 import uic,QtWidgets
from reportlab.pdfgen import canvas
import sqlite3, csv

Our biggest problem is the update in the application that for each new functionality needs a new installation,
The packages I want to send in the update can contain .ui files,
I try unsuccessfully to use:
-Updater4pyi
-PyUpdater
-Esky
Esky seemingly out of phase and do not support some configurations and I believe that the tools doesn't work correctly freezing the app to .exe because de .ui files,
What is the possible solution to this issue?
Thank you in advance
Setup.py
import esky.bdist_esky
from esky.bdist_esky import Executable as Executable_Esky
from cx_Freeze import setup, Executable
include_files = ['consulta2.ui']
setup(
    name = 'cadastro',
    version = '1.0',
    options = {
        'build_exe': {
            'packages': ['sqlite3','csv'],
            'excludes': ['tkinter','tcl','ttk'],
            'include_files': include_files,
            'include_msvcr': True,
        },
        'bdist_esky': {
            'freezer_module': 'cx_freeze',
        }
    },
    data_files = include_files,
    scripts = [
        Executable_Esky(
            "controle.py",
            gui_only = False,
            #icon = XPTO #Coloque um icone aqui se quiser ,
            ),
    ],
    executables = [Executable('controle.py',base='Win32GUI')]
    )

A: I want to execute continuos deploy,
With new functions and screens


text:
Q: When to use EventListenerList instead of a general collection of listeners When I learned how to fire events in Java, I became familiar with EventListenerList. When I create my own listeners, I write the listener so it extends EventListener, I store them in an EventListenerList, and my fire method would go through the event listeners like this:
protected void fireChangeOccurred(Change change) {
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length-2; i>=0; i-=2) {
        if (listeners[i]==ChangeListener.class) {
            ((ChangeListener)listeners[i+1]).changeOccurred(change);
        }
    }
}

Now I'm reviewing code that simply puts listeners into a HashMap (could be any collection), the listener interface does not extend EventListener, and the fire method looks like this:
protected void fireChangeOccurred(Change change) {
    for (ChangeListener listener : listeners) {
        listener.changeOccurred(change);
    }
}

What are the advantages of using EventListenerList instead of just maintaining my own list of listeners? Does it really only matter if the listeners are in a Swing component - does it matter for the Event Dispatch Thread?

A: EventListenerList has a method, getListeners(Class<T> t), specifically for the case where you are only interested in one event type.
Here's an example of how to use it:
protected void fireChangeOccurred(Change change) {
    for (ChangeListener listener:
         listenerList.getListeners(ChangeListener.class)) {
            listener.stateChanged(new ChangeEvent(this));
    }
}

If you choose to maintain your own collection of listeners, I recommend a CopyOnWriteArrayList.

A: To me, the major advantage of EventListenerList is if the containing class has (or may have) more than one type of listener. Many Swing components do; the one you're reviewing may not. The second example is shorter, but it has that implicit design limitation.

A: There is no huge advantages this days. Just small optimizations. Here is what JavaDocs says:

main benefits that this class provides
  are that it is relatively cheap in the
  case of no listeners, and it provides
  serialization for event-listener lists
  in a single place, as well as a degree
  of MT safety (when used correctly)

With modern JVMs and collections it really doesn't matter. But what you could do with your own implementation is provide the way to fire changes on EDT if you using Swing - that would be beneficial.


text:
Q: How to run command (cmd.exe) from inside emacs inside WSL? I now have emacs running under VcXsrv started when I open WSL (Unbuntu) on Windows 10.  And if I invoke "shell" it runs a bash shell fine.  However, I have a few command files I like to run.  In particular, I want to run the windows studio command line tools in a dos like environment, so first run "c:\program files (x86)\microsoft visual studion...\vsvars.bat" then run my "xyzzy.cmd" script that invokes nmake to build and run a legacy test program.
I tried running both directly from bash and they don't work (no surprise).  Then I tried invoking c:\windows...\cmd.exe as my shell interpreter in emacs but that doesn't seem to bring up a prompt.  It just hangs the shell.  I also tried the "cmdproxy.exe" which you use with emacs running directly on windows and that did no better.
Currently, I am running one emacs directly on windows (and when I invoke shell there it brings up command (using cmdproxy.exe) if I understand right).  In that I can run the scripts and that emacs will capture the output in a buffer, which I can then write to a file.  And I have the separate emacs I described above to do my real editing, and I read the file in there.  I'd rather have just one emacs, so I could use the emacs functions for switching buffers etc.
(By the way, I think I could do it under cygwin, but I'd rather use WSL.)
Here's what happens if I open a shell window in emacs and type the path to cmd.exe in it ($ is my shell prompt):
$ ls -l  /mnt/c/Windows/System32/cmd.exe
-r-xr-xr-x 2 cfclark cfclark 280064 Oct 28 23:03 /mnt/c/Windows/System32/cmd.exe
$ /mnt/c/Windows/System32/cmd.exe /?
[6n

At that point the shell is hung.
But you answer gave me an idea and I am closer:
$ /mnt/c/Windows/System32/cmd.exe /C z:/testbase/cpandrun.cmd -next -rev24 | cat
The system cannot find the path specified.
 +----------------------------------------------------------------------
  Setting up environment vars to build the tutorials with MVC++ 2019
 +----------------------------------------------------------------------
ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\cfclark\AppData\Roaming
...  (lots of environment variables omitted)
The system cannot find the path specified.
yxx1.exe does not exist
Too many of the files: yxx.exe and yxxdiff.cmd
         or yxx1.exe, yxx2.exe, and yxx.cmd.cmd
are missing from \yxx.24\bin.
The system cannot find the file specified.
The system cannot find the path specified.
Done!
The system cannot find the path specified.
Done!

The .cmd file expected to be run from a joined directory, so that it looks like the root of a partition, but that I can probably fix in the .cmd script.

A: To get this work from inside emacs (inside wsl), you need to add "| cat" to the line:
/mnt/c/Windows/System32/cmd.exe /c path_to_run.cmd | cat
This gets the output displayed in the emacs shell buffer and it will even wait for input that you type in the buffer.  At least it did for the "pause" command in my .cmd file.


text:
Q: In Plotly 3D Scatterplot, is there a way to freeze rotation of one axis? I am making a 3-D Scatterplot with plotly in Python 3 and the Z-axis represents time. I would like to freeze that so that, when the using clicks around to rotate the plot, it spins on that axis, but that axis stays up and down. I'm not sure if it's possible, but that would be a great feature.
As it is, the oldest points are at the top (this is a genetic tree) and the newest are at the bottom. However, it's very easy to get this turned when clicking around the plot to rotate and then the time axis is going left-to-right or diagonal or something and it's a bit disorienting, especially for people who are not used to looking at complex visuals like this (i.e. my intended audience).
A first draft example: https://plot.ly/~seth127/6
Any help is greatly appreciated!
Thanks,
Seth