text:
Q: document.querySelectorAll attribute value with carriage return I have a (assumed) poorly constructed HTML document and I'm trying to select a particular button, but the value of the attribute contains a carriage return.  Using Chrome, I can right click and copy the element HTML and paste into Notepad++ and then show special characters and the [CR][LF] is there.
I've tried this with no success:
document.querySelectorAll('button[title='Attribute<br>Value']')[0].click();

I've tried this with no success:
document.querySelectorAll('button[title='Attribute\nValue']')[0].click();

Thank you in advance.


text:
Q: Good idea to control LCD contrast using a microcontroller? In a commercial product, would it be a good idea to control LCD contrast using a microcontroller?
The LCD is to be installed in a vehicle and is to withstand temperature changes. I am concerned if the temperature changes would cause the LCD to be become unreadable.
The microcontroller i am using to control LCD does not have a DAC so I will be using a digital pot or external DAC.

A: In most examples I've seen the contrast control line has been adjusted automatically by a thermistor: -

This picture came from here - it describes how the circuit works and shows its output compared to the typical theoretical requirements for a typical LCD.
You can of course use a micro but you'd be copying most of the circuit above, reading the analogue value into the micro thru an ADC pin then outputting possibly a PWM signal that can be low pass filtered then fed to the LCD. Can't see the need to over complicate it really. Stick with "simple". Simple is usually best!
Here's another page that uses the same circuit. Here is a computational tool that can help - slightly different circuit but the tool, I'd imagine, will give you values.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get the number of links in a link list in Shopify Liquid In Shopify Liquid, how can I get the number of links within a link list for use in an if statement? For instance:
if [[ the count of `linklist.links` ]] > 6

A: Both linklist.links and link.links return an array. So you can use the size filter to get the number of links in your menu. You can use the dot notation of this filter in an if statement:
if linklist.links.size > 6


text:
Q: Some style effects that I don't know how they are named I am new in coding and i have a project to make and some minor problems I don't know how the circled things. I believe the top one can be made by croping the photo, but i want to find out if there's a html/css way and the margins that go after the content is a big mistery to me. If anyone would be so kind, i will appreciate just naming those things so i can do a little research by myself. The image is located at the following url : http://postimg.org/image/u4lzmixjj/ .
Thank you, Iosif

A: They can be constructed using a few superimposed shapes as demonstrated in this tutorial:
see: Pure CSS/HTML Tutorial
But more generally these are images created outside html/css, and resized and used as a template/background to place html objects onto.
see: Image/CSS/HTML Tutorial

A: This tool is fun to play around with. I would prefer images.


text:
Q: Google analytics goal fired on ajax success so the code I have is very basic and looks like this...
    jQuery(document).ajaxSuccess(function(e, xhr, opt){
        var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'xxxx']);

        _gaq.push(['_trackPageview', '/goal1']);
    });

I have this in my footer
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'xxxx']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl'  : 'http://www')  + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

And yet it does not work, any suggestions on how i could get this to work is appreciated, also I did a alert to make sure the ajax success works and it worked so i am 100% positive it should work.

A: you'll have to write it this way
var _gaq = window._gaq || [];

Else, _gaq is undefined at this point because of variable Hoisting in Javascript.

A: Eliminate these 2 lines:
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'xxxx']);

They're clearing the analytics object. You should just have the push in the success handler.


text:
Q: No codec available for format GIF in Ubuntu This is what Error i get from
8/27/2013 5:37:36 AM

Function Name : CreateCheckCodeImage

Message : No codec available for format:b96b3cb0-0728-11d3-9d7b-0000f81ef32e

This is CreateCheckCodeImage Function's Source Code
private void CreateCheckCodeImage(string checkCode)
    {
        if (checkCode == null || checkCode.Trim() == string.Empty)
        {
            return;
        }
        Bitmap bitmap = new Bitmap((int)Math.Ceiling((double)checkCode.Length * 12.5), 22);
        Graphics graphic = Graphics.FromImage(bitmap);
        try
        {
            Random random = new Random();
            graphic.Clear(Color.White);
            for (int i = 0; i < 25; i++)
            {
                int num = random.Next(bitmap.Width);
                int num1 = random.Next(bitmap.Width);
                int num2 = random.Next(bitmap.Height);
                int num3 = random.Next(bitmap.Height);
                graphic.DrawLine(new Pen(Color.Silver), num, num2, num1, num3);

                Font font = new Font("Arial", 12f, FontStyle.Bold | FontStyle.Italic);
                LinearGradientBrush linearGradientBrush = new LinearGradientBrush(new Rectangle(0, 0, bitmap.Width, bitmap.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                graphic.DrawString(checkCode, font, linearGradientBrush, 2f, 2f);
                for (int j = 0; j < 100; j++)
                {
                    int num4 = random.Next(bitmap.Width);
                    int num5 = random.Next(bitmap.Height);
                    bitmap.SetPixel(num4, num5, Color.FromArgb(random.Next()));
                }
                graphic.DrawRectangle(new Pen(Color.Silver), 0, 0, bitmap.Width - 1, bitmap.Height - 1);
                MemoryStream memoryStream = new MemoryStream();
                bitmap.Save(memoryStream, ImageFormat.Gif);
                base.Response.ClearContent();
                base.Response.ContentType = "image/Gif";
                base.Response.BinaryWrite(memoryStream.ToArray());
            }
        }
        catch (Exception exception)
        {
            CY.WriteError(CY.GetCurrentMethod(), exception.Message);
        }
        finally
        {
            graphic.Dispose();
            bitmap.Dispose();
        }
    }

i have found that the code problem are on the saving state.
bitmap.Save(memoryStream, ImageFormat.Gif);
base.Response.ClearContent();
base.Response.ContentType = "image/Gif";
base.Response.BinaryWrite(memoryStream.ToArray());

And i m using Ubuntu 12.04 and i have installed GDI+ and gif ext.
root@cy-VirtualBox:~/WebSite2# dpkg --get-selections | grep gif
libgif-dev                  install
libgif4                     install
root@cy-VirtualBox:~/WebSite2# dpkg --get-selections | grep jpeg
libjpeg-turbo8                  install
libjpeg8                    install
root@cy-VirtualBox:~/WebSite2# dpkg --get-selections | grep gdi
printer-driver-sag-gdi              install
root@cy-VirtualBox:~/WebSite2#

How to solve this problem? it is work fine in my window XP with IIS, but not in Ubuntu and Mono.
p/s: i can sure that file is gif file. because on IIS are working fine
and this is i checking on ubuntu command with gdk-pixbuf-query-loaders
"/usr/lib/x86_64-linux-gnu/gdk-pixbuf-2.0/2.10.0/loaders/libpixbufloader-gif.so"
"gif" 4 "gdk-pixbuf" "The GIF image format" "LGPL"
"image/gif" ""
"gif" ""
"GIF8" "" 100

How to install GIF Codec in Ubuntu?

A: Problem solved with changing the code with
 public static byte[] ImageToByte(Image img)
    {
        ImageConverter converter = new ImageConverter();
        return (byte[])converter.ConvertTo(img, typeof(byte[]));
    }

byte[] trytry = ImageToByte(bitmap);
                memoryStream.Write(trytry,0,trytry.Length );
                base.Response.ClearContent();
                base.Response.ContentType = "image/Gif";
                base.Response.BinaryWrite(memoryStream.ToArray());

No more using bitmap to save the file. so we don't need the codec. Anyway, anyone know how to install GIF codec in Ubuntu?


text:
Q: Проблемы с реализацией дружественной функции Есть примерно такой код:
comandSource.h
#pragma once

#include <iostream>
#include <math.h>
#include <assert.h>

using namespace std;

namespace mth
{
    template <typename T>
    class Vector
    {
    private:
        unsigned int length = 0;
        T* buffer = NULL;

    public:
        Vector();
        Vector(const Vector &r);
        Vector(int _length);
        ~Vector() { delete[] buffer; }

        void print();
        unsigned int len() { return length; }
        friend T dot_product(const Vector<T>& v1, const Vector<T>& v2)
        /*{
            T res = 0;
            assert(v1.length == v2.length && "The array lengths must be equal");

            for (unsigned int i = 0; i < v1.length; ++i)
                res += v1.buffer[i] * v2.buffer[i];

            return res;
        }*/;

        Vector operator = (const Vector& source);
        Vector operator + (const Vector& other);
        T& operator [] (const unsigned int index);
        friend Vector<T> operator-<>(const Vector<T>& v1, const Vector<T>& v2);
    };

    template <typename T>
    Vector<T>::Vector():
        Vector(1)
    {}

    template <typename T>
    Vector<T>::Vector(int _length):
        length(_length)
    {
        buffer = new T[length];
        for (unsigned int i = 0; i < length; i++)
            buffer[i] = 0;
    }

    template <typename T>
    Vector<T>::Vector(const Vector &arg):
        length(arg.length)
    {
        buffer = new T[length];
        for (unsigned int i = 0; i < length; i++)
            buffer[i] = arg.buffer[i];
    }

    template<typename T>
    void Vector<T>::print()
    {
        cout << "{ ";
        for (unsigned int i = 0; i < length; i++)
            cout << "'" << buffer[i] << "' ";
        cout << "}\n";
    }

    template<class T>
    T dot_product(const Vector<T>& v1, const Vector<T>& v2)
    {
        T res = 0;
        assert(v1.length != v2.length && "The arrays lengths must be equal");

        for (unsigned int i; i < v1.length; ++i)
            res += v1.buffer[i] * v2.buffer[i];

        return res;
    }

    template<typename T>
    Vector<T> Vector<T>::operator=(const Vector& source)
    {
        length = source.length;
        buffer = new T[length];

        for (unsigned int i = 0; i < length; i++)
            buffer[i] = source.buffer[i];

        return *this;
    }

    template <typename T>
    Vector<T> Vector<T>::operator+(const Vector& arg)
    {
        if (length != arg.length)
        {
            cout <<"[ERROR] vectors doesn't match by size"<<endl;
            exit(1);
        }

        Vector<T>temp(length);
        for (unsigned int i = 0; i < length; i++)
            temp.buffer[i] = buffer[i] + arg.buffer[i];

        return temp;
    }

    template<typename T>
    T& Vector<T>::operator[](const unsigned int index)
    {
        assert(index >= 0 && index < length && "Invalid array index");
        return buffer[index];
    }

    template<typename T>
    Vector<T> operator-(const Vector<T>& v1, const Vector<T>& v2)
    {
        assert(v1.length == v2.length && "The array lengths must be equal");

        Vector<T> temp(v1.length);
        for (unsigned int i = 0; i < v1.length; i++)
            temp.buffer[i] = v1.buffer[i] - v2.buffer[i];

        return temp;
    }
}

Пишу в main
mth::Vector<int> example(2);
    mth::Vector<int> example2(2);

    example[0]=1;
    example[1]=2;

    example2[0]=5;
    example2[1]=8;
    cout << mth::dot_product(example, example2) << endl;

Выдает ошибки типа такой, по одной на каждое обращение к члену.
mth::Vector<int>::length: невозможно обратиться к private член, объявленному в классе "mth::Vector<int>"

Как так, если функция дружественная? Причем, если определить функцию в теле класса, а не снаружи, то все работает.
И еще вопрос касательно синтаксиса c++, не создавать же для такой ерунды отдельную тему:
Почему для перегрузки через метод мы можем писать как
(const Vector& source)

так и
(const Vector<T>& source)

А для перегрузки через дружественную функцию работает только так?
(const Vector<T>& v1, const Vector<T>& v2)

Я про <T> в параметрах

A: Объявите в классе
template<typename U> friend
U dot_product(const Vector<U>& v1, const Vector<U>& v2);

вместо вашего
friend T dot_product(const Vector<T>& v1, const Vector<T>& v2);

У вас дружественная функция - шаблон...


text:
Q: Can't download images from google drive through node.js I am working on node.js and trying to access google drive and I can access the google drive images but I'm not able to download the images.
now i pasted the entire code. API returns the images we can log the names and file id. from there i trying to download that images.
      fs.createWriteStream(file.name);

i used this piece of code. but that downloaded image file format was not supported
logs in consloe:
File Name :  resume
File ID :  1wGthzSGg6axSL4unlz1tiVjzhRUPRCXA
File Name :  Remisha Resume.docx
File ID :  0BwgraHo4GmEXYUdvcFBQa2pjVlQ3dE9TWDB0a0VSOS1RRTZR
File Name :  IMG20181125154740.jpg
File ID :  1zGKGka51EnDuIl4wNqL5GogFNYZpzy_O
File Name :  IMG20181125185027.jpg
File ID :  1l5s2yR_5YMJcjFUQjkVFBC0f5PD0WSzw
File Name :  IMG20181125185037.jpg
File ID :  1vOxliIoztqUD_BbnjdXMBd9rpVTR4mvt
File Name :  IMG20181125155437.jpg
File ID :  10QXoAIjVvval0Xnlswf0bZmFYD2fqOK1
File Name :  IMG20181125185039.jpg
File ID :  1lcfUQJ--gnxxizqUHojKp2cX_RNpUx9c
File Name :  IMG20181125160713.jpg
File ID :  1bOpfM04Fo0fvY2Base8dSTRDkjesPz1i
File Name :  IMG20181125185043.jpg
File ID :  1Yk09Fe7nye3NwvYQNVDNSghozxiIFOtI
File Name :  IMG20181125165932.jpg
File ID :  1pe5vZFdmDBX0PSSllW2C2cLmYchAnS8G
saved images in disk is not supported format
 const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';

// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Google Drive API.
  authorize(JSON.parse(content), listFiles);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getAccessToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getAccessToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

/**
 * Lists the names and IDs of up to 10 files.
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listFiles(auth) {
  var drive = google.drive({version: 'v3', auth});
  drive.files.list({
    pageSize: 4,
    fields: 'nextPageToken, files(id, name)',
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    const files = res.data.files;
    if (files.length) {

      **files.map((file) => {
      //i am trying to download the image here. but that downloaded image
      // file format was not supported
      fs.createWriteStream(file.name)
        //console.log(`${file.name} (${file.id})`);
      });**

    } else {
      console.log('No files found.');
    }
  });


text:
Q: Collision detection through array Hi everyone  I started to write a little game with ball and bricks and have some problem with collision detection. Here is my code http://jsbin.com/ibufux/9 . I know that detection works though array, but I can't figure how I can apply it to my code.
Here is what i have tried:
 bricksCollision: function() {
        for (var i = 0; i < $bricks.length; i++) {
                if ($ball.t == $bricks[i].offset().top) {
                    $bricks[i].splice(i, 1);
                }
        }

Every bricks in game are generated by for loop and then goes to $bricks array. Every brick after generating receive top and left position and have position absolute. I have tried to check if $ball.t (it's properties of my ball object which detects ball top position) reach the bricks and than remove bricks.
Thanks for any help. I'm only start to learn JS that's why my code is
knotty.

A: First of all, let'stalk about some code errors

*

*$ball.t should be probably $ball.top

*you do not need to have $ as a prefix, for your code, it's simply a variable and you are calling $ball instead of ball witch results in assumption errors!

for those assumption errors here is what you are doing wrong:

*

*$ball is a dom element, not a jQuery element

*the same as $bricks

*$ball is an array

with those concluded from some console.log() let's try to fix the code:
the $ball should be called, as there's only one, by it's array element, as $ball[0] and because you have variables pointing to DOM elements and not jQuery elements, you need to wrap it in Jquery as:
if ( $($ball[0]).top === $($bricks[i]).offset().top ) { ...

a good idea not to get confused is only use $ in jQuery elements, prefixing it in a variable, does not make them a jQuery Element.
And everytime you see that you have an error such as "element x has no method y" always assume that you're calling a method from a DOM element, and not a jQuery element.

A: Now, that @balexandre has nicely explained some points about your code, lets examine how we can compute the collision.
Imagine 2 Ranges overlapping each other (Range a partly overlaps Range b)
[100     .|..      300]
          [200      ..|.      400]

The part overlapping is from | to | -> 200 to 300, so the size of the overlap is 100
If you look at the numbers, you notice, that the overlap could be seen like,

*

*Take the smaller number of the right side -> 300

*Take the greate number of the left side -> 200

*Subtract them from each other -> 300 - 200 = 100.

Lets take a look at 2 other situations. (Range b completely in Range a)
[50    ...    150]
    [75...125]

So the values we have are: Math.min (150,125) //125 for the end value and Math.max (50,75) // 75 for the start value, resulting in a value of 125 - 75 = 50 for the overlap
Let's take a look the last example (Range a not in Range b)
[50    ...    150]
                      [200    ...    300]

Using the above formula, yields the result Math.min (150 , 300 ) - Math.max (50,200) // -50 which absolutes' value is the gap between the 2 Ranges, 50
Now we can add a last condition, as you want to compute the collision, only values > 0 are of interest for us. Given this we can put it into one condition.
Math.min ((Brick["Right"],Ball["Right"]) - Math.max (Brick["Left"], Ball["Left"]) > 0)
Which will yield true if the elements' overlap and false if they don't.
Applying this to your code, we could compute the collision the following way
bricksCollision: function () {

    for (var i = 0; i < $bricks.length; i++) {
        var $brick = $($bricks[i]);
        var offset = $brick.offset();
        var brickBounds = [offset.left - field.l]; //brick left pos
        brickBounds[1] = brickBounds[0] + 40 //bricks right pos -> left pos + .bricks.width;
        var ballBounds = [ball.l]; //balls left pos
        ballBounds[1] = ballBounds[0] + 20 //balls right pos -> left pos + #ball.width;
        if (ball.t <= (offset.top + 20) && (Math.min(brickBounds[1], ballBounds[1]) - Math.max(brickBounds[0], ballBounds[0])) > 0) {

            $bricks[i].style.opacity = 0; //Make the brick opaque so it is not visible anymore
            $bricks.splice(i, 1) //remove the brick from the array -> splice on the array, not the element

            return true;
        }
    }
}

With this we could return true to the move function, when the Ball collides with a Brick.
But hey, we want it to Bounce off in the right direction, so we will face another problem.
So rather then returning a Boolean value whether the Brick collides or not, we could return a new direction in which the Ball will should move.
To be able to easily change only the x or the y part of the direction, we should use something like a vector.
To do so, we could use 2 Bits of an Integer, where the bit b0 stays for the x direction and the bit b1 for the y direction. Such that.
Dec        Bin       Direction

 0    ->    00    -> Down Left
             ^    -> Left
            ^     -> Down
 1    ->    01    -> Down Right
             ^    -> Right
            ^     -> Down
 2    ->    10    -> Up Left
             ^    -> Left
            ^     -> Up
 3    ->    11    -> Up Right
             ^    -> Right
            ^     -> Up

But to be able to change only a part of the direction, we need to pass the old direction to the collision function, and use bitwise & and | respectively to turn them off or on
Also we have to compute from which side the ball collides.
Fortunatly we have overlap calculation from before, which already uses all values we need, to compute the direction of collision.
If it comes frome the

*

*right

*

*Brick ["Right"] - Ball["Left"] has to be the same value as the overlap.

*left

*

*Ball ["Right"] - Brick["Left"] has to be the same value as the overlap.

If none of them are true, it has to either come from the

*

*bottom

*

*if Ball["Top"] is more than ( Brick["Top"] plus half of the Brick["height"] )

or else from the top.
To reduce the range where the condition, for the collision from the side, evaluates to true we can add another condition that the overlap has to be less than e.g ... && overlap < 2
So if it collides with the edge it doesn't always bounce of to the side.

So enough the talking, in code this could look like something like this.
bricksCollision: function (direction) {
    var newDirection = direction

    var ballBounds = [ball.l]; //balls left pos
    ballBounds[1] = ballBounds[0] + 20 //balls right pos -> left pos + #ball.width;

    for (var i = 0; i < $bricks.length; i++) {
        var $brick = $($bricks[i]);
        var offset = $brick.offset();

        var brickBounds = [offset.left - field.l]; //brick left pos
        brickBounds[1] = brickBounds[0] + 40 //bricks right pos -> left pos + .bricks.width;

        var overlap = Math.min(brickBounds[1], ballBounds[1]) - Math.max(brickBounds[0], ballBounds[0]);

        if (ball.t <= ((offset.top - field.t) + 20) && overlap > 0) {

            $bricks[i].style.opacity = 0; //Make the brick opaque so it is not visible anymore
            $bricks.splice(i, 1) //remove the brick from the array -> splice on the array, not the element

            if (ballBounds[1] - brickBounds[0] == overlap && overlap < 2) { //ball comes from the left side
                newDirection &= ~(1); //Turn the right bit off -> set x direction to left
            } else if (brickBounds[1] - ballBounds[0] == overlap && overlap < 2) { //ball comes from the right side
                newDirection |= 1; // Turn the right bit on -> set x direction to right;
            } else {
                if (ball.t > (offset.top + (20 / 2))) //Ball comes from downwards
                    newDirection &= ~(2) // Turn the left bit off -> set y direction to down;
                else //Ball comes from upwards
                    newDirection |= 2; // Turn the left bit on -> set y direction to up;
            }
            //console.log("Coming from: %s  Going to: %s", field.directionsLkp[direction], field.directionsLkp[newDirection], direction)
            return newDirection;
        }
    }
    return direction;
}

To get that to work, we should also change the moveXX functions, to use the new direction, returned.
But if we are going to get the new direction from the collision function anyway, we could move the complete collision detection to the function, to simplify our move functions.
But before that, we should have a look at the move functions and, add a lookup object to field which holds the numbers for the direction, to maintain readability.
var field = {
  directions: {
    uR : 3, // 11
    dR : 1, // 01
    dL : 0, // 00
    uL : 2  // 10

  },
  directionsLkp: [
    "dL","dR","uL","uR"
  ],
...
}

Now the move functions could then look like this,
    ballCondact: function () {
        var moves = [moveDl,moveDr,moveUl,moveUr]
        var timeout = 5;

        function moveUr() {
            var timer = setInterval(function () {
                $ball.css({
                    top: (ball.t--) + "px",
                    left: (ball.l++) + "px"
                })
                var newDirection = game.bricksCollision(field.directions.uR) //get the new direction from the collision function
                if (newDirection !== field.directions.uR) {
                    clearInterval(timer);
                    moves[newDirection](); //move in the new direction
                }
            }, timeout);
        }
...
}

Like this, the move function simply changes the direction if the collision function returns a direction which differs from the current one.
Now we can start moving the wall collisions to the collision function, to do this we could add another check at the beginning.
    bricksCollision: function (direction) {

      ...

      if (ball.t <= field.t)
        newDirection &= ~(2);  //Ball is at top, move down
      else if (ball.l <= 0)   //Ball is at the left, move right
        newDirection |= 1;
      else if (ball.t >= field.b - ball.height) //Ball is at the bottom, move up
        newDirection |= 2;
      else if (ball.l > field.width - ball.width) //Ball is at the right, move left
        newDirection &= ~(1);

      if (direction !== newDirection)
        return newDirection

      ...
}

Note, i left out the collision check for the platform, as the idea should be clear =)
Here is a Fiddle


text:
Q: Proof of an alternative min-max inequality The standard max-min inequality states that, for a bivariate function $f: X \times Y \to \mathbb{R}$,
$$
\sup_x \inf_y f(x,y) \le \inf_y \sup_x f(x,y). \qquad (*)
$$
I wonder whether the following property is also a max-min inequality:
$$
\sup_x \inf_y f(x,y) \le \inf_x \sup_y f(x,y), \qquad (**)
$$
since
$$
\begin{align}
\inf_{y_0} f(x,y_0) &\le f(x,y) &\quad \forall x\forall y\\
\sup_{x_0} \inf_{y_0} f(x_0,y_0) &\le \sup_{x_0} f(x_0,y) &\quad \forall y\\
\sup_{x_0} \inf_{y_0} f(x_0,y_0) &\le \inf_{y_0}\sup_{x_0} f(x_0,y_0).
\end{align}
$$
I am wondering whether (a) the proposed min-max inequality (**) is indeed correct based on the proof, and if so, (b) why it is not as widely used or referenced in minimax theory.

A: The proof you gave seems to conclude with (*) rather than (**).
(**) is false, as you can see for instance with $f(x,y)=x$.


text:
Q: An inequality about expectations This inequality is actually exercise 11, chapter 3.3 in Kai Lai CHUNG's A Course in Probability Theory:
If $X$ and $Y$ are independent, $E(|X|^p)<\infty$ for some $p\ge1$, and $E(Y)=0$, then $E(|X+Y|^p)\ge E(|X|^p)$.
As I understand, Fubini's theorem could be used here:
$$
E(|X+Y|^p)=\iint |x+y|^p \mu^2(dx,dy)=\int\left[\int |x+y|^p \mu_y(dy)\right]\mu_x(dx)
$$
Since $E(|X|^p)=\int |x|^p \mu_x(dx)$, it would be sufficient to prove:
$$
|x|^p \le \int |x+y|^p \mu_y(dy).
$$
However, I don't know how to use the $E(Y)=0$ condition here. Did I use Fubini's theorem properly?

A: Notice that
$$\int|x+y|^p\mu_Y(\mathrm dy)\geqslant \left|\int(x+y)\mu_Y(\mathrm dy)\right|^p,$$
by Jensen's inequality.


text:
Q: How do I get the absolute path of the chrome extensions directory? I'm writing an app that has full access to the file system and I want to be able to get the absolute path of my extension's directory. How would I do this?
My app has permissions to "<all_urls>", {"filesystem": [ "write" ]} and has the "allow access to file urls" checked.

A: If you mean the file system path, that differs on each operating system. You can find it by doing a file search for your extensions identifier.
If you want a chrome reference, you can use:
chrome.extension.getURL('');
You can also provide something in the string and it will give you the path that you would need to reference the file contained in your app.
Example:
chrome.extension.getURL('index.html');

Returns:
"chrome-extension://gbchcmhmhahfdphkhkmpfmihenigjmpp/index.html"


text:
Q: using redis in python flask to live send messages Below is a simple app to send mesg to the browser. if there is a new mesg from the redis channel it will be sent other wise send the last know value in a non-blocking way.
But i am doing something wrong. can someone please help me understand
from gevent import monkey, Greenlet
monkey.patch_all()

from flask import Flask,render_template,request,redirect,url_for,abort,session,Response,jsonify

app = Flask(__name__)

myglobaldict = {'somedata':''}

class RedisLiveData:
    def __init__(self, channel_name):
        self.channel_name = channel_name
        self.redis_conn = redis.Redis(host='localhost', port=6379, db=0)
        pubsub = self.redis_conn.pubsub()
        gevent.spawn(self.sub, pubsub)
    def sub(self,pubsub):
        pubsub.subscribe(self.channel_name)
        for message in pubsub.listen():
            gevent.spawn(process_rcvd_mesg, message['data'])

def process_rcvd_mesg(mesg):
    print "Received new message %s " % mesg
    myglobaldict['somedata'] = mesg

g = RedisLiveData("test_channel")

@app.route('/latestmessage')
def latestmessage():
    return Response(myglobaldict,mimetype="application/json")

if __name__ == '__main__':
    app.run()

on the javascript side i am just using a simple $.ajax get to view the messages.
but the client http://localhost:5000/latestmessage has the old message even after the redis update.

A: It should be the cache issue.
You can add a timestamp or a random number to the request http://localhost:5000/latestmessage?t=timestamp sent from the ajax.

A: I suggest you to use POST instead of GET as http method, you eliminate the caching problem and some annoying behaviour from browsers like chrome where the requests after the first will wait for the first to complete before being sent to the webserver.
If you want to keep the GET method then you can ask jquery to make the request non cache-able by the browser with the setting parameter cache
$.ajax(..., {cache:false})


text:
Q: I wish to merge records within a single table I have a single table with some duplicate records all bar one column.
e.g.
Field-A  Field-B  Field-C
abc      abc       Fred
abc      abc       Harry
def      cba       Bert
def      wxy       David
def      wxy       Peter
def      wxy       Larry
I wish to crunch this table down in T-SQL (SQL Server 2005 Stored Procedure) so that where columns Field-A and Field-B are the same across two or more rows the resulting table will have one row with Field-C as a merger of the others.
So, for the above example the resulting table will be..
Field-A  Field-B  Field-C
abc      abc       Fred, Harry
def      cba       Bert
def      wxy       David, Peter, Larry
Is there any way that this can be done?

A: SELECT DISTINCT
Field-A,
Field-B,
(SELECT Field-C + ',' from yourtable y WHERE y.Field-A=x.Field-A and y.Field-B=x.Field-B FOR XML PATH(''))
FROM yourtable x


text:
Q: Backup/export custom view automatically from Event Viewer How can I simply export or back-up a custom view from the event viewer? I do not want to export the regular Event logs, such as: System, Application, Security etc. But I want to export automatically my own whole custom view log with event id's.

A: Open up the Custom View properties, select Edit Filter and then switch to the XML tab and copy the filter.

You can now use the filter with PowerShell, like this:
[xml]$CustomView = @"
<QueryList>
  <Query Id="0" Path="Application">
    <Select Path="Application">*[System[(Level=2 or Level=3) and ( (EventID >= 1000 and EventID <= 2000) )]]</Select>
  </Query>
</QueryList>
"@

Get-WinEvent -FilterXML $CustomView | Export-CSV "C:\LogFiles\CustomView_$(Get-Date -format "yyyy-MM-DD").log"

Set up a scheduled task to run a script like the above every week


text:
Q: Proving a special case of the Squeeze Theorem
Prove that if $\{a_n\}\to0$, $$0\leqslant b_n\leqslant a_n \implies \{b_n\}\to0,$$where $a_n,b_n$ are infinite sequences and $n\in\mathbb{N}$.  Then, using the result $$\{a_n\}\to0\iff\{\left|a_n\right|\}\to0,$$prove that  if $\{a_n\}\to0$, $$0\leqslant \left|b_n\right|\leqslant a_n \implies \{b_n\}\to0$$

My Attempt
We begin by proving that if $\{a_n\}\to0$, $$0\leqslant b_n\leqslant a_n \implies \{b_n\}\to0.$$
So we have
$$\{a_n\}\to0\iff\forall \epsilon > 0 \exists N\in \mathbb{N}\text{ s.t. }\left|a_n\right|<\epsilon \forall n>N.$$Now $$0\leqslant b_n\leqslant a_n \implies  \left|b_n\right|\leqslant\left|a_n\right|$$and so$$\forall \epsilon > 0 \exists N\in \mathbb{N}\text{ s.t. }\left|b_n\right|\leqslant\left|a_n\right|<\epsilon \forall n>N\\\implies\forall \epsilon > 0 \exists N\in \mathbb{N}\text{ s.t. }\left|b_n\right|<\epsilon \forall n>N\\\iff \{b_n\}\to 0.$$
Now using the given result, we obtain that $\{\left|b_n\right|\}\to0$. After this point I am stuck so any hints will be appreciated.

What really confuses me about this question is that you can prove that if $\{a_n\}\to0$, $$0\leqslant \left|b_n\right|\leqslant a_n \implies \{b_n\}\to0$$ in a different order of the steps than the question requires. If you just write down the definition for $\{a_n\}$ being a null sequence and then use the fact that $0\leqslant \left|b_n\right|\leqslant a_n \implies \left|b_n\right|\leqslant\left|a_n\right|$ (since $\left|a_n\right|=a_n\geqslant0$) you can prove that $\{\left|b_n\right|\}\to 0$ and then using the given result it follows that $\{b_n\}\to 0$.
Again, any help will be appreciated.
Thank you in advance.

A: You have:
1) If $\{a_n\}\to0$, $0\leqslant b_n\leqslant a_n \implies \{b_n\}\to0$
2) $\{a_n\}\to0\iff\{\left|a_n\right|\}\to0$
so from (1), by replacing $b_n$ by $|b_n|$
3)  If $\{a_n\}\to0$, $0\leqslant |b_n| \leqslant a_n \implies \{|b_n|\}\to0$
and from (2), by replacing $a_n$ by $b_n$
4) $\{b_n\}\to0\iff\{\left|b_n\right|\}\to0$
and combining (3) and (4)
5) If $\{a_n\}\to0$, $0\leqslant |b_n| \leqslant a_n \implies \{b_n\}\to0$
quod erat demonstrandum.


text:
Q: Static page with bitnami I'm running bitnami with WordPress on an AWS Lightsail instance, and I'd like to host some static content without destroying WordPress.
/opt/bitnami/apache2/conf/bitnami/bitnami.conf has the VirtualHost DocumentRoot set to /opt/bitnami/apache2/htdocs, but adding a file like "demo.html" there doesn't work. It just reaches the WordPress "Page not found".
Is there an elegant way of doing this? Either a subfolder or subdomain?

A: I just had to put content into /opt/bitnami/apps/wordpress/htdocs/. The answer was already described here


text:
Q: connecting google firestore to php - grpc not found I am trying to connect php to firestore database following this repo https://github.com/googleapis/google-cloud-php-firestore.
Google Cloud Firestore for php requires grpc extension to be installed. I have installed grpc through pecl and it says it is perfectly installed. But whenever I try to run the code, it says firestore could not connect because grpc extension could not be found. I am attaching the screenshots of errors here. I have even added grpc to php.ini file, not sure why this error still pops up.Proof that grpc is installed image Error image

A: From php extensions check php_grpc, other wise it will be available for operations you do,
secondly from php.ini add
extension=php_grpc.dll

A: The link you've posted also features one relevant tutorial: Install gRPC for PHP.


text:
Q: An Objective-C class extension header - for what? I'm familiar with Objective-C class extensions in class main implementation file, but curious for what the new Xcode 4.4 "An Objective-C class extension header" file template is intended for?

A: Another reason is that a Class Extension Header file is useful in the case you are using Unit Test to test your class, putting class extension in a separate header file allow you to import the the header containing private methods into the implementation of the class that needs those private methods and into the unit test file that you use to test the class ...
This is a very good addition(the opportunity to test private methods in the unit test)  to Objective-C in my opinion, it is a thing that you can't do at the moment with JUnit in Java .

A: Class extensions must be implemented in the main @implementation block, but the declaration can be anywhere.
Extensions are used to add something to the class interface that you do not want to be public, and therefore cannot put in the public class declaration header.
Declaring the extension in the same file of the implementation, which you are familiar with, is used when the extension is only used by the class implementation itself.
Declaring the extension in a separate header, which is what the template is for, is useful when you develop a framework. The extension header will not be part of the set of public headers, but will be used internally by more than one implementation file of the framework.
You can think of it as private to framework instead of private to class.


text:
Q: Pass Value in Variable through Left Outer Join I want to pass variable in select query but getting below error.
Declare @ChangeComment as varchar(1000)
set @ChangeComment=''
select FirstName,LastName,SalesAmount,@ChangeComment='Test'
FROM [AdventureWorksDW2014].[dbo].[DimCustomer] a
left outer join [AdventureWorksDW2014].[dbo].[FactInternetSales] b on a.CustomerKey=b.CustomerKey

A: Just do this:
Declare @ChangeComment as varchar(1000)
set @ChangeComment='Test'

    select FirstName,LastName,SalesAmount,@ChangeComment as ChangeComment
    FROM [AdventureWorksDW2014].[dbo].[DimCustomer] a
    left outer join [AdventureWorksDW2014].[dbo].[FactInternetSales] b on a.CustomerKey=b.CustomerKey

You don't need to set @ChangeComment in the query because you decide of its value independently from the result of the query.

A: I think you want a dynamic SQL :
DECLARE @ChangeComment as varchar(1000)
DECLARE @sql nvarchar(max)

SET @ChangeComment='Test'

SET @sql = N'select FirstName,LastName,SalesAmount, '+@ChangeComment+'
FROM [AdventureWorksDW2014].[dbo].[DimCustomer] a LEFT OUTER JOIN
     [AdventureWorksDW2014].[dbo].[FactInternetSales] b on a.CustomerKey=b.CustomerKey'

PRINT @sql -- By using this you will see how SQL Statement looks at the run time before execution.

EXEC sp_executesql @sql;


text:
Q: jquery drag table row -> drop table column and row i have a table and i like to drag a tr and drop it to a td in a droppable row?
This is my code:
<button id='foo' onclick='clearConsole();'>clear console</button>

console log type thing

Units	Colum 1	Colum 2

Drag 1	1	2

Drag 2	1	2

Drag 3 	1	2

        Drop 1	1	2

        Drop 2	1	2

        Drop 3	1	2

    function clearConsole() {
        $('#console').html(" ");
    }
    function log(msg) {
        var oldmsg = $('#console').html();
        var newmsg = msg + "
" + oldmsg;
        $('#console').html(newmsg);
    }
    function dump(object) {
        var output = '';
        for (var property in object) {
            if ( object[property] !== null )
              output += property + ': ' + object[property] + '; ';
        }
        return output;
    }
    $('.droppableItem')
        .bind('dragenter dragover', false)
        .bind('drop', function(event){
            action($(this),event);
        });
    $('tr.DraggableThings2').bind('click', function () {
        $(this).toggleClass("selected");
    });
    function action(a,b) {
        for(var i = 0; i < a.length; i++)
            log(a[i].id + " made it to " + b.target.id);
    }

    $("tr.DraggableThings2").draggable({
          helper: function(){
              var selected = $('tr.DraggableThings2.selected');
            if (selected.length === 0) {
              selected = $(this).addClass('selected');
            }
            var container = $('
').attr('id', 'draggingContainer');
        container.append(selected.clone().removeClass("selected"));
        return container;
          }
     });

    $("tr.droppableItem").droppable({
        drop: function (event, ui) {
        action(ui.helper.children(), event);
        $('tr.DraggableThings2').removeClass('.selected');
        }
    });

    table {
        width:200px;
        border: brown 1px solid;
        padding:5px;
    }

        table tr {
            background-color:#FCF6CF;
        }

        .selected {
            background-color: #ECB;
        }
        #menu_table tr {
         width:200px;
         height:100px
        }

I have created a jsfiddle.
I have two questions:

*

*How can i highlite the td-cell where i am dragging to?

*How can i get the id of the tr which i dragged and the td where i dropped in my action-function?

For example: I like to drag "Drag 1" id="1" AND "Drag 2" id="2" and drop it to "Drop 2" Colum 2 where the id is "9-2".
In my action function i loop through the tr and get the id of each row by a[i].id That works. But b.target.id get the id of the tr element not the td element where i like to drop.
Maybe some of you can help.
Thanks


text:
Q: AWS ECS: how to change estimated EC2 instance warm-up in the scaling policy when using a capacity provider I use a capacity provider with an Auto Scaling Group (ASG). The scaling policy (AutoScaling-ECSManagedAutoScalingPlan) in the ASG is managed by the capacity provider.
Is it possible to change the estimated instance warm-up parameter in an ASG scaling policy? I tried to create a scaling policy in terraform but it's not used when the capacity provider is applied.

A: When using capacity provider, it takes over the ASG scaling policy and injects it's own.
You cannot change it when the provider is used


text:
Q: Why is this wrong? (C# Task ContinueWith) When I write the following code:
 Task<string> task = Task.Factory.StartNew<string>(() => "first task")
         .ContinueWith(t =>
                 {
                     Console.WriteLine(t.Result);
                     Console.WriteLine("second task");
                 });

That is wrong!
Then I change it to this:
 var  task = Task.Factory.StartNew<string>(() => "first task")
         .ContinueWith(t =>
                 {
                     Console.WriteLine(t.Result);
                     Console.WriteLine("second task");
                 });

Then everything is OK!
Why?
What is the different between "Task task"  and "var task"?

A: Your line of code returns a Task, not a Task<string> object, because you wrote ContinueWith, not ContinueWith<string>.
A tip that could help you in the future: when you replace a type by var in a variable declaration, you can move your mouse over the var keyword in Visual Studio, a pop-up will be shown with the actual type the var hides in your code.

A: task is a reference to the continuation and not the original task (a reference to the original task is passed as t to the continuation).
Since the continuation doesn't return anything its not a Task<string>. Obviously var handles this which is why your second example works and the first doesn't.


text:
Q: Expo-camera in React Native does not working correclty I am trying to access camera using React native app. I have copied all the code from official documentation. Every one has done the same including the official expo-docs https://docs.expo.io/versions/latest/sdk/camera/. My code to access the camera and take picture is
export default function Cameracontrol() {

        const [hasPermission, setHasPermission] = useState(null);
        const [type, setType] = useState(Camera.Constants.Type.back);

        async function takePicture() {

            console.log(this.camera)
            if (this.camera) {
                console.log('Pictactue Taken')
                let photo = await this.camera.takePictureAsync();
            }
            else {
                console.log('Caera Not Open');

            }
        }

        useEffect(() => {
            (async () => {
                const { status } = await Camera.requestPermissionsAsync();
                setHasPermission(status === 'granted');
            })();
        }, []);

        if (hasPermission === null) {
            return <View />;
        }
        if (hasPermission === false) {
            return <Text>No access to camera</Text>;
        }

        return (
            <View style={{ flex: 1 }}>
                <Camera style={{ flex: 1 }} type={type}
                ref={camera => this.camera = camera}
                >
                    <View
                        style={{
                            flex: 1,
                            backgroundColor: 'transparent',
                            flexDirection: 'row',
                        }}>

                        <View style={{ flex: 1, flexDirection: "row", justifyContent: "space-between", margin: 20 }}>

                            <TouchableOpacity

                                style={{
                                    alignSelf: 'flex-end',
                                    alignItems: 'center',
                                    backgroundColor: 'transparent',
                                }}
                                onPress={() => {
                                    setType(
                                        type === Camera.Constants.Type.back
                                            ? Camera.Constants.Type.front
                                            : Camera.Constants.Type.back
                                    );
                                }}>
                                <Ionicons
                                    name="ios-photos"
                                    style={{ color: "#fff", fontSize: 40 }}
                                />

                            </TouchableOpacity>
                            <TouchableOpacity
                                onPress={takePicture}
                                style={{
                                    alignSelf: 'flex-end',
                                    alignItems: 'center',
                                    backgroundColor: 'transparent',
                                }}>
                                <FontAwesome
                                    name="camera"
                                    style={{ color: "#fff", fontSize: 40 }}
                                />
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={{
                                    alignSelf: 'flex-end',
                                    alignItems: 'center',
                                    backgroundColor: 'transparent',
                                }}>
                                <MaterialCommunityIcons
                                    name="camera-switch"
                                    style={{ color: "#fff", fontSize: 40 }}
                                />
                            </TouchableOpacity>
                        </View>
                    </View>
                </Camera>
            </View>
        );
    }

I am experiencing the following error.
undefined is not an object (evaluating '_this.camera = camera')

this error is strongly related with the line
ref={camera => this.camera = camera}

By removing this line of code the error is also removing.
I would really really appreciate if some boy would help me with this.

A: You are in a functional component, not a class. Therefore, you cannot use this. Also, ref is not working like in classes.
You should use useRef : https://reactjs.org/docs/hooks-reference.html#useref

const inputEl=useRef(null);
<input ref={inputEl} type="text" />


text:
Q: Why does my website look different in Android emulator and on devices? I have built a website (no link for the moment). Said website is responsive and generally works well across most modern devices. It helps that the only really modern CSS features I am using are "transition," "transform," and "box-sizing." They are generally used in both prefixed and unprefixed forms.
Now, since I don't have a bazillion Android devices here, I thought I'd try the website in the Android Emulator offered with the Android SDK. At that point, I was a bit shocked to find that it was rather broken in everything below 4.3.
The issue seems to be that my menu implementation uses "transform: translate();" and that the Android stock browser apparently does not support this property.
I noticed that Google seems to use the same WebKit version (534.30) in the emulator images for Android 4.0, 4.1, 4.2, and 4.3. (If I can trust the user agent string.)
In the Android 4.4 and above emulator images,everything works as expected. Android 4.4 is also the first version to use a WebView implementation based on Chrome (version 33).
My own Android device (from Sony) runs on Android 4.3. According to the user agent string, the WebView's WebKit version there is also 534.30. I tried my website in a browser that uses WebView (Lightning browser from F-Droid). And it worked, including animations.
A colleague also opened my web page on his Samsung device with Android 4.0. It worked there too. (Haven't checked the user agent there.)
So, I thought, maybe Google updates WebView via Play Services. To the best of my understanding, that does not seem to be the case: I disabled the Play Services app, deleted its data, rebooted the phone. The page still worked.
What is going on? Are manufacturers wildly patching WebKit? Can I trust the WebKit version number at all?
(Updated to clarify the actual issue.)

A: Check the screensize. the emulators always have different screen size. that may be the issue.


text:
Q: How to make while loop work properly to correct given 2D array I'm trying to write a method that will take a two-dimensional array as an input, and return a new 2D array in which all the zeroes are removed from the array.
Also, if there is an element in the first array that has a value equal to the length of the second array, then it should be removed and all elements in the second array will be subtracted by 1.
The above process should be repeated for the second array also.
This is what I've written for the code implementation so far, but the code gets stuck in a loop and I don't think it's doing what it's supposed to do.
Note: When ArrayUtils is called, the Apache Lang library is being used, and this is the 2D array I inputted:
[[0, 0, 2, 2, 3, 4], [0, 0, 2, 2, 3, 4]]

Code:
public static int[][] removeTrivialCases(int[][] startingSums) {
    int[][] correctedSums = startingSums;

    int counter = 0;

    int numRows = correctedSums[0].length;
    int numCols = correctedSums[1].length;

    boolean zeroesExist = true;
    boolean valueEqualsDimension = true;

    boolean trivialCasesRemain = true;

    while(trivialCasesRemain) {
        for (int i = 0; i < correctedSums.length; i++) {
            for (int j = 0; j < correctedSums[i].length; j++) {
                if (correctedSums[i][j] == 0) {
                    trivialCasesRemain = true;
                    correctedSums[i] = ArrayUtils.removeElement(correctedSums[i], j);
                }

                for (int h = 0; h < correctedSums[i].length; h++) {
                    if (correctedSums[i][h] == 0) {
                        zeroesExist = true;
                    }
                }

            }
        }

        for (int i = 0; i < correctedSums[0].length; i++) {
            if (correctedSums[0][i] == numCols) {
                trivialCasesRemain = true;
                correctedSums[0] = ArrayUtils.removeElement(correctedSums[0], i);
                for (int j = 0; j < correctedSums[0].length; j++) {
                    correctedSums[0][j]--;
                }

                valueEqualsDimension = false;

                for (int h = 0; h < correctedSums[0].length; h++) {
                    if (correctedSums[0][h] == numCols) {
                        valueEqualsDimension = true;
                    }
                }
            }
        }

        for (int i = 0; i < correctedSums[1].length; i++) {
            if (correctedSums[1][i] == numRows) {
                trivialCasesRemain = true;
                correctedSums[1] = ArrayUtils.removeElement(correctedSums[1], i);
                for (int j = 0; j < correctedSums[1].length; j++) {
                    correctedSums[1][j]--;
                }
            }

            valueEqualsDimension = false;

            for (int h = 0; h < correctedSums[1].length; i++) {
                if (correctedSums[1][h] == numRows) {
                    valueEqualsDimension = true;
                }
            }
        }

        if (!zeroesExist || !valueEqualsDimension) {
            trivialCasesRemain = false;
        }
    }

    return correctedSums;
}

A: Regarding,

but the code gets stuck in a loop and I don't think it's doing what it's supposed to do.

Here:
for (int h = 0; h < correctedSums[1].length; i++) {

This loop will never end since h never changes within the loop. It should be:
for (int h = 0; h < correctedSums[1].length; h++) {

If you ran the code in a debugger, or used println's, you'd know what loop the code is stuck in, and this would allow you to inspect it immediately and correct it.


text:
Q: Why doesn't a standalone group_by in dplyr appear to do anything? I have a df like below;
set.seed(1)
No <- rep(seq(0,95,1),times=21)
AC <- rep(rep(c(78,110),each=1),times=length(No)/2)
AR <- rep(rep(c(256,320,384),each=2),times=length(No)/6)
AM <- rep(1,times=length(No))
DQ <- rep(rep(seq(0,15,1),each=6),times=3)
 V <- rep(seq(100,2100,100),each=96)
 R <- sort(replicate(3, sample(5000:6000,96)))

 df <- data.frame (No,AC,AR,AM,DQ,V,R)

head df

  No  AC  AR AM DQ   V    R
1  0  78 256  1  0 100 5012
2  1 110 256  1  0 100 5013
3  2  78 320  1  0 100 5022
4  3 110 320  1  0 100 5025
5  4  78 384  1  0 100 5034
6  5 110 384  1  0 100 5043

library(dplyr)
df %>% group_by(AR,AC,No)

when I try to group_by any one of names(df), nothing changes I get the same format output as df. Any idea to solve this?

A: dplyr is working as expected. The group_by command in itself doesn't output anything other than a grouped data frame:
str(df)
'data.frame':   2016 obs. of  7 variables:...

df1 <- df %>% group_by(AR,AC,No)
str(df1)
Classes 'grouped_df', 'tbl_df', 'tbl' and 'data.frame': 2016 obs. of  7 variables:....

If you want summary statistics (one output row per group), you can try the function summarise:
df2 <- df %>% group_by(AR,AC,No) %>%
              summarise(mean = mean(R), number = n())

Or you can try mutate (new column for each row) for example rank in each group:
df3 <- df %>% group_by(AR,AC,No) %>%
              arrange(R) %>%
              mutate(rank = row_number())

Take a look at the dplyr vignette


text:
Q: TO_NUMBER function inside AVG doesn't work I'm in trouble with TO_NUMBER ORACLE function.
The query
SELECT TO_NUMBER(varchar2_column)
FROM TABLE@ANOTHER_DB;

works, but if I put TO_NUMBER inside AVG, ORACLE returns the following error:

ORA-01722: invalid number ORA-02063: preceding line from ANOTHER_DB Position: 0

The query is the following:
SELECT AVG(TO_NUMBER(varchar2_column))
FROM TABLE@ANOTHER_DB;

Could someone help me? Thanks in advance

A: You can use to following query to get a working format mask for your data:
SELECT AVG(TO_NUMBER(varchar2_column, 'FM'||REGEXP_REPLACE(varchar2_column,'\d','0')))
  FROM TABLE@ANOTHER_DB;

That will produce a formatmask replacing all numerical characters with 0, which should work with all your data.


text:
Q: How to install PHPUnit with coverage logging via composer I'm trying to install PHPUnit via composer as in documentation it is said that PEAR installation will be gradually discontinued [1].
here is my composer.json after few hours of adding never-ending dependencies (plus a few other tools that I need):
    {
    "require": {
        "phpunit/phpunit": "4.0.*",
        "phpunit/dbunit": ">=1.2",
        "phpunit/php-invoker": "*",
        "phpunit/phpunit-selenium": ">=1.2",
        "phpunit/phpunit-story": "*",
        "phpunit/phpunit-mock-objects": "*",
        "phpunit/phpunit-story": "*",
        "phpunit/php-code-coverage": "2.*",
        "sebastian/diff": "*",
        "squizlabs/php_codesniffer": "*",
        "phploc/phploc": "*",
        "pdepend/pdepend" : "1.1.0",
        "phpmd/phpmd" : "1.4.*",
        "sebastian/phpcpd": "*",
        "theseer/phpdox": "dev-master"
    }
}

Here is info about my PHP (cli):
php -v
PHP 5.4.26 (cli) (built: Mar 15 2014 21:14:32)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies
    with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans

Now when trying to run some simple tests I receive some exceptions like this:
PHP Warning:  Uncaught exception 'PHPUnit_Framework_Error_Warning' with message 'require(classes/SebastianBergmann\Diff.php): failed to open stream: No such file or directory'

Are there some more dependencies that have to be included?
PS. I tried to just download phar file from the site, but it complains about some other files he cannot find.
UPDATE:
Here is my phpunit.xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true"
    bootstrap="tests/bootstrap.php"
         backupGlobals="false"
         backupStaticAttributes="false"
         strict="true"
         verbose="true">
    <testsuites>
        <testsuite name="Test Suite">
            <directory>./tests/</directory>
        </testsuite>
    </testsuites>

    <logging>
     <log type="coverage-html" target="build/coverage"/>
     <log type="coverage-clover" target="build/logs/clover.xml"/>
     <log type="junit" target="build/logs/junit.xml" logIncompleteSkipped="false"/>
    </logging>
</phpunit>

If I remove coverage logging part, everything works OK.
<log type="coverage-html" target="build/coverage"/>
<log type="coverage-clover" target="build/logs/clover.xml"/>

A: All what you need to do is to go into your project folder and add a composer.json file with the following content:
{
    "require-dev": {
        "phpunit/phpunit": "4.0.*"
   }
}

Then type $ composer install into your console window and composer will take care of all the dependencies. Composer creates a folder called vendor with a bin folder in it.
Calling $ vendor/bin/phpunit --version from within you project folder should print the current version of PHPUnit.
To use PHPUnit in your application you need to include the autoload file into your application:
require 'vendor/autoload.php';


text:
Q: Fork System Call when a process calls fork and it succeeds should it stay in the running state ? what about child whether it is brought to running state? Similarly when  process calls exec and it succeeds should it stay in the running state? Similarly when  process calls wait and it succeeds should it stay in the running state?

A: check:
man fork
man exec
man wait

Except lastest one, if fork/exec succeed, parent and child processes stay in RUNNING state.

A: When you fork, the child and parent are both running, and what defines whether or not a process actually has control of the CPU is your OS context switching between the different processes.
When you call exec and it succeeds, the entire program state is cleared and whatever you tried to exec will be the only thing that process does.


text:
Q: Error: implicit declaration of function [c] I included math.h library and used abs function and this error shows:
error: implicit declaration of function 'abs' [-Werror=implicit-function-declaration]
razlika=(abs(x3) / ((x1+x2)/2))*100;
^
cc1: some warnings being treated as errors

A: Include stdlib.h, not math.h.
Implicit declaration errors are generally due to missing/incorrect header files.


text:
Q: Social media icons not aligns Vertically instead of Horizontally Trying to have the sidebar icons show up horizontally; they show up as vertically for me.
I don't understand too well what I copy and pasted for the CSS to be honest, but I just wanted the list at the top like navbar and just a sidebar that I copy and paste on each page to always have social media links.
//Valentines Project if you couldn't tell//

@import url('https://fonts.googleapis.com/css?family=Roboto:700');

body {

    margin: 0;

    padding: 0;

    display: flex;

    justify-content: center;

    align-items: top center;

    height: auto;

    background: #333;

    font-family: 'Roboto', sans-serif;

}

ul {

    margin: 0;

    padding: 0;

    display: flex;

}

ul li {

    list-style: none;

    margin: 0 20px;

    transition: 0.5s;

}

ul li a {
    top: 10%;

    display: block;

    position: relative;

    text-decoration: none;

    padding: 5px;

    font-size: 25px;

    font-family: 'Roboto', sans-serif;

    font-weight: bold;

    color: #fff;

    text-transform: uppercase;

    transition: 0.5s;

}

ul:hover li a {

    transform: scale(1.5);

    opacity: .2;

    filter: blur(5px);

}

ul li a:hover {

    transform: scale(2);

    opacity: 1;

    filter: blur(0);

}

ul li a:before {

    content: '';

    position: absolute;

    top: 0;

    left: 0;

    width: 100%;

    height: 100%;

    background: #ff497c;

    transition: transform 0.5s;

    transform-origin: right;

    transform: scale(0);

    z-index: -1;

}

ul li a:hover:before {

    transition: transform 0.5s;

    transform-origin: left;

    transform: scaleX(1);

}

.sidebar {
    height: 50px;
    width: 0;
    position: fixed;
    z-index: 1;
    bottom: 0%;
}

#katy-fb {
    display: block;
    text-indent: -9999px;
    width: 50px;
    height: 50px;
    background: url(/doodle-bop/Assets/icons/katy-fb.png);
    background-size: 50px 50px;
}

#geo-fb {
    display: block;
    text-indent: -9999px;
    width: 50px;
    height: 50px;
    background: url(/doodle-bop/Assets/icons/geo-fb.png);
    background-size: 50px 50px;
}

#katy-twit {
    display: block;
    text-indent: -9999px;
    width: 50px;
    height: 50px;
    background: url(/doodle-bop/Assets/icons/katy-twit.png);
    background-size: 50px 50px;
}

#geo-twit {
    display: block;
    text-indent: -9999px;
    width: 50px;
    height: 50px;
    background: url(/doodle-bop/Assets/icons/geo-twit.png);
    background-size: 50px 50px;
}

#insta {
    display: block;
    text-indent: -9999px;
    width: 50px;
    height: 50px;
    background: url(/doodle-bop/Assets/icons/instagram.png);
    background-size: 50px 50px;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="/doodle-bop/Code/Styles/index.css">
  <title>Katy and Geo</title>

Photos

Videos

Other

what


text:
Q: What is the difference between filed of view and receptive field? guys. I want to know difference between  filed of view and receptive field. I know both things are similar, but what is the difference?

A: These are essentially different concepts. Field of view is a term related to the theory of optics, which means a solid angle with a vertex in the center of entrance pupil.
On the other hand, receptive field is a term of neural networks (convolutional/transformers), that means the size of the region in the input that produces the feature in the output (read more here).


text:
Q: How to AddItem with certain ContentTypeID using PowerShell I am using PowerShell to add 100 items which need to be of a specific ContentType.
(requirement)
Test my custom events receiver using powershell. The test is to create a list with a custom content type and then add 100 items of that content type.
(background)
I am trying to rule out the reasons for a strange behaviour in list workflows. Support team claims it is caused by our custom AddItem event, which I doubt since the receiver works fine on other lists. My addItem custom event receiver uses the ContentTypeID to initiate a corresponding workflow from another configuration list.
(previous searches)
This thread gives a different answer to my requirement, I don't want to change or update an-already-added item.
(question)  How do I add an item with my content type ID, or create the object with certain CT-ID before adding it because I want to test the "AddItem" event receiver. I created te following pseudocode to clarify what I am looking for:
#Pseudo-code:
get CSV "c:\file.csv"
connect to SPList "MyList"
for( file.Item Count )
 Create Item object i;
 set object i.ContentID = 0x001ETC #this!
 MyList.AddItem(object i);
End loop & close connection

A: The action my colleague suggested was to put the content type that I want to use as the default content type from list settings.
It is not exactly how I wanted it but it partially solved the question.


text:
Q: Smooth curved graphs in R I have a line graph which is currently displaying straight direct lines between each point on the graph.

Is there a way of making this so that the line is a smooth curve rather than simply 'join-the-dots'?
Here is the code extract I'm using to generate the above graph:
  plot(dataPlotsX,dataPlotsY, type="o", col="red", ann=FALSE)

  title(main=plotTitle, col.main="red", font.main=4)
  title(xlab="Time (hours)", col.lab="red")
  title(ylab="Discharge (m^3/s per 10mm)", col.lab="red")

For reference;
dataPlotsX = c(0, 1, 2, 3, 4, 5, 6)
dataPlotsY = c(0.000000, 5.772690, 17.303517, 12.981276,  2.886345,  0.000000,  0.000000)

Many thanks
Cobain

A: You can interpolate using a spline, e.g. :
# run this code just after your example
# to add a spline interpolating the points
s <- smooth.spline(dataPlotsX,dataPlotsY)
smooth <- predict(s,seq.int(from=min(dataPlotsX),to=max(dataPlotsX),length.out=10000))
lines(smooth,type="l",col='blue')


text:
Q: How to create a new array using the values of an array of objects within objects? (This is a similar but more complex scenario to a previous question)
I have an array originalArrayData like so:
originalArrayData = [{
    "16": {
        "id": 22,
        "grid_row_id": 5,
        "grid_col_id": 16,
        "data": "10",
        "created_at": "rertte",
        "error_mgs": null
    },
    "header": "BUTTERFLY HEADER",
    "id": 5
},
{
    "17": {
        "id": 31,
        "grid_row_id": 9,
        "grid_col_id": 16,
        "data": "14",
        "created_at": "rtyhtyjtdyj",
        "error_mgs": null
    },
    "header": "BUTTERFLY HEADER",
    "id": 6
},
{
    "18": {
        "id": 35,
        "grid_row_id": 9,
        "grid_col_id": 12,
        "data": "55",
        "created_at": "thrtuhrs",
        "error_mgs": null
    },
    "header": "PARROT HEADER",
    "id": 6
},
{
    "19": {
        "id": 36,
        "grid_row_id": 9,
        "grid_col_id": 12,
        "data": "31",
        "created_at": "rtyhtyjtdyj",
        "error_mgs": null
    },
    "header": "PARROT HEADER",
    "id": 7
},
{
    "20": {
        "id": 36,
        "grid_row_id": 9,
        "grid_col_id": 14,
        "data": "31",
        "created_at": "rtyhtyjtdyj",
        "error_mgs": null
    },
    "header": "OTHER HEADER",
    "id": 7
}...........

Let's say I have an array of ids (these numbers could be random and there isn't always 2. There could be 1, 3, etc. array items)
arrayOfIds: [16 , 12]

If the value of grid_col_id is present anywhere in the arrayOfIds, then for each object with the same grid_col_id, how can I create a new array with new keys made using the "header" value, and the value of those keys being the sum of the "data" value of all items with the same grid_col_id.
TARGET / EXPECTED OUTPUT:
[{ "butterflyheader": 24, "parrotheader": 86, "category": "None"}]
EXPLANATION: If you look at each item in originalArrayData (for this example there are 4, but there can be many), the first 2 items have the same grid_col_id and the same header. For those two, the "data" = "10" and "14", which when added results in 24. Hence, you have "butterflyheader": 24.
The same logic can be applied to parrotheader. All new keys are the lowercase and no space version of the original "header" of each object.
The item with header "OTHER HEADER" isn't included because its grid_col_id does not exist in arrayOfIds.
"category": "None" is always there and can be 'hard coded' into the new array.
To solve the issue, I have the following code:
        // creates an array of all of the innermost objects in the original array
        let tableDataFiltered = originalArrayData.map(item =>
            Object.values(item).filter(item => typeof item === "object")
        ).flat()

        // Retrieve all items with the relevant grid_col_id
        tableDataFiltered.filter(item => arrayOfIds.includes(item.grid_col_id))

        // Headers to use as keys
        let headersAsKeys = tableDataFiltered.forEach(item => {
            item.header.toLowerCase().split(' ').join(''))
        })

        Object.values(tableDataFiltered.reduce((acc, curr) => {
            acc[curr.category] = 'None';
            headersAsKeys.forEach(key => {
                acc[curr.category][key] += curr[key];
            })
            return acc;
        }, {}));

However, it results in headersAsKeys.forEach is not a function.
How can I achieve the target array? =>
[{ "butterflyheader": 24, "parrotheader": 86, "category": "None"}]

A: You can use Array#reduce with an object to store the data for each of the headers.

const arr=[{"16":{id:22,grid_row_id:5,grid_col_id:16,data:"10",created_at:"rertte",error_mgs:null},header:"BUTTERFLY HEADER",id:5},{"17":{id:31,grid_row_id:9,grid_col_id:16,data:"14",created_at:"rtyhtyjtdyj",error_mgs:null},header:"BUTTERFLY HEADER",id:6},{"18":{id:35,grid_row_id:9,grid_col_id:12,data:"55",created_at:"thrtuhrs",error_mgs:null},header:"PARROT HEADER",id:6},{"19":{id:36,grid_row_id:9,grid_col_id:12,data:"31",created_at:"rtyhtyjtdyj",error_mgs:null},header:"PARROT HEADER",id:7},{"20":{id:36,grid_row_id:9,grid_col_id:14,data:"31",created_at:"rtyhtyjtdyj",error_mgs:null},header:"OTHER HEADER",id:7}];
const ids = [16 , 12];
let res = [arr.reduce((acc, {header,id,...rest})=>{
  let [{grid_col_id, data}] = Object.values(rest);
  header = header.toLowerCase().replaceAll(' ', '');
  if(ids.includes(grid_col_id))
    acc[header] = (acc[header] || 0) + +data;
  return acc;
}, {category: "None"})];
console.log(res);

A: You only need a single loop for this. When looking at an object you're iterating over, check if the grid_col_id is the one you're looking for. If it is, add the data value to the output object (which starts with { category: 'none' }, summing with the previous value there if there is one. At the end, surround the resulting object in an array.

const originalArrayData=[{16:{id:22,grid_row_id:5,grid_col_id:16,data:"10",created_at:"rertte",error_mgs:null},header:"BUTTERFLY HEADER",id:5},{17:{id:31,grid_row_id:9,grid_col_id:16,data:"14",created_at:"rtyhtyjtdyj",error_mgs:null},header:"BUTTERFLY HEADER",id:6},{18:{id:35,grid_row_id:9,grid_col_id:12,data:"55",created_at:"thrtuhrs",error_mgs:null},header:"PARROT HEADER",id:6},{19:{id:36,grid_row_id:9,grid_col_id:12,data:"31",created_at:"rtyhtyjtdyj",error_mgs:null},header:"PARROT HEADER",id:7},{20:{id:36,grid_row_id:9,grid_col_id:14,data:"31",created_at:"rtyhtyjtdyj",error_mgs:null},header:"OTHER HEADER",id:7}];
const arrayOfIds = [16, 12];

const outputObj = { category: 'none' };
for (const { header, id, ...rest } of originalArrayData) {
  const { grid_col_id, data } = Object.values(rest)[0];
  if (arrayOfIds.includes(Number(grid_col_id))) {
    outputObj[header] = (outputObj[header] || 0) + Number(data);
  }
}
console.log([outputObj]);


text:
Q: How to configure ProGuard for an Android release build with Kotlin I added Kotlin 1.2.71 to my Android (Java) application project.
The project is configured for Java 8:
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

Here are the Kotlin changes:
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.71"

...
apply plugin: "kotlin-android"
apply plugin: "kotlin-android-extensions"
apply plugin: "kotlin-kapt"

...
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.2.71"
kapt "org.parceler:parceler:1.1.11"

I noticed that the release build with ProGuard fails. The build process outputs the following information:
Warning: kotlin.internal.jdk8.JDK8PlatformImplementations: can't find referenced
    method 'int start(java.lang.String)' in library class java.util.regex.Matcher
Warning: kotlin.internal.jdk8.JDK8PlatformImplementations: can't find referenced
    method 'int end(java.lang.String)' in library class java.util.regex.Matcher
Warning: kotlin.internal.jdk8.JDK8PlatformImplementations: can't find referenced
    method 'java.lang.String group(java.lang.String)' in library class java.util.regex.Matcher

Note: kotlin.internal.PlatformImplementationsKt: can't find dynamically
    referenced class kotlin.internal.JRE8PlatformImplementations
Note: kotlin.internal.PlatformImplementationsKt: can't find dynamically
    referenced class kotlin.internal.JRE7PlatformImplementations
Note: kotlin.jvm.internal.Reflection: can't find dynamically
    referenced class kotlin.reflect.jvm.internal.ReflectionFactoryImpl

Note: the configuration keeps the entry point
    'com.google.android.gms.flags.impl.FlagProviderImpl { void init(com.google.android.gms.dynamic.zzd); }',
    but not the descriptor class 'com.google.android.gms.dynamic.zzd'

Note: there were 1 unkept descriptor classes in kept class members.
      You should consider explicitly keeping the mentioned classes
      (using '-keep').
      (http://proguard.sourceforge.net/manual/troubleshooting.html#descriptorclass)
Note: there were 3 unresolved dynamic references to classes or interfaces.
      You should check if you need to specify additional program jars.
      (http://proguard.sourceforge.net/manual/troubleshooting.html#dynamicalclass)
Warning: there were 3 unresolved references to library class members.
         You probably need to update the library versions.
         (http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedlibraryclassmember)
Warning: Exception while processing task java.io.IOException: Please correct the above warnings first.
Thread(Tasks limiter_9): destruction

Kotlin does not require any special ProGuard rules as far as I saw. People recommend (post from 2015) to put just simply rules:
-dontwarn kotlin.**

Is this still the recommended solution?
Related

*

*Kotlin docs: Using Kotlin for Android Development

*StackOverflow: How to use Kotlin with Proguard

*ProGuard issue #182: Support Kotlin class files

*KT-7652: Specify and document Proguard rules for kotlin-reflect.jar

A: Looking at the actual warnings tells you it cannot find specific methods in the java standard library.
Referencing Matcher.end(String) shows that it is a method that is only available if your minSdk is 26. This was the SDK level when Java-8 support was added.
Simply put, you're trying to use the java8-level kotlin library with an android sdk that does not support it, leading to the errors you're observing.


text:
Q: Configure Sonatype Nexus 3 privileges for hosted docker registry namespace using wildcard I have installed Sonatype Nexus 3 OSS with Hosted Repository for Docker (Private Registry for Docker). I want to have couple of users, which will be able to pull/push docker images, based on their permissions.
First way, how I can do it - is to create several hosted repositories for docker and then via Securiy -> Privileges use repository-view with such approach configure permissions based on exact repository:
username:   repository name:    permission:

user1       docker-internal-1   nexus:repository-view-:docker:docker-internal-1:read
user2       docker-internal-1   nexus:repository-view-:docker:docker-internal-1:add

user3       docker-internal-2   nexus:repository-view-:docker:docker-internal-2:read
user4       docker-internal-2   nexus:repository-view-:docker:docker-internal-2:add

This approach works, but it requires having multiple hosted repositories for docker.
My question will be - is it somehow possible to have one singe hosted repository for docker and then configure permissions, based on docker repository namespace?
So let's say I have a repository called docker-internal and then I have such permissions:
username:   repository name:    permission:

user1       docker-internal     nexus:repository-view-:docker:docker-internal/namespace1:read
user2       docker-internal     nexus:repository-view-:docker:docker-internal/namespace1:add

user3       docker-internal     nexus:repository-view-:docker:docker-internal/namespace2:read
user4       docker-internal     nexus:repository-view-:docker:docker-internal/namespace2:add

Unfortunately in Nexus 3 documentation I haven't found a way how I can do it with repository-view permissions, cause they only allow you to specify repository name, but no namespace. Then there is such thing as wildcard, which is described in Sonatype docs like "Wildcard -> These are privileges that use patterns to group other privileges." So I've tried to create some regex pattern like this:
nexus:repository-view:docker:docker-internal/namespace1:read

And unfortunately it doesn't work.

A: We find a way to combine content-selectors and permission to support image level permissions.
First you have to create two content selectors:

*

*"docker-login-all" with the expression format=="docker" and path=~"/v2/". If you are support v1 protocol too, make sure to create another selector for it.

*"docker-foo-selector" with an expression matching the image you want to grant access. For example to select all the releases of foo/bar-linux, the expression is format=="docker" and path=~".*/foo/bar-linux/.*"
The first selector is very important, as without it you are not able to create a rule that allow your users to login.
Then create two privileges based on content-selectors:

*

*"docker-login-all-privilege" based on "Docker-login-all" applied on all the docker registries, with read grants. This will grant the ability to login via docker cli.

*"docker-foo-privilege" based on "docker-foo-selector" applied on all the docker registries, with read grants. This will allow your users to pull only foo/bar-linux images.

Then create a role with only the two privileges, and associate it to the users. It should work.
Please be aware of unexpected behaviours when using some commands: https://issues.sonatype.org/browse/NEXUS-12220

A: Based on answer from Sonatype Nexus support currently it's not possible to do it via wildcard and namespace in docker registry. So the only working way is to use separate docker repositories and repository-view permissions.


text:
Q: jQuery check if height of CSS class is less than 20% Okay so I have a question.
I simply want to make it so if a CSS class #hunger .bg is less than 20% height so height: 20%;
Then it needs to execute a jQuery code.
I have this now but this doesn't seem to work!
if ($('#hunger .bg').css('height') < '20%') {
    alert('Less than 20% hunger');
}

A: Your issue is that .css('height') is returning a value like "20px" which you can't perform mathematical operations on. Simply use .height() and find the percentage with simple math.

let height = $('#hunger .bg').height() / $('#hunger').height() * 100;

if(height < 20){
  alert("Less than 20% hunger");
}
#hunger {
  height:100px;
}

div {
  background-color:lightgray;
  height:19%;
}


text:
Q: How are typeof and sizeof Implemented I want to know how the typeof and sizeof keywords are implemented.
What if I want to implement my own 'x'of() expression like timeof(object) where object contains a DateTime as one of it's properties or something?

A: The short answer is no. typeof and sizeof are part of the C# language, and you cannot (directly) add expressions like them. The normal way of doing what you're asking would be to simply access the property:
DateTime time = myObject.SomeDateTimeProperty;

You could make a method to do this (although it wouldn't make sense for such a trivial thing). E.g. if you used an interface:
public interface ICreateTime
{
    DateTime CreateTime { get; }
}

public DateTime TimeOf(ICreateTime myObject)
{
    return myObject.CreateTime;
}

To be more specific: typeof and sizeof aren't implemented in the same way you implement methods. Instead, typeof translates to ldtoken [type] and call System.Type.GetTypeFromHandle IL instructions, and sizeof becomes a constant. E.g.
Type t = typeof(int);
int s = sizeof(int);

Compiles to:
IL_0001:  ldtoken     System.Int32
IL_0006:  call        System.Type.GetTypeFromHandle
IL_000B:  stloc.0     // t
IL_000C:  ldc.i4.4    // the constant 4, typed as a 4-byte integer
IL_000D:  stloc.1     // s

A: For your use case, I would not recommend doing this even if it was possible.
typeof and sizeof are both methods that return information relevant to the compiler.  Getting the time of an object is accessing a property and not a compiler attribute.
If you have an object that has a DateTime you should be accessing it using:
object.DateTimeProperty


text:
Q: Postfix refusing to find a new user I recently added a new user account to our LDAP directory. But somehow, Postfix just refuses to find that user when sending an email.
The accounts login works everywhere. Our Mailserver is a dedicated server with its own LDAP, but that's just mirroring the main LDAP. It doesn't look like an error with the LDAP. The directory for the emails is created and the entry does show up in the LDAP directory correctly. But when logging in the user only gets the message "no Mailbox selected" (Webmailer is SOGo). And with that not enough, when trying to send an email to that user it just doesn't work, neither from SOGo nor other clients.
The log says
Apr 30 12:03:14 mail postfix/smtpd[1355]: NOQUEUE: reject: RCPT from localhost[127.0.0.1]: 550 5.1.1 <user@domain.de(opens in new tab)>: Recipient address rejected: User unknown in local recipient table; from=<me@domain.de(opens in new tab)> to=<user@domain.de(opens in new tab)> proto=ESMTP helo=<localhost>

When disabling the local recipient table by adding the line "local_recipient_maps =" to the postfix main.cfg the error changes to
Mai 02 12:59:04 mail postfix/local[8909]: 1EA11100379: to=<user@domain.de(opens in new tab)>, relay=local, delay=0.22, delays=0.13/0.01/0/0.08, dsn=5.1.1, status=bounced (unknown user: "user")

I can't think of any solution for that problem. The only discussions about that topic I could find where because of misconfigurations. But the point is that there haven't been any changes to the configuration in a very long time. The only things that have changed are the packages that received updates. And that new user is currently the only one I know about having any problems.
About our setup:
Debian 10.4 running the nightly version of SOGo 4, postfix 3.4, slapd 2.4.47 and dovecot 2.3.4.1 with pigeonhole 0.5.4.
Postfix config:
# See /usr/share/postfix/main.cf.dist for a commented, more complete version
# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname
smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
biff = no
# appending .domain is the MUA's job.
append_dot_mydomain = no
# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h
readme_directory = /usr/share/doc/postfix
# TLS parameters
smtpd_tls_cert_file=/etc/ssl/certs/mail.domain.de.cert.pem
smtpd_tls_key_file=/etc/ssl/private/mail.domain.de.private.pem
smtp_tls_CAfile = /etc/ssl/certs/CA.crt
smtpd_tls_mandatory_ciphers = high
smtpd_tls_mandatory_exclude_ciphers = aNull, MD5
tls_high_cipherlist=!EDH+CAMELLIA:EDH+aRSA:EECDH+aRSA+AESGCM:EECDH+aRSA+SHA384:EECDH+aRSA+SHA256:EECDH:!CAMELLIA256:+AES256:!CAMELLIA128:+AES128:+SSLv3:!aNULL:!eNULL:!LOW:!3DES:!MD5:!EXP:!PSK:!DSS:!RC4:!SEED:!ECDSA:!CAMELLIA256-SHA:AES256-SHA:!CAMELLIA128-SHA:AES128-SHA
smtpd_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_tls_dh1024_param_file = /etc/ssl/private/dhparams.pem
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes
# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.
myhostname = mail.domain.de
alias_maps = hash:/etc/aliases
virtual_alias_maps = mysql:/etc/postfix/mysql-forwards.cf
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = domain.de, mail.domain.de
relayhost = smarthost.maindomain.de
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
message_size_limit = 67108864
mailbox_command = /usr/lib/dovecot/deliver -d $USER
recipient_delimiter = +
inet_interfaces = all
html_directory = /usr/share/doc/postfix/html
# Mailman config
relay_domains = lists.domain.de
transport_maps = hash:/etc/postfix/transport
mailman_destination_recipient_limit = 1
relay_recipient_maps = hash:/var/lib/mailman/data/virtual-mailman
# disable VRFY and EXPN command as per ITC recommendation
disable_vrfy_command = yes
# Older configurations combine relay control and spam control. To
# use this with Postfix ≥ 2.10 specify "smtpd_relay_restrictions=".
smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks
smtpd_relay_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination
# Configuration for rspamd
smtpd_milters=inet:localhost:11332
non_smtpd_milters = inet:localhost:11332
milter_protocol = 6
milter_mail_macros = i {mail_addr} {client_addr} {client_name} {auth_authen}
milter_default_action = accept

PS: if the postfix config seems strange, our mail server isn't directly connected to the internet. We get our emails from our organizations central servers over our organizations network.

A: ok, I've now found the (very strange) error. User authentication is done by pam through LDAP. For some reason nslcd refused to get the latest users from the local LDAP. Searching the LDAP directly showed everything as supposed, but an id username for the newest users just came back with "user not found". I checked the configration a few times and compared it to the configuration of our Desktop Linux machine. The only differences where that the Desktop machine was running Debian 11 testing instead of 10 stable and that it used the main LDAP.
I fixed the error by setting nslcd on the mail server to the main LDAP and then back to the local LDAP directory. It now finds the new users even with id username, sending them emails also is no problem. Very strange error but in the end easy to fix


text:
Q: Como percorrer Hashmap com subkeys? Como percorrer um HashMap que possui outro HashMap?
for (Map.Entry<Date,HashMap<String, Integer>> entrada : m.entrySet()) {
   // ....
}

A: Veja o código abaixo, exemplificando várias maneiras de fazer tal iteração:
Veja que você pode acessar os valores via chaves, valores ou recuperando-se valores através de chaves. Perceba aqui a grande flexibilidades de se usar Maps.
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class HashMapInHashMap {

    public static void main(String[] args) {

        // mapa representado o problema
        Map<Date, Map<String, Integer>> map = new HashMap<Date, Map<String, Integer>>();

        // iterando-se sobre cada entry
        for (Map.Entry<Date, Map<String, Integer>> entry : map.entrySet()) {

            // recupere a chave de cada entry
            Date key = entry.getKey();

            // recupera o valor da entry atual, que é um mapa
            Map<String, Integer> value = entry.getValue();

            // itere itere sobre todas as chaves do mapa a cima
            for (String keyInner : value.keySet()) {

            }

            // itere sobre todos os valores do mapa a cima
            for (Integer valueInnter : value.values()) {

            }
        }

        // uma maneira mais fácil é iterar sobre cada chave e valor, dos mapa referente ao valor
        for (Map<String, Integer> innerMap : map.values()) {
            // itere sobre cada chave
            for (String key : innerMap.keySet()) {

            }

            // itere sobre cada valor
            for (Integer value : innerMap.values()) {

            }
        }

        // agora recupera o valor baseado na chave corrente
        for (Date key : map.keySet()) {

            // recupere o valor
            Map<String, Integer> value = map.get(key);

            // itere sobre o mapa
            for (String keyInner : value.keySet()) {
                Integer valueInner = value.get(keyInner);
            }
        }
    }
}


text:
Q: jquery/javascript: How do I remove the 'active' class from all the children of a parent element? I have a few lists, something like so:

...

...

...

...

...

...

When one of the  elements is clicked, I want to clear all the
 elements of its list of the 'active' class. I've been fiddling around with .parent(), .children(), and .removeClass('active') but I think I'm totally missing something because I can't get it to work. Can anyone give me a hand? This is the beginning of the script:
$(document).ready(function() {
    $(".divclass ul li a").click(function() { ... }}

where .divclass is the class of the div that contains the unordered lists.

A: Remove all
$(".divclass ul li a").click(function() {
    $(this).closest('.divclass').find('li').removeClass('active');
}};

Remove only form the same list
$(".divclass ul li a").click(function() {
    $(this).closest('ul').find('li').removeClass('active');
}};

If you also want to add the class active to the li parent of the a clicked:
$(".divclass ul li a").click(function() {
    $(this).parent().addClass('active').siblings().removeClass('active');
}};

A: You can use:
 $("#menu a").click(function() {
    //to remove class active from li elements
    $(this).closest('ul').find('.active').removeClass('active');

    //to remove li with active class
    $(this).closest('ul').find('.active').remove();
 });


text:
Q: How to dynamically add DefinitionSeries to a StackedAreaChart in Silverlight? I want to code sth where I can dynamically add a new random-value-series to a Silverlight StackedAreaChart. That is, everytime the user clicks a button at runtime I want a new value series in a different color added to the programs main StackedAreaChart.
I cannot find any good examples of this on the internet except for the Silverlight Visualization demos (Stacked Area example).
The programmer made it static with three predefined series, but i want it to be dynamic and cant figure it out :-/
I spent 2 weeks on this now, any help will be greatly appreciated since I'm new to this stuff :(
Thx ppl! :)

A: Finally I have found time to create an example of dynamic random series.
XAML code is simple: one button and the chart.
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="40" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <Button Content="Add random series" Click="AddSeries_Click" HorizontalAlignment="Center" />
    <chart:Chart x:Name="chart" Grid.Row="1">
        <chart:StackedAreaSeries />
    </chart:Chart>
</Grid>

Code-behind looks rather complex, but majority of code is used to generate random data. The main code is in the AddSeries_Click method.
public partial class MainPage : UserControl
{
    private string[] categories = new[] { "Apples", "Oranges", "Bananas", "Lemons" };
    private Random random = new Random((int)DateTime.Now.Ticks);
    private int lastSeriesYear = 2011;

    public MainPage()
    {
        InitializeComponent();
    }

    public class ChartItem
    {
        public string Title { get; set; }
        public double Value { get; set; }
    }

    private void AddSeries_Click(object sender, RoutedEventArgs e)
    {
        var sd = new SeriesDefinition();
        sd.ItemsSource = categories.Select(c => new ChartItem { Title = c, Value = random.Next(30, 35) }).ToList();
        sd.Title = (lastSeriesYear--).ToString();
        sd.IndependentValuePath = "Title";
        sd.DependentValuePath = "Value";

        ((StackedAreaSeries)this.chart.Series[0]).SeriesDefinitions.Add(sd);
    }
}

If you rather like to work with view models and observable collections than with code-behind, I have the extended chart class which allows data binding to a list of series. But it requires much more code, so let there be this example with code-behind.


text:
Q: Why is this MergeSort implementation not stable? I found several mergesort algorithms in the net and pasted together this one. it carries the indices along to keep the information where the element was before. but it turns out, that when i feed in an array which has the same value at each element the indices are shuffled. do i need to use another merge method?
procedure TMSortNode.MergeSort(values, indices: TMValueArrayPtr; L, R: Integer);
var
  i, j, k, m : Integer;

begin
If (l < r) Then
begin
m:= (r+l) div 2;

MergeSort(values, indices, l, m );
MergeSort(values, indices, m+1, r );

For i:= l To m Do
begin
  FValueBuffer[i]:= values^[i];
  FIndexBuffer[i]:= indices^[i];
end;
i:= l;

For j:= m+1 To r Do
begin
  FValueBuffer[r+m+1-j]:= values^[j];
  FIndexBuffer[r+m+1-j]:= indices^[j];
end;
j:= r;

For k:= l To r Do
begin
  If (FValueBuffer[i] <= FValueBuffer[j]) Then
  begin
    values^[k]:= FValueBuffer[i];
    indices^[k]:= FIndexBuffer[i];
    inc(i);
  end
  else
  begin
    values^[k]:= FValueBuffer[j];
    indices^[k]:= FIndexBuffer[j];
    dec(j);
     end;
    end;
  end;
end;

EDIT:
this is the correct stable merge part:
length := r-l+1;
For i:= 0 To length-1 Do
begin
  FValueBuffer[i]:= values^[l+i];
  FIndexBuffer[i]:= indices^[l+i];
end;

j := 0;
k := m-l+1;

for i := 0 to length-1 do
if k < length then
  begin
  if j <= m-l then
  begin
    if FValueBuffer[j] > FValueBuffer[k] then begin
      values^[l+i] := FValueBuffer[k];
      indices^[l+i] := FIndexBuffer[k];
      inc(k)
    end else begin
      values^[l+i] := FValueBuffer[j];
      indices^[l+i] := FIndexBuffer[j];
      inc(j);
    end;
  end
  else
  begin //only upper Entrys left
    values^[i+l] := FValueBuffer[k];
    indices^[i+l] := FIndexBuffer[k];
    inc(k);
  end;
end else begin //only superior Entrys left
  values^[i+l] := FValueBuffer[j];
  indices^[i+l] := FIndexBuffer[j];
  inc(j);
end;

A: try
If (FValueBuffer[i] <= FValueBuffer[j]) Then ...
(to keep stability, we have not to exchange equal items)
Edit:
Another issue: standard merging looks like:

*

*while both left and right part contains untreated items, move the smallest item to the new place

*move the rest of untreated part (if exists)

Example:
procedure Merge(var c, d: array of Integer; l, m, r: Integer);
 var
   i, j, k: Integer;
 begin
   i := l;
   j := m;
   k := l;
   while (i < m) and (j <= r) do
     if c[i] <= c[j] then begin
       d[k] := c[i];
       Inc(k);
       Inc(i);
     end
     else begin
       d[k] := c[j];
       Inc(k);
       Inc(j);
     end;
   while i < m do begin
     d[k] := c[i];
     Inc(k);
     Inc(i);
   end;
   while k <= r do begin
     d[k] := c[j];
     Inc(k);
     Inc(j);
   end;
  end;

But your first variant goes beyond the left-right part border (to avoid this, one could use sentinel item(s) with extra value - it takes additional efforts and place).
It seems that this problem is taken into account in the second version