text:
Q: Form sends only one file/image I have a problem with multiple image upload. I've been trying multiple options but nothing seems to work.
Front-end Code

Here is my PUG
form#new-shortcut.form-horizontal.elegant-color-dark(action=`/themes/new?_csrf=${csrfToken}` method='POST' enctype='multipart/form-data')
          input#csrf(type='hidden' name='_csrf' value=`${csrfToken}`)
          input#files.file_updload(type='file' multiple='multiple' accept='image/*' name='photosArr[]')

Which is rendered to this
<form class="form-horizontal elegant-color-dark" id="new-shortcut" action="/themes/new?_csrf=undefined" method="POST" enctype="multipart/form-data">
<input id="csrf" type="hidden" name="_csrf" value="undefined" />
<input class="file_updload" id="files" type="file" multiple="multiple" accept="image/*" name="photosArr[]" />
</form>

This is and output from chrome console when checking if files are added.
document.querySelector('#files').files
> FileList {0: File, 1: File, length: 2}

Server Code
function formidablePromise(req, opts) {
  return new Promise(((resolve, reject) => {
    const form = new formidable.IncomingForm(opts);
    form.parse(req, (err, fields, files) => {
      if (err) return reject(err);
      resolve({ fields, files });
    });
  }));
}

router.post('/themes/new', csrfProtection, async (req, res, next) => {
  console.log('reached');
  const form = await formidablePromise(req);
  const filePaths = [];
  let base64img;
  try {
    const promises = [];
    console.log(form.files)
    Object.keys(form.files).forEach((key) => {
      console.log(form.files[key].path);
      const filePath = `${process.env.PC_DIR}${nanoid()}${form.files[key].name}`;
      filePaths.push(filePath);
      promises.push(fs.move(form.files[key].path, `${filePath}`));
    });
    await Promise.all(promises);
    console.log(filePaths);
    console.log(form.fields)
    // filepath = `/Users/lucjangrzesik/Desktop/themegrams/public/img/${nanoid()}${form.files.file.name}`;
    // await fs.move(form.files.file.path, filepath);
    console.log('success!');
  } catch (err) {
    return console.error(err);
  }

  try {
    const promises = [];
    for (let index = 0; index < filePaths.length; index++) {
      promises.push(bucket.upload(filePaths[index]));
    }
    const data = await Promise.all(promises);
    console.log(data);
  } catch (err) {
    console.error('ERROR:', err);
  }

  try {
    const promises = [];
    for (let index = 0; index < filePaths.length; index++) {
      promises.push(image2base64(filePaths[index]));
    }
    const data = await Promise.all(promises);
    const imgurPromises = [];
    for (let index = 0; index < data.length; index++) {
      imgurPromises.push(imgur.uploadBase64(data[index]));
    }
    const images = await Promise.all(imgurPromises);
    const links = [];
    images.forEach((e) => {
      links.push(e.data.link);
    });
    console.log(links)
    res.redirect('/');
    // await fs.remove(filepath);
  } catch (error) {
    console.log(error);
    return res.redirect('back');
  }
});

console.log(form.files) return
form is receiving only one file.
{
  'photosArr[]': File {
    _events: [Object: null prototype] {},
    _eventsCount: 0,
    _maxListeners: undefined,
    size: 427923,
    path: 'C:\\Users\\Lucien\\AppData\\Local\\Temp\\upload_0f6dc87e49472d18c12a8d0686bb6215',
    name: 'BANDEAU SOLDES CDO outlet 1800.png',
    type: 'image/png',
    hash: null,
    lastModifiedDate: 2020-01-13T13:24:06.281Z,
    _writeStream: WriteStream {
      _writableState: [WritableState],
      writable: false,
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      path: 'C:\\Users\\Lucien\\AppData\\Local\\Temp\\upload_0f6dc87e49472d18c12a8d0686bb6215',
      fd: null,
      flags: 'w',
      mode: 438,
      start: undefined,
      autoClose: true,
      pos: undefined,
      bytesWritten: 427923,
      closed: false
    }
  }
}

I'm using node-formidable to retrieve the form.

Form sent with ajax
When I'm sending the form with ajax server receives all the files.
Here is ajax code
const csrf = document.querySelector('#csrf').getAttribute('value');
const headers = {
  'X-Requested-With': 'XMLHttpRequest',
  'CSRF-Token': csrf,
};
const fileInput = document.querySelector('#file');
const imagesDiv = document.querySelector('#images>.row.d-flex.justify-content-around');

async function sendData(data) {
  const output = document.getElementById('imgThumbnailPreview');
  output.innerHTML = '';
  const formData = new FormData();
  // - formData.append('file', fileInput.files[0]);
  for (const name in data) {
    formData.append(name, data[name]);
  }
  console.log(formData);
  for (let i = 0; i < fileInput.files.length; i += 1) {
    const imageDiv = document.createElement('div');
    imageDiv.classList.add('col-12', 'col-sm-6', 'col-md-4', 'col-lg-3', 'mt-2');
    const elem = document.createElement('div');
    elem.classList.add('card-loader', 'card-loader--tabs');
    imageDiv.append(elem);
    imagesDiv.append(imageDiv);
  }
  fileInput.value = '';
  const response = await fetch('http://localhost:3000/upload', {
    method: 'POST',
    headers,
    body: formData,
  });
  const imagesArr = document.querySelectorAll('.card-loader.card-loader--tabs');
  const imagesUrl = await response.json();
  for (let index = 0; index < imagesUrl.links.length; index++) {
    imagesArr[index].parentNode.innerHTML = `<img class='img-fluid' src='${imagesUrl.links[index]}'/><input name='images[${index}]' type="hidden" value="${imagesUrl.links[index]}">`
  }
}

A: So the problem was not with the form but with the formidable configuration; I just needed to add form.multiples = true; to the formidablePromise function.
function formidablePromise(req, opts) {
  return new Promise(((resolve, reject) => {
    const form = new formidable.IncomingForm(opts);
    form.multiples = true;
    form.parse(req, (err, fields, files) => {
      if (err) return reject(err);
      resolve({ fields, files });
    });
  }));
}


text:
Q: what is the aim to declare $name in each controller I am leaning cakePHP.
I noticed that a variable $name is declared in each Controller.
What is its purpose?
Is it referring to the name of table Sites?
<?php
class SitesController extends AppController {
var $name = 'Sites';
...
}
?>

If yes,
Can users refer to more than one table like this?
var $name = 'Sites', 'Sites2', 'Sites3';

A: It's used for compatibility with PHP4. You can safely ignore it.
No, it;s not referring to the name of the table... It sometimes imply that controller named FooController will use model named Foo, but it's not always true.
And no, you can't specify model names like that. Models to be loaded are listed in $uses property:
public $uses = array ('Sites', 'Sites2', 'Sites3');

A: No.  $name is for PHP4 compatibility.  PHP4 didn't have complete object orientated features, so it was sometimes unable to derive the name of a model from the controller class.  Setting $name just made sure that wouldn't happen -- that the name of the model was explicit, so this problem wouldn't happen.
AFAIK it's totally unnecessary if you're using PHP5 and never intend to use PHP4 with your app.

A: As far as I understand this is a legacy convention of CakePHP, mostly it works without it. Cake used this property to get Controller names right. Not that a big deal, just go with it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SonataAdminBundle with sonata_type_collection and upload image In Sonata Admin, I want to use upload and preview picture file in sonata_type_collection.
In my Admin/ItemAdmin.php :
class ItemAdmin extends Admin
{

    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('title')
            ->with('Photos')
            ->add('pictures', 'sonata_type_collection', array(
                'label' => 'Pictures',
                'by_reference' => false,
                'required' => false,
                ), array(
                'edit' => 'inline',
                'inline' => 'table',
                'sortable' => 'id'
            ))
            ->end()
        ;
    }

In my Admin/ItemPictureAdmin.php :
class ItemPictureAdmin extends Admin {

    protected function configureFormFields(FormMapper $formMapper) {
        $obj = $this->getSubject();

        $formBuilder = $formMapper->getFormBuilder();

        if(is_object($obj) && $obj->getPicture())
        {
            $formMapper
            ->add('picturePreview', 'image_preview', array(
                'required' => false,
                'property_path' => false,
                'upload_dir' => '/uploads/picture/',
                'file_name' => $obj->getPicture()
            ));
        }
        $formMapper->add('pictureFile', 'file', array('label' => 'Pic'));
    }

The type "image_preview" is a new type I created with a simple template twig to show the picture.
Preview : http://i.stack.imgur.com/AC0ih.png
Issue 1 : I have two pictures recorded in database with two differents picture files but in the list, it displays the first only.
Issue 2 : It's not possible to update a picture... I have to delete the record and upload a new file again.

A: I bumped on the Issue 1 myself. I tried every possible solution that I found, but nothing worked. I tried some of my solutions and one was good.
What I did:

*

*I saved in the session the index of the child entity (in your case ItemPictureAdmin) and when I needed an entity, I would take the index from session and get the element with that index from the list in the parent entity.

*First I save in session index 0 and in ItemPictureAdmin I access his parent list of ItemPictureAdmin with the index 0

*After this, I incremented the index in the session. After I got all the elements from the list, I deleted the session parameter that saved the index.

This solution is an adaptation of caponica's solution here

A: I had same problem and i am able to do this through "Custom Form Type Extension" for which documentation is given on the link "http://symfony.com/doc/current/cookbook/form/create_form_type_extension.html" .
It is the perfect solution ..


text:
Q: Is there a library to unzip .Z files using VB.NET? I need to unzip a list of .Z files which will be kept in a folder using Visual Basic.NET.
For example, consider that there is a folder like C:\FilesToBeUnzipped. Inside this folder there will some 5 to 6 files with .Z as extension. I need to unzip all these .Z files and save the unzipped files in a folder like C:\UnzippedDataFiles.
Is this possible in VB.NET? Is there any free component or class library to achive it?

A: I also ran into this issue as well, just needed to decompress a *.Z file
Please note, I am not the original author of this however, wanted to provide copy of source on stack overflow in case the original site is no longer available.
The original post can be found here
Here is an example of how to use the class:
using System;
using System.IO;

using Ebixio.LZW;

class MainClass
{
    public static void Main(string[] args)
    {
        byte[] buffer = new byte[4096];
        string outFile = Path.GetFileNameWithoutExtension(args[0]);

        using (Stream inStream = new LzwInputStream(File.OpenRead(args[0])))
        using (FileStream outStream = File.Create(outFile)) {
            int read;
            while ((read = inStream.Read(buffer, 0, buffer.Length)) > 0) {
                outStream.Write(buffer, 0, read);
            }
        }
    }
}

Here is a modifed version of this as a static method that i made.  It allows choosing the *.Z file location and a path to extract to:
public static void LzwUncompress(this string path, string unzippedPath) {
            byte[] buffer = new byte[4096];
            //string outFile = Path.GetFileNameWithoutExtension(path);

            using (Stream inStream = new Ebixio.LZW.LzwInputStream(File.OpenRead(path)))
            using (FileStream outStream = File.Create(unzippedPath)) {
                int read;
                while ((read = inStream.Read(buffer, 0, buffer.Length)) > 0) {
                    outStream.Write(buffer, 0, read);
                }
            }
        }

An example using the static method:
savePath.LzwUncompress(unzippedPath);

Add this class file to your project:
// LzwInputStream.cs
//
// Copyright (C) 2009 Gabriel Burca
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library.  Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//

using System;
using System.IO;

namespace Ebixio.LZW {

    /// <summary>
    /// This class contains constants used for LZW
    /// </summary>
    sealed public class LzwConstants {
        /// <summary>
        /// Magic number found at start of LZW header: 0x1f 0x9d
        /// </summary>
        public const int MAGIC = 0x1f9d;

        /// <summary>
        /// Maximum number of bits per code
        /// </summary>
        public const int MAX_BITS = 16;

        /* 3rd header byte:
         * bit 0..4 Number of compression bits
         * bit 5    Extended header
         * bit 6    Free
         * bit 7    Block mode
         */

        /// <summary>
        /// Mask for 'number of compression bits'
        /// </summary>
        public const int BIT_MASK = 0x1f;

        /// <summary>
        /// Indicates the presence of a fourth header byte
        /// </summary>
        public const int EXTENDED_MASK = 0x20;
        //public const int FREE_MASK      = 0x40;

        /// <summary>
        /// Reserved bits
        /// </summary>
        public const int RESERVED_MASK = 0x60;

        /// <summary>
        /// Block compression: if table is full and compression rate is dropping,
        /// clear the dictionary.
        /// </summary>
        public const int BLOCK_MODE_MASK = 0x80;

        /// <summary>
        /// LZW file header size (in bytes)
        /// </summary>
        public const int HDR_SIZE = 3;

        /// <summary>
        /// Initial number of bits per code
        /// </summary>
        public const int INIT_BITS = 9;

        LzwConstants() {
        }
    }

    /// <summary>
    /// This filter stream is used to decompress a LZW format stream.
    /// Specifically, a stream that uses the LZC compression method.
    /// This file format is usually associated with the .Z file extension.
    ///
    /// See http://en.wikipedia.org/wiki/Compress
    /// See http://wiki.wxwidgets.org/Development:_Z_File_Format
    ///
    /// The file header consists of 3 (or optionally 4) bytes. The first two bytes
    /// contain the magic marker "0x1f 0x9d", followed by a byte of flags.
    ///
    /// Based on Java code by Ronald Tschalar, which in turn was based on the unlzw.c
    /// code in the gzip package.
    /// </summary>
    /// <example> This sample shows how to unzip a compressed file
    /// <code>
    /// using System;
    /// using System.IO;
    ///
    /// using Ebixio.LZW;
    ///
    /// class MainClass
    /// {
    ///     public static void Main(string[] args)
    ///     {
    ///         byte[] buffer = new byte[4096];
    ///         using (Stream inStream = new LzwInputStream(File.OpenRead(args[0])))
    ///         using (FileStream outStream = File.Create(Path.GetFileNameWithoutExtension(args[0]))) {
    ///             int read;
    ///             while ((read = inStream.Read(buffer, 0, buffer.Length)) > 0) {
    ///                 outStream.Write(buffer, 0, read);
    ///             }
    ///         }
    ///     }
    /// }
    /// </code>
    /// </example>
    public class LzwInputStream : Stream {
        byte[] one = new byte[1];
        bool headerParsed = false;

        // string table stuff
        private const int TBL_CLEAR = 0x100;
        private const int TBL_FIRST = TBL_CLEAR + 1;

        private int[] tabPrefix;
        private byte[] tabSuffix;
        private int[] zeros = new int[256];
        private byte[] stack;

        // various state
        private bool blockMode;
        private int nBits;
        private int maxBits;
        private int maxMaxCode;
        private int maxCode;
        private int bitMask;
        private int oldCode;
        private byte finChar;
        private int stackP;
        private int freeEnt;

        // input buffer
        private byte[] data = new byte[10000];
        private int bitPos = 0, end = 0, got = 0;
        private bool eof = false;
        private const int EXTRA = 64;

        /// <summary>
        /// Creates a LzwInputStream
        /// </summary>
        /// <param name="baseInputStream">
        /// The stream to read compressed data from (baseInputStream LZW format)
        /// </param>
        public LzwInputStream(Stream baseInputStream) {
            this.baseInputStream = baseInputStream;
        }

        /// <summary>
        /// See <see cref="System.IO.Stream.ReadByte"/>
        /// </summary>
        /// <returns></returns>
        public override int ReadByte() {
            int b = Read(one, 0, 1);
            if (b == 1)
                return (one[0] & 0xff);
            else
                return -1;
        }

        /// <summary>
        /// Moves the unread data in the buffer to the beginning and resets
        /// the pointers.
        /// </summary>
        /// <param name="bitPos"></param>
        /// <returns></returns>
        private int ResetBuf(int bitPos) {
            int pos = bitPos >> 3;
            Array.Copy(data, pos, data, 0, end - pos);
            end -= pos;
            return 0;
        }

        private void Fill() {
            got = baseInputStream.Read(data, end, data.Length - 1 - end);
            if (got > 0) end += got;
        }

        private void ParseHeader() {
            headerParsed = true;

            byte[] hdr = new byte[LzwConstants.HDR_SIZE];

            int result = baseInputStream.Read(hdr, 0, hdr.Length);

            // Check the magic marker
            if (result < 0) throw new ApplicationException("Failed to read LZW header");
            if (hdr[0] != (LzwConstants.MAGIC >> 8) || hdr[1] != (LzwConstants.MAGIC & 0xff)) {
                throw new ApplicationException(String.Format(
                    "Wrong LZW header. Magic bytes don't match. 0x{0:x2} 0x{1:x2}",
                    hdr[0], hdr[1]));
            }

            // Check the 3rd header byte
            blockMode = (hdr[2] & LzwConstants.BLOCK_MODE_MASK) > 0;
            maxBits = hdr[2] & LzwConstants.BIT_MASK;

            if (maxBits > LzwConstants.MAX_BITS) {
                throw new ApplicationException("Stream compressed with " + maxBits +
                    " bits, but decompression can only handle " +
                    LzwConstants.MAX_BITS + " bits.");
            }

            if ((hdr[2] & LzwConstants.RESERVED_MASK) > 0) {
                throw new ApplicationException("Unsupported bits set in the header.");
            }

            // Initialize variables
            maxMaxCode = 1 << maxBits;
            nBits = LzwConstants.INIT_BITS;
            maxCode = (1 << nBits) - 1;
            bitMask = maxCode;
            oldCode = -1;
            finChar = 0;
            freeEnt = blockMode ? TBL_FIRST : 256;

            tabPrefix = new int[1 << maxBits];
            tabSuffix = new byte[1 << maxBits];
            stack = new byte[1 << maxBits];
            stackP = stack.Length;

            for (int idx = 255; idx >= 0; idx--)
                tabSuffix[idx] = (byte)idx;
        }

        #region Stream Overrides

        /// <summary>
        /// Reads decompressed data into the provided buffer byte array
        /// </summary>
        /// <param name ="buffer">
        /// The array to read and decompress data into
        /// </param>
        /// <param name ="offset">
        /// The offset indicating where the data should be placed
        /// </param>
        /// <param name ="count">
        /// The number of bytes to decompress
        /// </param>
        /// <returns>The number of bytes read. Zero signals the end of stream</returns>
        public override int Read(byte[] buffer, int offset, int count) {
            if (!headerParsed) ParseHeader();

            if (eof) return -1;
            int start = offset;

            /* Using local copies of various variables speeds things up by as
             * much as 30% in Java! Performance not tested in C#.
             */
            int[] lTabPrefix = tabPrefix;
            byte[] lTabSuffix = tabSuffix;
            byte[] lStack = stack;
            int lNBits = nBits;
            int lMaxCode = maxCode;
            int lMaxMaxCode = maxMaxCode;
            int lBitMask = bitMask;
            int lOldCode = oldCode;
            byte lFinChar = finChar;
            int lStackP = stackP;
            int lFreeEnt = freeEnt;
            byte[] lData = data;
            int lBitPos = bitPos;

            // empty stack if stuff still left
            int sSize = lStack.Length - lStackP;
            if (sSize > 0) {
                int num = (sSize >= count) ? count : sSize;
                Array.Copy(lStack, lStackP, buffer, offset, num);
                offset += num;
                count -= num;
                lStackP += num;
            }

            if (count == 0) {
                stackP = lStackP;
                return offset - start;
            }

            // loop, filling local buffer until enough data has been decompressed
        MainLoop: do {
                if (end < EXTRA) Fill();

                int bitIn = (got > 0) ? (end - end % lNBits) << 3 :
                                        (end << 3) - (lNBits - 1);

                while (lBitPos < bitIn) {
                    #region A
                    // handle 1-byte reads correctly
                    if (count == 0) {
                        nBits = lNBits;
                        maxCode = lMaxCode;
                        maxMaxCode = lMaxMaxCode;
                        bitMask = lBitMask;
                        oldCode = lOldCode;
                        finChar = lFinChar;
                        stackP = lStackP;
                        freeEnt = lFreeEnt;
                        bitPos = lBitPos;

                        return offset - start;
                    }

                    // check for code-width expansion
                    if (lFreeEnt > lMaxCode) {
                        int nBytes = lNBits << 3;
                        lBitPos = (lBitPos - 1) +
                        nBytes - (lBitPos - 1 + nBytes) % nBytes;

                        lNBits++;
                        lMaxCode = (lNBits == maxBits) ? lMaxMaxCode :
                                                        (1 << lNBits) - 1;

                        lBitMask = (1 << lNBits) - 1;
                        lBitPos = ResetBuf(lBitPos);
                        goto MainLoop;
                    }
                    #endregion

                    #region B
                    // read next code
                    int pos = lBitPos >> 3;
                    int code = (((lData[pos] & 0xFF) |
                        ((lData[pos + 1] & 0xFF) << 8) |
                        ((lData[pos + 2] & 0xFF) << 16)) >>
                        (lBitPos & 0x7)) & lBitMask;

                    lBitPos += lNBits;

                    // handle first iteration
                    if (lOldCode == -1) {
                        if (code >= 256) throw new ApplicationException("corrupt input: " + code + " > 255");

                        lFinChar = (byte)(lOldCode = code);
                        buffer[offset++] = lFinChar;
                        count--;
                        continue;
                    }

                    // handle CLEAR code
                    if (code == TBL_CLEAR && blockMode) {
                        Array.Copy(zeros, 0, lTabPrefix, 0, zeros.Length);
                        lFreeEnt = TBL_FIRST - 1;

                        int nBytes = lNBits << 3;
                        lBitPos = (lBitPos - 1) + nBytes - (lBitPos - 1 + nBytes) % nBytes;
                        lNBits = LzwConstants.INIT_BITS;
                        lMaxCode = (1 << lNBits) - 1;
                        lBitMask = lMaxCode;

                        // Code tables reset

                        lBitPos = ResetBuf(lBitPos);
                        goto MainLoop;
                    }
                    #endregion

                    #region C
                    // setup
                    int inCode = code;
                    lStackP = lStack.Length;

                    // Handle KwK case
                    if (code >= lFreeEnt) {
                        if (code > lFreeEnt) {
                            throw new ApplicationException("corrupt input: code=" + code +
                                ", freeEnt=" + lFreeEnt);
                        }

                        lStack[--lStackP] = lFinChar;
                        code = lOldCode;
                    }

                    // Generate output characters in reverse order
                    while (code >= 256) {
                        lStack[--lStackP] = lTabSuffix[code];
                        code = lTabPrefix[code];
                    }

                    lFinChar = lTabSuffix[code];
                    buffer[offset++] = lFinChar;
                    count--;

                    // And put them out in forward order
                    sSize = lStack.Length - lStackP;
                    int num = (sSize >= count) ? count : sSize;
                    Array.Copy(lStack, lStackP, buffer, offset, num);
                    offset += num;
                    count -= num;
                    lStackP += num;
                    #endregion

                    #region D
                    // generate new entry in table
                    if (lFreeEnt < lMaxMaxCode) {
                        lTabPrefix[lFreeEnt] = lOldCode;
                        lTabSuffix[lFreeEnt] = lFinChar;
                        lFreeEnt++;
                    }

                    // Remember previous code
                    lOldCode = inCode;

                    // if output buffer full, then return
                    if (count == 0) {
                        nBits = lNBits;
                        maxCode = lMaxCode;
                        bitMask = lBitMask;
                        oldCode = lOldCode;
                        finChar = lFinChar;
                        stackP = lStackP;
                        freeEnt = lFreeEnt;
                        bitPos = lBitPos;

                        return offset - start;
                    }
                    #endregion
                }   // while

                lBitPos = ResetBuf(lBitPos);

            } while (got > 0);  // do..while

            nBits = lNBits;
            maxCode = lMaxCode;
            bitMask = lBitMask;
            oldCode = lOldCode;
            finChar = lFinChar;
            stackP = lStackP;
            freeEnt = lFreeEnt;
            bitPos = lBitPos;

            eof = true;
            return offset - start;
        }

        /// <summary>
        /// Gets a value indicating whether the current stream supports reading
        /// </summary>
        public override bool CanRead {
            get {
                return baseInputStream.CanRead;
            }
        }

        /// <summary>
        /// Gets a value of false indicating seeking is not supported for this stream.
        /// </summary>
        public override bool CanSeek {
            get {
                return false;
            }
        }

        /// <summary>
        /// Gets a value of false indicating that this stream is not writeable.
        /// </summary>
        public override bool CanWrite {
            get {
                return false;
            }
        }

        /// <summary>
        /// A value representing the length of the stream in bytes.
        /// Always throws a NotSupportedException when attempting to get the length.
        /// </summary>
        /// <exception cref="NotSupportedException">Attempting to get the length</exception>
        public override long Length {
            get {
                throw new NotSupportedException("LzwInputStream Length not supported");
            }
        }

        /// <summary>
        /// The current position within the stream.
        /// Throws a NotSupportedException when attempting to set the position.
        /// </summary>
        /// <exception cref="NotSupportedException">Attempting to set the position</exception>
        public override long Position {
            get {
                return baseInputStream.Position;
            }
            set {
                throw new NotSupportedException("LzwInputStream Position not supported");
            }
        }

        /// <summary>
        /// Flushes the baseInputStream
        /// </summary>
        public override void Flush() {
            baseInputStream.Flush();
        }

        /// <summary>
        /// Sets the position within the current stream
        /// Always throws a NotSupportedException
        /// </summary>
        /// <param name="offset">The relative offset to seek to.</param>
        /// <param name="origin">The <see cref="SeekOrigin"/> defining where to seek from.</param>
        /// <returns>The new position in the stream.</returns>
        /// <exception cref="NotSupportedException">Any access</exception>
        public override long Seek(long offset, SeekOrigin origin) {
            throw new NotSupportedException("LzwInputStream Seek not supported");
        }

        /// <summary>
        /// Set the length of the current stream
        /// Always throws a NotSupportedException
        /// </summary>
        /// <param name="value">The new length value for the stream.</param>
        /// <exception cref="NotSupportedException">Any access</exception>
        public override void SetLength(long value) {
            throw new NotSupportedException("LzwInputStream SetLength not supported");
        }

        /// <summary>
        /// Writes a sequence of bytes to stream and advances the current position
        /// This method always throws a NotSupportedException
        /// </summary>
        /// <param name="buffer">Thew buffer containing data to write.</param>
        /// <param name="offset">The offset of the first byte to write.</param>
        /// <param name="count">The number of bytes to write.</param>
        /// <exception cref="NotSupportedException">Any access</exception>
        public override void Write(byte[] buffer, int offset, int count) {
            throw new NotSupportedException("LzwInputStream Write not supported");
        }

        /// <summary>
        /// Writes one byte to the current stream and advances the current position
        /// Always throws a NotSupportedException
        /// </summary>
        /// <param name="value">The byte to write.</param>
        /// <exception cref="NotSupportedException">Any access</exception>
        public override void WriteByte(byte value) {
            throw new NotSupportedException("LzwInputStream WriteByte not supported");
        }

        /// <summary>
        /// Entry point to begin an asynchronous write.  Always throws a NotSupportedException.
        /// </summary>
        /// <param name="buffer">The buffer to write data from</param>
        /// <param name="offset">Offset of first byte to write</param>
        /// <param name="count">The maximum number of bytes to write</param>
        /// <param name="callback">The method to be called when the asynchronous write operation is completed</param>
        /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests</param>
        /// <returns>An <see cref="System.IAsyncResult">IAsyncResult</see> that references the asynchronous write</returns>
        /// <exception cref="NotSupportedException">Any access</exception>
        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) {
            throw new NotSupportedException("LzwInputStream BeginWrite not supported");
        }

        /// <summary>
        /// Closes the input stream.  When <see cref="IsStreamOwner"></see>
        /// is true the underlying stream is also closed.
        /// </summary>
        public override void Close() {
            if (!isClosed) {
                isClosed = true;
                if (isStreamOwner) {
                    baseInputStream.Close();
                }
            }
        }

        #endregion

        /// <summary>
        /// Get/set flag indicating ownership of underlying stream.
        /// When the flag is true <see cref="Close"/> will close the underlying stream also.
        /// </summary>
        /// <remarks>
        /// The default value is true.
        /// </remarks>
        public bool IsStreamOwner {
            get { return isStreamOwner; }
            set { isStreamOwner = value; }
        }

        /// <summary>
        /// Base stream the inflater reads from.
        /// </summary>
        protected Stream baseInputStream;

        /// <summary>
        /// Flag indicating wether this instance has been closed or not.
        /// </summary>
        bool isClosed;

        /// <summary>
        /// Flag indicating wether this instance is designated the stream owner.
        /// When closing if this flag is true the underlying stream is closed.
        /// </summary>
        bool isStreamOwner = true;
    }
}

A: How about SevenZipSharp?
It's a managed wrapper around the 7-Zip compression/decompression engine that is released under the LGPL. Although the code is written in C#, all of the functions provided by the library are fully accessible in your VB.NET code.
If you're a do-it-yourselfer, check out the 7-Zip SDK.
I see SharpZipLib and DotNetZip recommended a lot, but I am not sure if they support .Z archives.  I know that 7-Zip does, not to mention it's one of my favorite open source apps.


text:
Q: React MUI Autocomplete - Is it possible to add independent option at the rendered option list? At the end of the list, it should be visible option Other which should be static (manually added) option.
The idea is to add it manually to the DOM and should be independent from all other dynamically created list elements.
My question, is that possible and if so, how ?
When user click on that option, additional form input should appear, but that logic is already implemented, I just need to trigger click handler and use
setFieldValue('pension_fund_name', CommonDropdownItems.Other)
import { createElement, HTMLAttributes } from 'react'
import { Divider } from '@eframe-ui/react'
import { FilterDropdownProps, DropdownOptionProps } from './types'
import { Translate } from '../translate'
import { Autocomplete, Paper } from '@mui/material'
import { FilterDropdownInput } from './Input'

export const FilterDropdown = ({
  data,
  dropdownDataLayout,
  selectFieldLabel,
  fieldValue,
  errors,
  setFieldValue,
}: FilterDropdownProps) => {
  /* eslint-disable @typescript-eslint/no-explicit-any */
  const CustomPaper = (props: any) => (
    <Paper {...props} sx={{ background: '#f4f7fa', marginTop: '4px' }} />
  )

  return (
    <Autocomplete
      freeSolo
      className="gap-y-1 flex flex-col"
      options={data}
      getOptionLabel={(option: string | DropdownOptionProps) =>
        (option as { value: string }).value
      } // filter value
      onChange={(e, value) => setFieldValue(fieldValue, value)}
      renderInput={(params) => (
        <FilterDropdownInput
          error={errors}
          params={params}
          label={selectFieldLabel}
        />
      )}
      renderOption={(
        props: HTMLAttributes<HTMLLIElement>,
        option: DropdownOptionProps,
        state
      ) => {
        const { label, mixin } = option

        return (
          <>
            <li {...props} className="w-full cursor-pointer">
              {dropdownDataLayout
                ? createElement(
                    dropdownDataLayout,
                    mixin as Record<string, string>,
                  )
                : label && (
                    <>
                      <Translate label={label} />
                      <Divider className="!my-2" />
                    </>
                  )}
            </li>
          </>
        )
      }}
      PaperComponent={CustomPaper}
    />
  )
}

Dynamic options are rendered through this layout
 const TransferAssetsLayout = (option: Record<string, string>) => (
    <>
      <p className="text-text-primary typo-regular-300 px-2 pt-1">
        {option.name}
      </p>
      {option.recipient && (
        <p
          className={clsx(
            classes.italic,
            'text-text-secondary typo-regular-200 px-2 pb-1',
          )}
        >
          {option.recipient}
        </p>
      )}
      <p
        className={clsx(
          classes.italic,
          'text-text-secondary typo-regular-200 px-2 pb-1',
        )}
      >
        {`${option.address}, ${option.zip_code} ${option.location}`}
      </p>
      <Divider className="!m-0" />
    </>
  )


text:
Q: What is the probability of choosing r independent vectors in $\mathbb{R}^n$ in the unit sphere? I was trying to compute the probability of choosing $r \leq n$ indepedent vectors $a_i \in \mathbb{R}^n$ such that they are independent.
I was told that the probability that they are not independent is zero if they lie in the unit sphere. However, was unsure of how to compute such a probability or if it was true.
The intuition I have is that there are infinite directions I could choose, so the probability that I choose the same vector pointing in the same direction is zero. However, that doesn't seem rigorous enough. I feel there might be a caveat I need to take care of to make sure its correct.
Is that correct and why? If we didn't choose them in the unit sphere would it still be true?

A: Since $r \leq n$, then yes, the probability of independence is $1$.
You'll have linear dependence if any of the vectors is in the span of the other $r - 1$ vectors. But the span of $r - 1$ vectors is a hyperplane; a set of measure $0$ in $\Bbb R^n$. This hyperplane has dimension $r - 1$ and intersects the unit sphere in a region whose dimension is at most $r - 2$, and thus has measure $0$, with respect to the surface of the sphere (which has dimension $n - 1$).
Thus, the $r$th vector is almost surely not in the span of the other $r - 1$.
I think the idea behind using the unit sphere is that you're restricting your attention to unit vectors. If we had been able to choose vectors in all of $\Bbb R^n$ instead of just the unit sphere, it wouldn't really change anything. Roughly, the unit sphere parameterizes the 'directionality' that vectors can have, and this is all that affects linear independence. If we have a set of not-necessarily-unit vectors, we can replace each vector $v$ with the unit vector $\frac{v}{||v||}$ in the same direction. This won't affect linear (in)dependence at all, so we might as well ignore length differences, and look at the unit sphere.
I think focusing on the sphere makes the argument a little tougher to digest, personally. It's clear that hyperplanes of dimension $r-1 < n$ "take up no volume" in $\Bbb R^n$, and so we're almost certain to pick vectors that aren't in the span of what we have. The same idea is still true on the sphere, but we have to use a different measure. The intersection of our span with the surface of the unit sphere is still "too small" with respect to the entire surface to give a non-negligible probability, but it's not as obvious, in my opinion.
So, it seems to me that you need to utilize some kind of measure on $\Bbb R^n$ or the unit sphere to more rigorously justify the assertion.

EDIT for a specific example:
I'm certainly not an expert, but higher-end probability relies on measure theory. Just think about being on the unit $2$-sphere $S^2 = \{(x, y, z):x^2 + y^2 + z^2 = 1\}$. Any (nontrivial proper) subspace of $\Bbb R^3$ will intersect our sphere in either a pair of antipodal points (call the set of such a pair $P$) or a great circle (call it $C$), corresponding to the span of $1$ or $2$ vectors intersecting $S^2$ (the intersection of a line or a plane with the unit sphere).
The probability of picking a point in $P$ is essentially $$\frac{\text{the area of } P}{\text{the area of }S^2},$$ and it's analogous for picking a point on a great circle. However, $0$- and $1$- dimensional objects have $0$ as their $2$-dimensional area, leading to a $0$ probability of choosing such a point.
Measure theory just makes $n$-dimensional area rigorous, but it does more than that, in the context of probability theory. But, the take-away is that probabilities are measures, and when it comes to problems like this, we really need the measure-theoretic view: just counting discrete possibilities isn't good enough.
Hopefully, however, the intuition here is helpful, because it's all I can provide.


text:
Q: Big Endian bytes vs. Strings as keys in string - string databases I haven't seen the common sense notion of converting an integer to network order and to write the resulting bytes into an indexable entity in a string - string database vs. writing the string representation of the number anywhere in the documentation of such databases.
Surely the size overhead of writing a 64-bit int as a string into a database must outweigh the trivial complexity of having to do a ntohl call before writing the bytes back into an integer type.
I am therefore missing something here, what are the downsides to using big-endian bytes vs. strings as indexable entities in string-string databases ?
(C++/C tags as I am talking about writing bytes into the memory location of a programatic type, BDB as that is the database I am using, could be kyotodb as well).

A: If the database validates that the string data you send is valid in the expected encoding then you can't just give it any data you want. You'll only be able to send such integers as happen to look like a valid encoding. I don't know if BDB or kyotodb do such validation.
Also it seems to me like a hack to try to trick one data type to hold something else, and then rely on clients to all know the trick. Of course that applies whether you're using the string to hold a ascii-decimal representation of the integer or if you're using the string as a raw memory buffer to hold the integer. It seems to me that it'd be better to use a database that actually holds the types you want to hold, instead of just strings.

A: The advantage of big-endian in this case is that the strings would sort correctly in ascending order.
If the database architecture cannot natively store 64-bit integers, but you need to store them anyway, stringifying them this way is a way to do it.
Of course if you later upgrade the database to one that can store 64-bit integers natively, you will either be "stuck" with the implementation or have to go through a migration process.


text:
Q: mysql query check date I cannot figure out how to write query for checking date.
For example;
Rooms table;
room_id, number_of_rooms, checkin(date: 1/05/2012), checkout(date:14/05/2012);
I want to write a query which check for entered date by user (checkin and checkout date) with rooms tabel(checkin and checkout date);
The idea is to know whether period of time entered by user is between check in and check out date of rooms table
Something like this;
select * from romms
where checkin and checkout date is not among user_entered_checkin and user_entered_checkeout

A: Maybe
SELECT * FROM rooms
WHERE (checkin IS NOT BETWEEN user_entered_checkin AND user_entered_checkout)
  AND (checkout IS NOT BETWEEN user_entered_checkin AND user_entered_checkout)

A: If you want ranges from the table that are completely outside the user-entered range, then you could go like this:
...
WHERE checkin  > user_entered_checkout
   OR checkout < user_entered_checkin

If you want rows where the ranges are at least partly outside the user-entered range, then the condition could be this:
...
WHERE checkin  < user_entered_checkin
   OR checkout > user_entered_checkout


text:
Q: How to make jointjs paper responsive? I just discover javascript library JointJs and I implemented a graph with paper and rects.
But I can't make it responsive when I reduce the browser size my graph doesn't display correctly.
How can I make my paper responsive with jointjs ?

A: You can initially set the paper to be the same dimensions as it's containing element, but that's only calculated initially when the paper is created. If you want to paper to change size as you resize your browser, you'll need to react to resize events.
Firstly, you'll need to set overflow to hidden on your container, otherwise its dimensions will stretch to fit its child, and it won't shrink if you shrink the browser.
#modelCanvas {
    overflow: hidden;
}

You'll have to make sure your #modelCanvaselement will stretch to fill available space by some method, either setting height: 100% (in situations where that will work) or using flexbox or absolute positioning.
Secondly, you'll need a resize event handler
$(window).resize(function() {
    var canvas = $('#modelCanvas');
    paper.setDimensions(canvas.width(), canvas.height());
});

A: From the docs on setDimensions (http://resources.jointjs.com/docs/jointjs/v2.2/joint.html#dia.Paper.prototype.setDimensions), you can set width: '100%', height: '100%' and then control the responsive display with your css.
Then, something like:
$(window).on('resize', joint.util.debounce(function() {
    paper.scaleContentToFit({ padding: 10 });
}));

and/or also set a min-width/min-height in px to the paper in css and add an overflow: auto to the parent.

A: I Recommend using a responsive layout css such as bootstrap I personally recommend pure css (http://purecss.io) and the rest is easy once you set a base layout for the html page which contains the JointJS paper.
For example let's suppose you made the html base and you created specifically a div container called "modelCanvas" this div was made with a responsive css (For this example I used pure CSS).

<div id="modelCanvas" style="height:100%;width:100%; overflow-y: auto; overflow-x: auto;background-image:url(../res/tiny_grid.png);background-repeat:repeat;">

Now into the JS part of your web site you, we'll initialize required JointJS paper and graph init
var graph = new joint.dia.Graph;

var paper = new joint.dia.Paper({
 el: $('#modelCanvas'),
 gridSize: 10,
 height: $('#modelCanvas').height(),
 width: $('#modelCanvas').width(),
 gridSize: 1,
 model: graph,
});

Now the JointJS paper is responsive
Best,
AG

A: You can just change the size of the div containing your paper:
document.getElementById("your-paper-container").setAttribute("style", "height: " + window.innerHeight + "px; overflow: scroll;");

You could change the code window.innterHeight to a variable if you have some additional elements within your page:
headers = 210;
height = window.innerHeight - headers;
document.getElementById("paper-container").setAttribute("style", "height: " + height + "px; overflow: scroll;");


text:
Q: Ubuntu 22.0 screen and icons refresh every second I upgraded my Ubuntu 20.04 to 22.04. I have this issue. My screen and everything refreshes every second and I can't do anything.

Results of sudo lshw -c video :
*-display
       description: VGA compatible controller
       product: Skylake GT2 [HD Graphics 520]
       vendor: Intel Corporation
       physical id: 2
       bus info: pci@0000:00:02.0
       logical name: /dev/fb0
       version: 07
       width: 64 bits
       clock: 33MHz
       capabilities: pciexpress msi pm vga_controller bus_master cap_list rom fb


text:
Q: If value in column I is 2 or 3, the copy corresponding B:D in same row and paste on cover page I have a worksheet that can be updated. The user inputs a sheet number to real time update and then macro will look at Column 9 (I) and copy B:D of that row and paste it in cells on the front sheet (coverpage). This will continue until all data in the data sheet has run through.
Sub Update_Current()
    Dim Page
    Dim lastrow As Long, i As Long
    Dim ws As Worksheet

    lastrow = ActiveSheet.Range("D1000").End(xlUp).Row + 1

    Page = InputBox("Which week would you like to update?")

    If Page = 1 Then
        Worksheets("Week(1)").Select

        For i = 6 To 100
            If ws.Cells(i, 9) = "2" Or ws.Cells(i, 9) = "3" Then
                Range("i,2:1,4").Copy

                {TORN ON WHAT GOES HERE}

            End If
        Next i
    End If
End Sub

A: I know it is late but cannot leave a question without an answer when i think i have one. Hopefully this will help someone else.
Sub Update_Current()
Dim Page
Dim lastrow As Long, i As Long
Dim ws As Worksheet

Page = InputBox("Which week would you like to update?")

If Page = 1 Then
   Set ws = Worksheets("Week(1)")
   ws.Select
    For i = 2 To 100
        If ws.Cells(i, 9) = "2" Or ws.Cells(i, 9) = "3" Then
            ws.Range("B" & i & ":D" & i).Copy
            ThisWorkbook.Sheets("CoverPage").Select
            lastrow = ThisWorkbook.Sheets("CoverPage").Range("D1000").End(xlUp).Row + 1
            ThisWorkbook.Sheets("CoverPage").Range("B" & lastrow).PasteSpecial xlPasteValues
        End If
    Next i
End If
End Sub


text:
Q: serialize and deserialize self reference object in c# I have a class A like this
class A
    {
        public string Type { get; set; }
        public object[] Content { get; set; }
        public string[] jsonContent { get; set; }

        public A()
        {

        }

        public A(string type)
        {
            this.Type = type;
        }

        public A(string type, object[] content)
        {
            this.Type = type;
            this.Content = content;
        }

        public string ToJson()
        {
        int len = Content.Length;
        string[] jsonContentTmp = new string[len];
        for (int i = 0; i < Content.Length; ++i)
        {
            jsonContentTmp[i] = JsonConvert.SerializeObject(Content[i]);
        }
        jsonContent = jsonContentTmp;
        var json = JsonConvert.SerializeObject(this);
        return json;
        }

        public static A ToA(string str)
        {
        Request a = JsonConvert.DeserializeObject<A>(str);
        return a;
        }
    }

Consider bellow:
A sub1 = new A();
A sub2 = new A();
object[] obj = {sub1, sub2};
A test = new A("type", obj);

When I want to serialize test, I receive exception

self reference

I tried PreserveReferencesHandling but i couldn't deserialize and receive exception

'cannot preserve reference toarray'

.
Any idea to serialize and deserialize it?

A: So it seems this is done on purpose to prevent Stackoverflow exceptions. No pun intended. You have to turn PreserveReferences on, to enable self referencing:
Serialising Circular references
In your AppStart in Global.asax try the following:
var jsonSerializerSettings = new JsonSerializerSettings
{
    PreserveReferencesHandling = PreserveReferencesHandling.Objects
};

GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonNetFormatter(jsonSerializerSettings));


text:
Q: Azure Active Directory and Multi-tenant apps authorization After registering an application in AAD, there seems to be no way of managing tenant access control in the Azure portal.
From what i have been reading, the burden of allowing or denying a particular tenant falls on the developer in the app code.  All users. from any AAD domain can access a registered app  by default (after Grant Permissions )..
If this is the case than this is a piss-poor model.  This means that "allowed-tenants" table can potentially grow to millions of records, and each time a user logs in, a query would need to check his tennantID against that table..

A: AFAIK, currently there is no such feature make allow/deny list for a multi-tenant app. We could control that in app , by checking tid claim in JWT token , you could create a deny list( records will less then allow list) and check whether tid is in the deny list . And here is a feedback which requires same feature .


text:
Q: Paerser Error when loading C# ASP.NET website hosted on GoDaddy I am hosting a website with GoDaddy, recently I started getting errors when trying to load the site.
I am publishing the site to file system and then loading the site to the right folder in my hosting account. The site worked before but I had to update and how I'm getting this error, the site works fine in my IIS setup I use for testing sites.
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Cannot execute a program. The command being executed was "D:\Hosting\13634184\html\{domain-name}.com\bin\roslyn\csc.exe" /shared /keepalive:"10" /noconfig  /fullpaths @"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\{domain-name}.com\748bda03\4edc4877\ux22cjxn.cmdline".

Source Error:

Line 1:  <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="{project-name}._Default" %>
Line 2:
Line 3:  <asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">

Source File: /{domain-name}.com/default.aspx    Line: 1

The last part of the Parser Error Message "\ux22cjxn.cmdline" changes pretty much every time the site is loaded

A: Thank you for pointing me in the right direction. I had the trust level set, but the problem was the
    <system.codedom>
       <!-- All is removed between the 2 tags-->
    </system.codedom>

Removing the code from here fixed the problem.


text:
Q: Why does this simple Akka Streams program never terminate? Should be a simple question.  I'm using Akka 2.4.2 (contains Akka Streams & HTTP).  I expected this Source to complete & the program to terminate because the Source is finite, but it never does.  Why doesn't this program terminate?
import scala.concurrent._
import scala.collection.immutable._
import akka._
import akka.actor._
import akka.stream._
import akka.stream.scaladsl._
import akka.util._

object Test extends App {

  implicit val system = ActorSystem("TestSystem")
  implicit val materializer = ActorMaterializer()

  val s = Source.single(1)
  s.runForeach(println)
}

Output:
$ sbt run
...
[info] Running Test
[DEBUG] [02/23/2016 10:59:19.904] [run-main-0] [EventStream(akka://TestSystem)] logger log1-Logging$DefaultLogger started
[DEBUG] [02/23/2016 10:59:19.904] [run-main-0] [EventStream(akka://TestSystem)] Default Loggers started
1

Relevant portion of my build.sbt file:
scalaVersion  := "2.11.7"

scalacOptions := Seq("-unchecked", "-deprecation", "-encoding", "utf8")

libraryDependencies ++= {
  val akkaVersion = "2.4.2"
  Seq(
    "com.typesafe.akka" %%  "akka-stream" % akkaVersion
  )
}

A: Because Akka uses non-daemonic threads, so it'll keep the app running until you shut-down the ActorSystem. That's because the typical use case is to start the system in your main method and then all computation happens on threads that the ActorSystem manages (i.e. the main() thread is left to complete and go away - if the threads would be daemonic the app would shut down, which is not what we usually want).
You can do so via:
import system.dispatcher
s.runForeach(println).onComplete { _ =>  system.terminate() }

A: Answered at https://groups.google.com/d/msg/akka-user/u3MXlfVpm40/LHyYruS0HgAJ by https://stackoverflow.com/users/111024/konrad-ktoso-malawski, copied here for convenience; credit to him:
Because Akka uses non-daemonic threads, so it'll keep the app running until you shut-down the ActorSystem.
You can do so via:
import system.dispatcher
s.runForeach(println).onComplete { _ =>  system.terminate() }


text:
Q: How to make a delay after not hover on submenu I have a problem with menu delay. I can't add delay when I not hover on submenu. What can I change to delay the submenu for 1 second when I not hover on it. I have to delete this delay when I hover on main menu.
better explenation:
When you hover the main menu items, the delay of the first item keeps the menu item open, while the mouse is already on the second menu item. See gif below.
How will I be able to fix this? Keeping the delay, but when another menu is open, hiding the menu item instantly.
problem
structure of html (compressed for better view):

Hello

hi

Hello

hi

ok

Code in javascirpt to correct:
    $('ul.menu_type_top > li').on('mouseover', function(e){
            var ulObj = $(this).find("ul:first");
            console.log(ulObj);
            ulObj.show();
            var menu_height = ulObj[0].clientHeight + 300;
            $('ul.menu_type_top').css({ height: menu_height });//pokazanie podmenu bo warstwa jest w divie gdzie overflow: hidden

        }).on('mouseout', function(e){
             $(this).find("ul:first").hide();
            $('ul.menu_type_top').css({ height: 40 });//powrót do normalnej wysokości menu
        });

        $('ul.menu_type_top li li').on('mouseover',function(e){
            if($(this).has('ul').length) {

            }

            $('ul:first',this).show();
        }).on('mouseout',function(e){

            $('ul:first', this).hide();
        });


text:
Q: Calling an IMAGEJ plugin in another program thanks for the help!
I am a senior student designing something for my school hospital so any help is greatly appreciated and might make a difference :).
The design involves using a video capture card to gather a stack of images. We then open IMAGEJ and import the stack of images. Then we create a 3D model of the imported stack in IMAGEJ using the plugin 3DViewer (a ".JAR")
In the interest of physician and patient time, it is important to streamline this process. Luckily, the capture card comes with a software development kit that we can tweak.
I want to add a button to the capture card program's GUI (seems simple enough) that will directly call to the IMAGEJ plugin "3DViewer" and send a selected image sequence, thereby eliminating the need to open IMAGEJ.
Is something like this possible? I have never worked with .JAR files. Also, as I change the development kits class files (which runs as its own .JAR file), how do I get the updated .JAR?
Thanks

A: As you use only ImageJ, you have to use the scripting language associated with ImageJ. Each ImageJ command/plugin/PluginFilter can be called from a script.


text:
Q: Textwidth and TikZ \documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{tikz}
\usepackage{lipsum}

\begin{document}
    \lipsum[2]
    \noindent
    \begin{tikzpicture}
    \draw[red, line width=.2cm] (0,0)--(\textwidth,  0) ;
    \end{tikzpicture}
\end{document}

Here is the code and the picture.
Do you know why the red line is overflow ?
Thanks for your help.
Clairon.

A: For simple line after paragraph, I would rather use colored \rule as follows:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{xcolor}
%--------------- show page layout. don't use in a real document!
\usepackage{showframe}
\renewcommand\ShowFrameLinethickness{0.15pt}
\renewcommand*\ShowFrameColor{\color{red}}
%
\usepackage{lipsum}                             % for dummy text
%---------------------------------------------------------------%

\begin{document}
    \lipsum[66]
    \textcolor{red}{\rule{\textwidth}{2mm}}
\end{document}

(red lines indicate text area borders)

A: When PGF (which TikZ is a frontend to) builds a picture then it keeps track of that pictures bounding box. This is what is then used by TeX to determine the size of the graphic. Usually, PGF simply tracks the coordinates that are used and adjusts the bounding box to contain them. Occasionally, this isn't quite right (bézier curves tend to get overlarge bounding boxes) but by-and-large it is and being more accurate is more effort that it is worth. However, one adjustment that is made is to take the line width into account, since although a coordinate might be where a path ends, the actual path will extend slightly beyond that coordinate in some direction. Again, PGF takes the simple approach and simply adds half the current line width to ensure that the bounding box is big enough.
So if you draw a path of line width 1cm from (0,0) to (5,0) then the actual bounding box will have lower left corner of (-.5,-.5) and upper right corner of (5.5, .5).
Now, this additional half linewidth gets added on in both horizontal and vertical directions even if the line doesn't actually need them. This is what I meant by PGF taking the simple approach.
In your code, your line is of width .2cm so an extra .1cm is added in all directions to the obvious bounding box, including to the left and right. So your graphic is actually \textwidth + .2cm in width, hence the overflow.
Fortunately, whenever PGF takes a simple option it often provides a way to correct for it. In this case, you can issue the keys trim left and trim right to the tikzpicture. These take x-coordinates as arguments (or points, whereupon TikZ just reads in the x-coordinate of that point) and so trim left=0 or trim left={(0,0)} (the braces are because of the comma in the coordinate) says "Trim the left-hand side of the bounding box so that its left-hand edge has x-coordinate 0." (note that the "trim" can add space if the coordinate given lies off to the left of the actual picture).
So in your case you would add trim left=0, trim right=\textwidth.
Here's some code to illustrate that.  I've added a rectangle at the end of each picture to show the current bounding box in effect at that point which shows the excess region beyond the red line. In the second one, I've used the trim keys to adjust the bounding box.  Note that this only affects the bounding box that is passed to TeX - the tikzpicture itself thinks that the bounding box is unchanged (if you want to change it from TikZ's point of view, look up the key use as bounding box in the manual).
\documentclass{article}
%\url{https://tex.stackexchange.com/q/654551/86}
\usepackage[T1]{fontenc}
\usepackage{tikz}
\usepackage{lipsum}

\begin{document}
\lipsum[2]

    \noindent
    \begin{tikzpicture}
\draw[red, line width=.2cm] (0,0)--(\textwidth,  0) ;
\draw[overlay] (current bounding box.south east) rectangle (current bounding box.north west);
    \end{tikzpicture}

    \noindent
    \begin{tikzpicture}[trim left=0,trim right=\textwidth]
\draw[red, line width=.2cm] (0,0)--(\textwidth,  0) ;
\draw[overlay] (current bounding box.south east) rectangle (current bounding box.north west);
    \end{tikzpicture}

\end{document}

Thanks to Qrrbrbirlbel in the comments for pointing out that one can use just x-coordinates in the arguments to the trim keys.


text:
Q: Odoo Python 2.7 Encoding utf8 I am trying to create a unicode string out of several fields. I do:
my_unicode_text = u' '.join((u'ID ',str(order_line.product_id.id),u' | [',order_line.product_id.code,u'] ',str(order_line.product_id.name),u' | ',str(order_line.product_uom_qty),u'
')).encode('utf-8').strip())

But I get:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xd3' in position 18: ordinal not in range(128)

I guess I am not correctly using join / str.

A: Perhaps if you replace the join with format:
class Product_id:
    def __init__(self, id, code, name):
        self.id, self.code, self.name = id, code, name

class Order_line:
    def __init__(self, product_id, product_uom_qty):
        self.product_id, self.product_uom_qty = product_id, product_uom_qty

order_line = Order_line(Product_id(42, 6789, u'\N{greek small letter beta}eer'), 6)

s = unicode.format(u'ID {order_line.product_id.id} | [{product_id.code}] {product_id.name} | {order_line.product_uom_qty}
', order_line=order_line, product_id=order_line.product_id)

print s

A: encode is used to go from unicode to str not the inverse, means converting unicode to bytes (str in python 2.x):
# -*- coding: utf-8 -*-
s = u'aller â'
print(type(s))
print(type(s.encode('utf-8')))  # convert to str but using utf-8 codec
print(s + str(1))  # unicode + str == unicode
print(str(s))  # generate an exception because its using `ascii` codec by default

so in your example product name is all ready a utf-8 unicode no need to convert it at all just convert non string object like Integers, Floats.
my_unicode_text = u' '.join(
    (u'ID ',
     str(order_line.product_id.id),  # Integer
     u' | [',
     order_line.product_id.code,
     u'] ',
     order_line.product_id.name,  # utf-8 uncide (database encoding)
     u' | ',
     str(order_line.product_uom_qty),  # floats
     u'
'))

but instead of using join use string formating and manually convert value:
my_unicode_text = u'ID {order_line.product_id.id} | [{order_line.product_id.code}] ' \
              u'{order_line.product_id.name} | {order_line.product_uom_qty}
'.format(order_line=order_line)


text:
Q: Passing arguments, parameters, swap function and a random number generator I am trying to create a random number generator that first swaps the minimum and maximum values and then swaps them again (back to their original state?). My other two questions are: how can I tell if the swap is actually taking place (because it appears to be an invisible process) and no matter which two values that are chosen as the minimum and maximum values the random number output is always 1.
#include <string>
#include <cstdlib>
#include <iostream>
using namespace std;

int minimum;
int maximum;

//Swap function
void swap (int& minimum, int& maximum) {
    minimum = maximum;
    maximum = minimum;
}

int randomNumber;
//Random number generator
void randomNum() {
    minimum = minimum;
    maximum = maximum;
    srand(time(NULL));
    randomNumber = rand() % maximum + minimum;

    cout<<"Your random value is: " << randomNum;

}

int main() {

    cout<<"Please enter your minimum value: " << endl;
    cin>>minimum;

    cout<<"Please enter your maximum value: " << endl;
    cin>>maximum;

     swap (minimum, maximum); //Calling swap function
     randomNum(); //Needs to swap again somehow.

}

A: There is a plethora of issues in your code:

*

*swapping can't take place if you don't save the value of minimum before overwriting it with maximum: the value is lost and on second assignment both just have same value (which is maximum)

*assigning a value to itself doesn't make any sense and I don't understand its purpose (eg minimum = minimum)

*operator precedence makes rand() % maximum + minimum parsed as (rand() % maximum) + minimum and that's not probably what you wanted

*if you want to generate a random number between an interval then you must use the difference between the bounds of the interval, not its sum, eg rand() % (x - y) to obtain a range [x, y).

*calling srand(time(NULL)) locally to randomNum() will reset the generator if you call the function multiple times in the same second

*I don't understand the whole purpose of swapping the values to swap them again, do you need to sort them so that the lesser is always stored in minimum or what?


text:
Q: Arredondar cantos de um Expanded - Flutter Estou tentando arredondar os cantos do segundo Expanded do código abaixo, no caso só queria arredondar o topLeft e o topRight dele, já tentei usar um ClipRRect e BoxDecoration mas ainda não consegui.
import 'package:flutter/material.dart';

void main() {
  runApp(Calculadora());
}

class Calculadora extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.white,
        body: SafeArea(
          child: Column(
            children: [
              Expanded(
                child: Container(
                  color: Colors.blue[100],
                  height: 120,
                ),
              ),
              Expanded(
                flex: 2,
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Também tentei retirar o Expanded e aplicar só no container, mas ainda assim não funcionou.

A: Não coloque a borda no Expanded, pois ele é um Widget mais relacionado com o layout de seu Widget filho. Utilize no widget filho (no seu caso, o Container) diretamente.
Use a propriedade borderRadius do BoxDecoration que você passou para o seu Container. A classe BorderRadius possui um construtor que permite você escolher a borda de cada canto especificamente:
borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(40.0),
                          topRight: Radius.circular(40.0))

Isso já deve ser o suficiente para ter o comportamento que você deseja.
Uma observação: Reparei que o fundo da tela é branco, e o seu Container de baixo tinha uma cor branca, então não é possível notar a borda. (Ficaria branco no branco.) Você disse que já tinha tentado antes. Talvez isso tenha gerado um engano? Você pode colocar o fundo preto para visualizar a borda:
color: Colors.black, //Dentro do boxDecoration do container inferior.

Segue o exemplo completo, com a borda, e o fundo do container preto. Pode ser testado no DartPad.
class Calculadora extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.white,
        body: SafeArea(
          child: Column(
            children: [
              Expanded(
                child: Container(
                  color: Colors.blue[100],
                  height: 120,
                ),
              ),
              Expanded(
                flex: 2,
                child: Container(
                  decoration: const BoxDecoration(
                      color: Colors.black,
                      borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(40.0),
                          topRight: Radius.circular(40.0))),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


text:
Q: Why a GET request send 2 requests to the ServerSocket.accept()? My goal is to understand how a request works. My current knowledge is that, for every request, there is a preflight request. In other words, if you send a GET request, it will send a preflight request first, and then send the actual request after receiving response from the server.
My expected result: I can send a GET request from Postman, or at least I can see the OPTIONS request in the browser, but I can't seem find it.
My actual result: I can't send a GET request from Postman, but I can get the response from browser (after 2nd attempt, if you restart the HttpServer.main(), the "Hello World" somehow will show up, and then if you send the request again from browser, it will refuse to connect, rinse and repeat)
What I've did: I modify the code to keep accepting connection with while(serverSocket.isBound() && !serverSocket.isClosed()) { //... until before the serverSocket.close(); }. The LOGGER log 2 connection request when I send the request from browser and from Postman, but it works.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer {
  private static final Logger LOGGER = LoggerFactory.getLogger(HttpServer.class);

  public static void main(String[] args) {
    LOGGER.info("Server starting...");
    try {
      ServerSocket serverSocket = new ServerSocket(8080);
      Socket socket = serverSocket.accept();

      LOGGER.info("* Connection accepted: " + socket.getInetAddress());

      InputStream inputStream = socket.getInputStream();
      OutputStream outputStream = socket.getOutputStream();

      final String CRLF = "\r\n"; // 13 10

      String messageBody = "Hello World";

      // RFC2616 Section 6 Response
      // response = Status-Line +
      //            * ((general-header
      //               | response-header
      //               | entity-header) + CRLF) +
      //             CRLF +
      //             [ message-body ]
      String response = "HTTP/1.1 200 OK" + CRLF + // Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
              "Content-Length: " + messageBody.getBytes().length + CRLF + // end of entity-header fields
              CRLF + // end of Header Fields
              messageBody;

      outputStream.write(response.getBytes());
      LOGGER.info("Connection processing finished");
      inputStream.close();
      outputStream.close();
      socket.close();
      serverSocket.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

This is the output I get when I use while(serverSocket.isBound() && !serverSocket.isClosed()) { // ... until before the serverSocket.close(); }
03:17:05.514 [main] INFO HttpServer - Server starting...
03:17:10.786 [main] INFO HttpServer - * Connection accepted: /0:0:0:0:0:0:0:1
03:17:10.789 [main] INFO HttpServer - Connection processing finished
03:17:10.955 [main] INFO HttpServer - * Connection accepted: /0:0:0:0:0:0:0:1
03:17:10.955 [main] INFO HttpServer - Connection processing finished

I also tried to log the inputStream.read(). I am assuming this should send  the preflight request, but instead it send the actual request right away.
GET / HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: max-age=0
sec-ch-ua: " Not;A Brand";v="99", "Microsoft Edge";v="91", "Chromium";v="91"
sec-ch-ua-mobile: ?0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36 Edg/91.0.864.41
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

A: Preflight request happens only in CORS (cross origin) requests - from one host to another.
If you had one you could have seen it in the network tab after pressing f12 on chrome

A:
. My current knowledge is that, for every request, there is a
preflight request. In other words, if you send a GET request, it will
send a preflight request first, and then send the actual request after
receiving response from the server.

You are wrong here, not for every request, but for requests that are not "simple requests" https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests

My expected result: I can send a GET request from Postman, or at least
I can see the OPTIONS request in the browser, but I can't seem find
it.

This is wrong, because Postman is not a web browser. The whole contept of CORS is based on the idea that the browser itself will perform a preflight request, so the browser is the one that is curiosus if you beeing on the site X.com can actually fetch resource from Y.com. This is not forced by the server. Simple proxy configuration can totally supress preflights requests and any other cross site checks.
When you make requests from Java - you are in the exact same positin that the postman is. If you don't care about CORS, you will not apply it. To do it, you would actually have to make additional preflight request - which is a simple OPTIONS request with proper CORS related headers - and stop or allow future processing of the code.
Long story short - CORS is enforced by the browsers, not servers. Have browsers without CORS, and nobody will notice.
As an simple analogy, lets imagine you are a little kid, and your friend told you to take a cookie from the jar. Because you don't actually know if you can do that (because its your mummy's jar), you ask your mum if it is ok to take a cookie from the jar (preflight). If mum says its ok, you take it. If she says you cannot, you refuse to do it (proceeed, or refuse). If the cookie jar would be yours in the first place, you will not bother to as mummy (its the same site,  no need for preflight to ask for permission). Thats when you would have cookie CORS policy in your mind.
Beeing a Postman, you can simply ignore what your mum has to say, and just take the cookie - cookier jar will not complain in both cases ;) (postman case, java case, any other http client case)


text:
Q: Import BLOB formatted csv with python I have a csv file that is an output from a BLOB store. The csv contains 6 related entries. Not all records utilise the 6 tables but all records do use table 1. I would like to import table 1 into a data frame, ultimately to write this into postgres. Data is described as following

Files are ASCII text files comprising variable length fields delimited by an asterisk. The files have an extension of "csv". Records are separated by a Carriage Return/Line Feed. No data items should contain an asterisk.

Further information is given in the technical arrangement.

Technical Arrangement
The technical arrangement of our summary data is as follows:
    Fields are in the exact order in which they are listed in this file specification.
    Records are broken down into Types. Each Type represents a different part of the record.
    Each record will begin with Type '01' data
    For each record type '01', there is one or more record type '02's containing Survey Line Item data.   There may be zero or more of record types '03' and '06'.
    There may be zero or one of record types '04' and '05'.
    If a record type '06' exists, there will be one record type '07'
    The end of a record is only indicated by the next row of Type '01' data or the end of the file.
  You should use this information to read the file into formal data structures.

I understand I could use java in place of python but I am more familiar with the python syntax


text:
Q: How can I remove the booked area for undisplayed figure/text or plot in shiny? I have a simple question that I want to display just "text" when the checkbox is unclicked. However, the undisplayed plot has already place to be displayed. I need to remove it.

     library(shiny)
   shinyUI(fluidPage(

    # Application title
     titlePanel("Old Faithful Geyser Data")
  sidebarLayout(
    sidebarPanel(
    sliderInput("bins",
              "Number of bins:",
              min = 1,
              max = 50,
              value = 30),
  checkboxInput("click","Plot")
),

    # Show a plot of the generated distribution
     mainPanel(
       splitLayout(plotOutput("distPlot"), h4("Just Text"))))))

library(shiny)

  shinyServer(function(input, output) {

   output$distPlot <- renderPlot({
  if(input$click){
# generate bins based on input$bins from ui.R
x    <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)

# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white')
   }
   else (return(0))})})

A: If I understand you correctly, you could just change your mainPanel to be a conditionalPanel. Replace your mainPanel code with this:
mainPanel(
  conditionalPanel(condition = "input.click === true",
                   plotOutput("distplot")
  ),
  conditionalPanel(condition = "input.click === false",
                   h4("Just text...")
  )
)

Now, when your check the checkbox, the text box should disappear and your plot shows up.


text:
Q: Select shapefile by their coordinates behaviour I want to filter shapefiles by their latitude behaviour:
If the latitudes of edges A and B are constantly decreasing or increasing then this class marked as correct, otherwise are incorrect.
For example, the red polygon should be marked as incorrect! (Because it starts increasing at the point C.)

This code works but selects also some correct shapefiles (because I set an absolute value for checking the latitude. This behaviour appears in north and south).
Does someone know how can I detect this kind of shapefile?
Code
import shapefile
import numpy as np

sf = shapefile.Reader(r"shapefiles/shapefiles.shp")
of = r"_temp/error.txt"

shapes = sf.shapeRecords()
ids = np.zeros(len(shapes))

output = open(of, 'w')
output.close()
output = open(of, 'a')
for shp in shapes:
    lats = np.zeros(len(shp.shape.points))
    lons = np.zeros(len(shp.shape.points))
    for i in range(0, len(shp.shape.points)):
        point = shp.shape.points[i]
        lats[i] = (point[1])
        lons[i] = (point[0])
    if max(lats)>86.5:
        #print shp.record[0]
        continue
    if min(lats)<-79.2:
        #print shp.record[0]
        continue

    # identification of shapefiles crossing dateline - not needed here
    #if max(lons)>179.9: continue
    #if min(lons)<-179.9: continue
    output.write(shp.record[0]+'\n')
output.close()


text:
Q: Converting a Mercurial repo with bookmarks to Git What's the best way to convert a Mercurial repo which uses bookmarks to a Git repo?
I've tried the steps listed here in Cygwin, but it converted only the default branch to master. The "branch" where I am using a bookmark on was not included in the conversion, although it did issue an error at the start about the Hg repo having an "unnamed" head.
The steps listed here (using git-hg) did not work at all.
Cygwin has Hg 1.9.3 and Git 1.7.5.1 installed, if that helps.

A: Mercurials hg-git plugin does the conversion you want. You need to place a bookmark on every revision you want to export to git, and then hg push /place/to/repo.git to export the commits.


text:
Q: Reportviewer(RDLC) Repeat header on each page not working when exporting to MS word Reportviewer(RDLC)I setup a report to show headerRow on each page.  when Export the report in pdf i can see headerRow on each page, but when export the same report in microsoft word header is only on page1 all other pages are without headerRow.
There are some limitation of exporting into word i can see here ..
http://technet.microsoft.com/en-us/library/cc627455(v=sql.100).aspx
Any Idea how to repeat headerrow in word on each page??

A: Here is a quote from the page you linked to (emphasis is mine):

Word does not repeat header rows on pages two and later although you
  set the RepeatOnNewPage property of the static header row in a tablix
  (table, matrix, or list) to true. You can define explicit page breaks
  into your report to force header rows to appear on new pages. However,
  because Word applies its own pagination to the rendered report
  exported to Word, results might vary and the header row might not
  repeat predictably. The static header row is the row that contains the
  column headings.

It seems like the only possibility is to define explicit page breaks, but this may not work reliably anyway.


text:
Q: Sharepoint calculated field's formula for created by i have a sharepoint list
with 2 users for examole (user A and user B)
i need a calculated field in the list items such that if user "A" created the    item the field vaule will be "X" and if user "B" created the item  fields value would be "Y"
but i couldnt use [created by] in the furmiula of the calculated field !!  why is that ?!! and is there another way to do what i need to do ?!

A: If using Sharepoint Designer is an option you can create a workflow for that list. Set it to start when a new item is created -or- edited, use a condition of "If Created_By equals ..." and an action of "Set yourfield to yourvalue", then add an Else If branch and repeat. This will always override anything a user enters in "yourfield". Takes about 2 minutes to do all of this.

A: I believe you can create a text field that has the default value set to [Me] which should then be usable in a calculated field.

A: For more complicated formulae (i.e. anything with conditional logic), try creating an event handler for the content type (or doc library). This will allow you full control to set the fields to what you desire.
The field can be hidden from the user inside the edit screens.
Make sure use the STSDev from codeplex to setup the solution for deployment.


text:
Q: Error installing Data.Aeson Hello can anyone tell me how can i install the Data.Aeson package?I am running into the following error:
WARNING: cache is out WoAfR NdaItNeG::  Cc:a/cUhsee riss/ aodurti aonf.b edrcaotev:i ciC/:Ap/pUDsaeta/rLso/caadlr/iParno.gbrearmcso/vsitcaic/kA/pxp8D6a_t6a4/-Lwoicnadlo/ws/Pgrhocg-r8a.ms0./2s\ltiabc\kp/xack8a6g_e6.4c-ownfi.ndd\poawcsk/agghec.-c8a.c0h.e2
\glhicb \wpialclk asgeee. caonn fo.ldd\ pvaicekwa goef. ctahcihse
pgahcck awgiel ld bs.e eU saen  'oglhdc -vpikegw  roefc atchhies'  ptaoc kfaigxe.
db. Use 'ghc-pkg recache' to fix.
Error parsing targets: Directory not found: Data.Aeson

Below it says Use ghc-pkg recache.When i try running this command i get the following error:
ghc-pkg.exe: C:\Program Files\Haskell Platform\8.4.2\lib\package.conf.d\package.cache: you don't have permission to modify this file

I have tried installing Data.Aeson both with cabal install Data.Aeson and with Stack install Data.Aeson.With the latter i get the following error:
WARNING:WA caRcNhIeN Gi:s  coaucth eo fi sd oautte :o fC :d/aUtsee:r sC/a:d/riaUns.ebresr/caodvriicain/.AbpeprDcatova/Lioccia/lA/pPprDoagtraa/mLso/csatla/cPkr/oxg8r6a_m6s4/-swtiancdko/wxs8/6g_h6c4--8w.i0n.d2o\wlsi/bg\hpca-c8k.a0g.e2.\cloinbf\.pda\cpkaacgkea.gceo.ncfa.cdh\ep
agchkca gwei.lcla csheee
 gahnc  owlidl lv iseewe  oafn  tohlids  vpiaecwk aogfe  tdhbi.s  Upsaec k'agghec -dpbk.g  Urseec a'cghhec'- ptkog  friexc.a
che' to fix.
Error parsing targets: Directory not found: Data.Aeson

A: Data.Aeson is not a package, it is one of many modules within the package called aeson.  Try cabal install aeson.


text:
Q: Trying to draw an arbitrary background image I've already seen many tutorials trying to put an image as background of my main activity. Tested many ways, and now I'm with this:
<?xml version="1.0" encoding="utf-8"?>

<merge
    xmlns:android="http://schemas.android.com/apk/res/android">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:src="@drawable/library"
        android:scaleType = "centerCrop"
        android:contentDescription="@string/bckgrndimg" />

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical"
    >

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="370dp"
        android:layout_marginLeft="0dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true">
    </ListView>

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/nuevo_libro"
        android:id="@+id/nuevoLibro"
        android:layout_above="@android:id/list"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="42dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/biblioteca_virtual"
        android:id="@+id/textView2"
        android:layout_above="@+id/nuevoLibro"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="31dp" />

</RelativeLayout>
</merge>

Ok, this should go ok, shouldn't it? My "library" image is a 900x600 PNG image, but it just doesn't show up on the screen.
Am I missing something?
Thank you!

A: Do you need an Image View?
You could do something like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/library.."
    ...
>
...
</RelativeLayout>

A: Change Background color of RelativeLayout
android:background="#ffffff"

To
android:background="@android:color/transparent"


text:
Q: How to pull repo from composer.json in a jenkins job I am trying to run composer install in the command shell section of jenkins, but when I build the job, its failing because composer.json contains a repository section.
"repositories": [
    {
        "type": "vcs",
        "url": "git@gitlab*****"
    }
],

in jenkin's Source Code Management I did added the git credentials plus the repository URL (this is working fine and building fine) this is a different repo than the one in the composer.json.
The only problem is that I cant pull the git repo inside the composer.json file (giving permission denied), my thinking is that jenkins doesnt store the ssh keys, it only execute when its building and then remove, am i right to think this? and if so how can I overcome this? And if not what am I doing wrong, how can i avoid having permission denied when pulling git repos inside a composer.json?


text:
Q: ¿Cómo mostrar un ArrayList único de dos clases diferentes? Estoy realizando un ejecicio en el que tengo herencia y polimorfismo sobre dos objetos CuentaCorriente y CuentaAhorro, voy a guardar en un mismo arrayList llamado cuenta que proviene de la clase abstracta CuentaBancaria.
static ArrayList <CuentaBancaria> cuenta = new ArrayList<CuentaBancaria>();

Es decir, en este arraylist añado por una parte los datos de cuenta corriente y por otra parte los datos de cuenta ahorro:
cuenta.add(new CuentaCorriente(numCuenta, ingreso));

cuenta.add(new CuentaAhorro(numCuenta, ingreso));

Si deseo ver en concreto la cuenta corriente o la cuenta ahorro ¿cómo lo haría?

A: Tienes varias opciones, una "tradicional" sería preguntar por la instancia de cada elemento de la lista, por ejemplo:
for (CuentaBancaria cb: cuenta) {
    if (cb instanceof CuentaCorriente) {
         CuentaCorriente cc = (CuentaCorriente)cb;
         // Aquí puedes trabajar con la instancia de CuentaCorriente
         // Para mostrarla o crear una nueva lista o lo que sea.
    } else if (cb instanceof CuentaCorriente) {
         CuentaAhorro ca = (CuentaAhorro)cb;
         // Aquí puedes trabajar con la instancia de CuentaAhorro
    }
}

Otra opción, compatible desde Java 8, sería crear una nueva lista "al vuelo" de una de las clases usando Streams, de esta forma:
List<CuentaCorriente > ctasCorriente = cuenta.stream()
         .filter(cta -> cta instanceof CuentaCorriente )
         .map(cta -> (CuentaCorriente )cta)
         .collect(Collectors.toList());

Si me permites un consejo, a las listas llámalas "listaDeAlgo" o usa un plural como "cuentas", resulta más intitutivo, de cara al mantenimiento posterior del código.


text:
Q: extracting result txt file to specific folder I have a simulation and I am assigning 2 processes to different cores.Every simulation extracts an output file at the end of simulation.The thing is that I want to do, at the end of the simulation, result file should be extracted to specific folder.If the run number is 0 result file should be result0.txt , if it is 1 result1.txt (result file is created by a class while simulating ). I am new in Linux so I don't know bash script.I just try to learn.How can I do this is there any way to do that?
#!/bin/bash
# My first script

count=0
echo -n "Enter a number of simulation > "
read number
echo "Please enter the algorithm type > "
echo -n "0 for NNA  1 for SPA   2 for EEEA > "

while read type; do
    case $type in
        0 ) while [ $count -lt $number ]; do
            cd /home/cea/Desktop/simulation/wsnfuture
        taskset -c $((count % 4)) ./wsnfuture -u Cmdenv omnetpp.ini > wsn1
            count=$((count + 1))
        done
        ;;
        1 ) while [ $count -lt $number ]; do
            cd /home/cea/Desktop/simulation/wsnfuture1
        taskset -c $((count % 4)) ./wsnfuture -u Cmdenv omnetpp.ini > wsn1
            count=$((count + 1))
        done
        ;;
        2 ) while [ $count -lt $number ]; do
            cd /home/cea/Desktop/simulation/wsnfuture2
        taskset -c $((count % 4)) ./wsnfuture -u Cmdenv omnetpp.ini > wsn1
            count=$((count + 1))
        done
        ;;
        * ) echo "You did not enter a number"
        echo "between 0 and 2."
        echo "Please enter the algorithm type > "
        echo "0 for NNA  1 for SPA   2 for EEEA > "
    esac
done

wsn1 just shows the running number and elapsed time of the simulation.


text:
Q: How can I go back to the first view from the third view directly? When I push cancel button in the third view, I want to go back to the first view directly.
I also want to remove the second view.
How can I do that?
This is the code.
// this part is in the first view.
self.second = [SecondController alloc] init];
[self.view addSubview:second.view];

// this part is in the second view.
ThirdController *thirdController = [[ThirdController alloc] initWithStyle:UITableViewStyleGrouped];
self.navigationController = [UINavigationController alloc] initWithRootViewController:thirdController];
[self.view addSubview:navigationController.view];

// this part is in the third view.
- (void)cancel {
    [self.view removeFromSuperview]; // this only goes to the second view.
}

EDIT:
Can I use popToViewController in called contoller? My app crashes.
I thought popToViewController can be used only in calling controller.
And popToViewController is used when it was pushed.
I did add not push.

A: [self.navigationController popToViewController:[[self.navigationController viewControllers] objectAtIndex:0] animated:YES];

A: popToViewController:animated: is a UINavigationController method that you use when popping view controllers off the navigation controller stack. It doesn't fit for this scenario.
This user is adding subviews, not pushing them on a navigation controller stack.
As a note, it appears as a matter of design you should be using a navigation controller with the first view as the root controller, then the second pushed on the stack, and the third pushed on the stack. Then all you have to do is [self.navigationController popToRootViewControllerAnimated:YES].
I think this will work if you want to keep your current architecture:
// this part is in the third view.
- (void)cancel {
    // remove the second view (self.view.superview) from the first view
    [self.view.superview removeFromSuperView];
    // can't recall, possibly you still need to remove the third view, but i think removing the superview will do it.
    // [self.view removeFromSuperView];
}

If you prefer to try the UINavigationController route, then the easiest path is to create a new project in Xcode and select the type for a Navigation-Based Application or a Master-Detail Application. This will create a UINavigationController in a nib and add it to your window. You can then set the root view controller in Interface Builder to your FirstViewController class.
If you prefer to create the UINavigationController in code, then that is also possible. I show that below, along with the rest of the code you need, regardless of whether you create your UINavigationController in a nib in IB or in code.
I also recommend reading the View Controller Programming Guide for iOS.
In your app delegate or some other code:
-(void)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions [
    // I would recommend setting up the UINavigationController and FirstViewController as IBOutlets in your nib, but it can be done in code.
    FirstViewController* fvc = [[FirstViewController alloc] initWithNibName:@"FirstView" bundle:nil];
    UINavigationController* navController = [[UINavigationController alloc] initWithRootViewController:fvc];

    [window addSubView:navController.view];
    [window makeKeyAndVisible];

    [fvc release];
    [navController release];
}

In the first view controller:
SecondViewController* svc = [[SecondViewController alloc] initWithNibName:@"SecondView" bundle:nil];
[self.navigationController pushViewController:svc animated:YES];
[svc release];

In the second view controller:
ThirdViewController* tvc = [[ThirdViewController alloc] initWithNibName:@"ThirdView" bundle:nil];
[self.navigationController pushViewController:tvc animated:YES];
[tvc release];

In the third view controller:
-(void)cancel {
    // returns to the first view controller
    [self.navigationController popToRootViewControllerAnimated:YES];
}

A: Use
- (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated

to go back to a specific view controller.

A: Try this:
[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];

This will pop to the view at index 1. Hope that Helps!

A: // this part is in the third view.
- (void)cancel {
    self.first = [SecondController alloc] init];
    [self.view addSubview:second.view];
}

And I think if you have you don't need to be worried about removing beneath view, later these will removed.