text:
Q: Firebase validation rule to check if movie with same title already exists I'm new to Firebase. I'm making an application which search movies and saves them in the Real Time Database. The data to save follows the below structure:
var movieData = {
    title: "Frozen",
    genre: "Animation"
};

I save the movie this way:
database.ref().child("movies").push(movieData);
This works OK. The problem arises if I try to save it twice so, in my database I'd have the movie duplicated:
{
  "movies" : {
    "-LYSENT90rjBj_fIAHpY" : {
      "genre" : "Animation",
      "title" : "Frozen"
    },
    "-LYSEPufvX3p3w-yXf4d" : {
      "genre" : "Animation",
      "title" : "Frozen"
    }
  }
}

I'm trying to create a validation rule that checks if some movie with the same title already exists. My last attempt is this:
{
  "rules": {
    ".read": true,
    ".write": true,
    "movies": {
      "$pushid" : {
        ".validate": "root.child('movies/' + newData.child('title').val()).val() === null"
      }
    }
  }
}

I find hard to understand how it checks for all movies if the pushidis different for each movie. Moreover, in the simulator, I have seen that I can only test read, set and update methods.
Is there some way to achieve this? Or would be easier to manually check through a query in the client just before pushing the movie?

A: You can't perform filtered queries in security rules.  The only way you can reach back into the database is if you know the full path of the node you want to read.  So I don't think you'll be able to do this with security rules.  Consider instead using Cloud Functions to reactively wipe out invalid data, or mark it as invalid, after it's been added.  Or, as you mentioned, check on the client first, if that helps.

A: How about using like Animation_Frozen as pushid.You can add two string together on client side.
database.ref().child("Animation"+"_"+"Frozen").set(movieData)


text:
Q: use mongoose expires to remove a ref object id from document i have 2 schema  TokenSchema and DriverSchema :
const tokenSchema: Schema = new Schema({
  token: { type: String, required: true },
  creationDate: { type: Date, required: true, expires: '1m', default: Date.now },
});

const driverSchema: Schema = new Schema({
  drivingLicenseNumber: {
    type: Number,
    required: true,
    unique: true,
  },
  name: { type: String, required: true },
  lastName: { type: String, required: true },
  email: {
    type: String,
    required: true,
    unique: true,
  },
  phone: {
    type: String,
    required: true,
  },

  password: {
    type: String,
    required: true,
  },
  token: {
    type: Schema.Types.ObjectId,
    ref: 'Token',
  },
});

i need to remove the token id ref from the driver then i remove the token object is that possible ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to efficiently create a multi-row photo collage from an array of images in Swift Problem
I am building a collage of photos from an array of images that I am placing onto a tableview. I want to make the images wrap when the number of images reaches the boundary of the tableview cell's width (this would allow me to display rows of images in the collage). Currently I get a single row. Please feel free to advise if additional information is required. I am most likely not approaching this in the most efficient way since there is a delay as the number of images used in the array begins to increase. (any feedback on this would be very much appreciated).
Nota Bene

I am creating a collage image. It is actually one image. I want to
  arrange the collage by creating an efficent matrix of columns and rows
  in memory. I then fill these rects with images. Finally I snapshot the resulting image and use it when needed. The algorithm is not
  efficient as written and produces only a single row of images. I need
  a lightweight alternative to the algorithm used below. I do not
  believe UICollectionView will be a useful alternative in this case.

Pseudo Code

*

*Given an array of images and a target rectangle (representing the
target view)

*Get the number of images in the array compared to max number allowed per row

*Define a smaller rectangle of appropriate size to hold the image (so
that each row fills the target rectangle, i.e. - if one image then that should fill the row; if 9 images then that should fill the row completely; if 10 images with a max of 9 images per row then the 10th begins the second row)

*Iterate over the collection

*Place each rectangle at the correct location from left to right
until either last image or a max number per row is reached; continue on next row until all images fit within the target rectangle

*When reaching a max number of images per row, place the image and
setup the next rectangle to appear on the successive row

Using: Swift 2.0
class func collageImage (rect:CGRect, images:[UIImage]) -> UIImage {

        let maxSide = max(rect.width / CGFloat(images.count), rect.height / CGFloat(images.count))

        UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.mainScreen().scale)

        var xtransform:CGFloat = 0.0

        for img in images {
            let smallRect:CGRect = CGRectMake(xtransform, 0.0,maxSide, maxSide)
            let rnd = arc4random_uniform(270) + 15
            //draw in rect
            img.drawInRect(smallRect)
            //rotate img using random angle.
            UIImage.rotateImage(img, radian: CGFloat(rnd))
            xtransform += CGFloat(maxSide * 0.8)
        }

        let outputImage = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

        return outputImage
    }

    class func rotateImage(src: UIImage, radian:CGFloat) -> UIImage
    {
        //  Calculate the size of the rotated view's containing box for our drawing space
        let rotatedViewBox = UIView(frame: CGRectMake(0,0, src.size.width, src.size.height))

        let t: CGAffineTransform  = CGAffineTransformMakeRotation(radian)

        rotatedViewBox.transform = t
        let rotatedSize = rotatedViewBox.frame.size

        //  Create the bitmap context
        UIGraphicsBeginImageContext(rotatedSize)

        let bitmap:CGContextRef = UIGraphicsGetCurrentContext()

        //  Move the origin to the middle of the image so we will rotate and scale around the center.
        CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);

        //  Rotate the image context
        CGContextRotateCTM(bitmap, radian);

        //  Now, draw the rotated/scaled image into the context
        CGContextScaleCTM(bitmap, 1.0, -1.0);
        CGContextDrawImage(bitmap, CGRectMake(-src.size.width / 2, -src.size.height / 2, src.size.width, src.size.height), src.CGImage)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage
    }

Alternative 1
I've refined my solution to this a bit. This one does stack the images in columns and rows however, as stated; my interest is in making this as efficient as possible. What's presented is my attempt at producing the simplest possible thing that works.
Caveat
The image produced using this is skewed rather than evenly distributed across the entire tableview cell. Efficient, even distribution across the tableview cell would be optimal.

class func collageImage (rect:CGRect, images:[UIImage]) -> UIImage {

        let maxSide = max(rect.width / CGFloat(images.count), rect.height / CGFloat(images.count)) //* 0.80
        //let rowHeight = rect.height / CGFloat(images.count) * 0.8
        let maxImagesPerRow = 9
        var index = 0
        var currentRow = 1
        var xtransform:CGFloat = 0.0
        var ytransform:CGFloat = 0.0
        var smallRect:CGRect = CGRectZero

        UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.mainScreen().scale)

        for img in images {

            let x = ++index % maxImagesPerRow //row should change when modulus is 0

            //row changes when modulus of counter returns zero @ maxImagesPerRow
            if x == 0 {
                //last column of current row
                //xtransform += CGFloat(maxSide)
                smallRect = CGRectMake(xtransform, ytransform, maxSide, maxSide)

                //reset for new row
                ++currentRow
                xtransform = 0.0
                ytransform = (maxSide * CGFloat(currentRow - 1))

            } else {
                //not a new row
                if xtransform == 0 {
                    //this is first column
                    //draw rect at 0,ytransform
                    smallRect = CGRectMake(xtransform, ytransform, maxSide, maxSide)
                    xtransform += CGFloat(maxSide)
                } else {
                    //not the first column so translate x, ytransform to be reset for new rows only
                    smallRect = CGRectMake(xtransform, ytransform, maxSide, maxSide)
                    xtransform += CGFloat(maxSide)
                }

            }

            //draw in rect
            img.drawInRect(smallRect)

        }

        let outputImage = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

        return outputImage
    }

Alternative 2
The alternative presented below scales the images so that they always fill the rectangle (in my case the tableview cell). As more images are added they are scaled to fit the width of the rectangle. When the images meet the maximum number of images per row, they wrap. This is the desired behavior, happens in memory, is relatively fast, and is contained in a simple class function that I extend on the UIImage class. I am still interested in any algorithm that can deliver the same functionality only faster.

Nota Bene: I do not believe adding more UI is useful to achieve the
  effects as noted above. Therefore a more efficient coding algorithm is
  what I am seeking.

class func collageImage (rect:CGRect, images:[UIImage]) -> UIImage {

        let maxImagesPerRow = 9
        var maxSide : CGFloat = 0.0

        if images.count >= maxImagesPerRow {
            maxSide = max(rect.width / CGFloat(maxImagesPerRow), rect.height / CGFloat(maxImagesPerRow))
        } else {
            maxSide = max(rect.width / CGFloat(images.count), rect.height / CGFloat(images.count))
        }

        var index = 0
        var currentRow = 1
        var xtransform:CGFloat = 0.0
        var ytransform:CGFloat = 0.0
        var smallRect:CGRect = CGRectZero

        UIGraphicsBeginImageContextWithOptions(rect.size, false,  UIScreen.mainScreen().scale)

        for img in images {

            let x = ++index % maxImagesPerRow //row should change when modulus is 0

            //row changes when modulus of counter returns zero @ maxImagesPerRow
            if x == 0 {
                //last column of current row
                smallRect = CGRectMake(xtransform, ytransform, maxSide, maxSide)

                //reset for new row
                ++currentRow
                xtransform = 0.0
                ytransform = (maxSide * CGFloat(currentRow - 1))

            } else {
                //not a new row
                smallRect = CGRectMake(xtransform, ytransform, maxSide, maxSide)
                xtransform += CGFloat(maxSide)
            }

            //draw in rect
            img.drawInRect(smallRect)

        }

        let outputImage = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

        return outputImage
    }

Efficiency Testing
Reda Lemeden gives some procedural insight into how to test these CG calls within Instruments on this blog post. He also points out some interesting notes from Andy Matuschak (of the UIKit team) about some of the peculiarities of off-screen rendering. I am probably still not leveraging the CIImage solution properly because initial results show the solution getting slower when attempting to force GPU utilization.

A: Since you're using Swift 2.0: UIStackView does exactly what you're trying to do manually, and is significantly easier to use than UICollectionView. Assuming you're using Storyboards, creating a prototype TableViewCell with multiple nested UIStackViews should do exactly what you want. You'll just need to make sure that the UIImages you're inserting are all the same aspect ratio if that's what you want.
Your algorithm is highly inefficient because it has to re-draw, with multiple Core Animation transforms, every image any time you add or remove an image from your array. UIStackView supports dynamically adding and removing objects.
If you still, for some reason, need to snapshot the resulting collage as a UIImage, you can still do this on the UIStackView.

A: Building on alternative 2 provided by Tommie C above I created a function that

*

*Always fills the total rectangle, without spaces in the collage

*determines the number of rows and columns automatically (maximum 1 more nrOfColumns than nrOfRows)

*To prevent the spaces mentioned above all individual pics are drawn with "Aspect Fill" (so for some pics this means that parts will be cropped)

Here's the function:
func collageImage(rect: CGRect, images: [UIImage]) -> UIImage {
    if images.count == 1 {
        return images[0]
    }

    UIGraphicsBeginImageContextWithOptions(rect.size, false,  UIScreen.mainScreen().scale)

    let nrofColumns: Int = max(2, Int(sqrt(Double(images.count-1)))+1)
    let nrOfRows: Int = (images.count)/nrofColumns
    let remaindingPics: Int = (images.count) % nrofColumns
    print("columns: \(nrofColumns) rows: \(nrOfRows) first \(remaindingPics) columns will have 1 pic extra")

    let w: CGFloat = rect.width/CGFloat(nrofColumns)
    var hForColumn = [CGFloat]()
    for var c=1;c<=nrofColumns;++c {
        if remaindingPics >= c {
            hForColumn.append(rect.height/CGFloat(nrOfRows+1))
        }
        else {
            hForColumn.append(rect.height/CGFloat(nrOfRows))
        }
    }
    var colNr = 0
    var rowNr = 0
    for var i=1; i<images.count; ++i {
        images[i].drawInRectAspectFill(CGRectMake(CGFloat(colNr)*w,CGFloat(rowNr)*hForColumn[colNr],w,hForColumn[colNr]))
        if i == nrofColumns || ((i % nrofColumns) == 0 && i > nrofColumns) {
            ++rowNr
            colNr = 0
        }
        else {
            ++colNr
        }
    }

    let outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return outputImage
}

This uses the UIImage extension drawInRectAspectFill:
extension UIImage {
    func drawInRectAspectFill(rect: CGRect, opacity: CGFloat = 1.0) {
        let targetSize = rect.size
        let scaledImage: UIImage
        if targetSize == CGSizeZero {
            scaledImage = self
        } else {
            let scalingFactor = targetSize.width / self.size.width > targetSize.height / self.size.height ? targetSize.width / self.size.width : targetSize.height / self.size.height
            let newSize = CGSize(width: self.size.width * scalingFactor, height: self.size.height * scalingFactor)
            UIGraphicsBeginImageContext(targetSize)
            self.drawInRect(CGRect(origin: CGPoint(x: (targetSize.width - newSize.width) / 2, y: (targetSize.height - newSize.height) / 2), size: newSize), blendMode: CGBlendMode.Normal, alpha: opacity)
            scaledImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
        }
        scaledImage.drawInRect(rect)
    }
}

A: To build the collage in memory, and to be as efficient as possible, I'd suggest looking into Core Image. You can combine multiple CIFilters to create your output image.
You could apply CIAffineTransform filters to each of your images to line them up (cropping them to size with CICrop if necessary), then combine them using CISourceOverCompositing filters. Core Image doesn't process anything until you ask for the output; and because it's all happening in the GPU, it's fast and efficient.
Here's a bit of code. I tried to keep it as close to your example as possible for the sake of understanding. It's not necessarily how I'd structure the code were I to use core image from scratch.
class func collageImage (rect: CGRect, images: [UIImage]) -> UIImage {

    let maxImagesPerRow = 3
    var maxSide : CGFloat = 0.0

    if images.count >= maxImagesPerRow {
        maxSide = max(rect.width / CGFloat(maxImagesPerRow), rect.height / CGFloat(maxImagesPerRow))
    } else {
        maxSide = max(rect.width / CGFloat(images.count), rect.height / CGFloat(images.count))
    }

    var index = 0
    var currentRow = 1
    var xtransform:CGFloat = 0.0
    var ytransform:CGFloat = 0.0
    var smallRect:CGRect = CGRectZero

    var composite: CIImage? // used to hold the composite of the images

    for img in images {

        let x = ++index % maxImagesPerRow //row should change when modulus is 0

        //row changes when modulus of counter returns zero @ maxImagesPerRow
        if x == 0 {

            //last column of current row
            smallRect = CGRectMake(xtransform, ytransform, maxSide, maxSide)

            //reset for new row
            ++currentRow
            xtransform = 0.0
            ytransform = (maxSide * CGFloat(currentRow - 1))

        } else {

            //not a new row
            smallRect = CGRectMake(xtransform, ytransform, maxSide, maxSide)
            xtransform += CGFloat(maxSide)
        }

        // Note, this section could be done with a single transform and perhaps increase the
        // efficiency a bit, but I wanted it to be explicit.
        //
        // It will also use the CI coordinate system which is bottom up, so you can translate
        // if the order of your collage matters.
        //
        // Also, note that this happens on the GPU, and these translation steps don't happen
        // as they are called... they happen at once when the image is rendered. CIImage can
        // be thought of as a recipe for the final image.
        //
        // Finally, you an use core image filters for this and perhaps make it more efficient.
        // This version relies on the convenience methods for applying transforms, etc, but
        // under the hood they use CIFilters
        var ci = CIImage(image: img)!

        ci = ci.imageByApplyingTransform(CGAffineTransformMakeScale(maxSide / img.size.width, maxSide / img.size.height))
        ci = ci.imageByApplyingTransform(CGAffineTransformMakeTranslation(smallRect.origin.x, smallRect.origin.y))!

        if composite == nil {

            composite = ci

        } else {

            composite = ci.imageByCompositingOverImage(composite!)
        }
    }

    let cgIntermediate = CIContext(options: nil).createCGImage(composite!, fromRect: composite!.extent())
    let finalRenderedComposite = UIImage(CGImage: cgIntermediate)!

    return finalRenderedComposite
}

You may find that your CIImage is rotated incorrectly. You can correct it with code like the following:
var transform = CGAffineTransformIdentity

switch ci.imageOrientation {

case UIImageOrientation.Up:
    fallthrough
case UIImageOrientation.UpMirrored:
    println("no translation necessary. I am ignoring the mirrored cases because in my code that is ok.")
case UIImageOrientation.Down:
    fallthrough
case UIImageOrientation.DownMirrored:
    transform = CGAffineTransformTranslate(transform, ci.size.width, ci.size.height)
    transform = CGAffineTransformRotate(transform, CGFloat(M_PI))
case UIImageOrientation.Left:
    fallthrough
case UIImageOrientation.LeftMirrored:
    transform = CGAffineTransformTranslate(transform, ci.size.width, 0)
    transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2))
case UIImageOrientation.Right:
    fallthrough
case UIImageOrientation.RightMirrored:
    transform = CGAffineTransformTranslate(transform, 0, ci.size.height)
    transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2))
}

ci = ci.imageByApplyingTransform(transform)

Note that this code ignores fixing several mirrored cases. I'll leave that as an exercise up to you, but the gist of it is here.
If you've optimized your Core Image processing, then at this point any slowdown you see is probably due to transforming your CIImage into a UIImage; that's because your image has to make the transition from the GPU to the CPU. If you want to skip this step in order to display the results to the user, you can. Simply render your results to a GLKView directly. You can always transition to a UIImage or CGImage at the point the user wants to save the collage.
// this would happen during setup
let eaglContext = EAGLContext(API: .OpenGLES2)
glView.context = eaglContext

let ciContext = CIContext(EAGLContext: glView.context)

// this would happen whenever you want to put your CIImage on screen
if glView.context != EAGLContext.currentContext() {
    EAGLContext.setCurrentContext(glView.context)
}

let result = ViewController.collageImage(glView.bounds, images: images)

glView.bindDrawable()
ciContext.drawImage(result, inRect: glView.bounds, fromRect: result.extent())
glView.display()

A: If someone is looking for Objective C code, this repository might be useful.


text:
Q: cannot find library error when using gcc I am trying to compile an example C program and link it to some static library files using:
gcc -I /usr/local/include -L /usr/local/lib -l libsundials_cvode.a -l libsundials_nvecserial.a cvRoberts_dns.c -o cvRoberts_dns.o

(I am sure that the library files and include files directories above are correct.)
The error I get is:
/usr/bin/ld: cannot find -llibsundials_cvode.a
collect2: ld returned 1 exit status

I have two questions:
1) Am using the -L and -l options correctly?
2) The above error is b/c gcc is looking for the library file in the wrong location right? I tried to fix this by setting $LD_LOAD_PATH via my terminal to /usr/local/bin. I still get the above error. How do I fix this?
Thanks!
-Rohan.

A: Try -lsundials_cvode instead - delete the 'lib' and '.a' parts
Note that LD_LOAD_PATH is for locating dynamic libraries at run-time, not during compilation.
Edit:
I just tried that. The change addresses the cannot find library error but
now I am faced with many "undefined reference to" errors. Does this mean
the linking of the library files has failed somehow? How do I correct this?

It means that there are other symbols that need to be resolved that are not in the library you linked.  Note that you need to change both libraries (you have two on the command line).  Also perhaps they are in the wrong order.


text:
Q: How to do optional reply in Camel I'd like to discard client messages if they don't match the type I expect, but without giving a response back to the client.
Case:
If I'm specting type "A" and client sends "A" then I process "A" and a response is sent as usually.
But if the client sends "B", then just discard the message and continue listening, and, the client-side dies by timeout. I'd like to do this in order to avoid using bandwidth with trash messages and eventually ban IP's that send unexpected content.
I've tried to:

*

*use stop() but this stops processing the exchange but still responding back the original one.

*change the MEP to inOptionalOut but I'm not sure what to do to skip replying.

Does it make sense what I need? :S or just should I settle for replying null or a short text like "banned :P" ?


text:
Q: Lost connection to MySQL server at 'reading initial communication packet' when frequent connection # -*- coding: utf-8 -*-
import MySQLdb
import sitedb

for i in range(5):
    print i
    cred = sitedb.loadmysqlcredential()
    db = MySQLdb.connect(host = cred["host"], user = cred["user"], passwd = cred["passwd"], db = "vg_site_db", charset = 'utf8')
    db.close()

I have MySQL at the different servers: Windows and Linux. At the Win this code work correct. At the Linux on the third iterate mysql sad: Lost connection to MySQL server at 'reading initial communication packet', system error: 0.
What I have to change at the Linux server?
UPD:
The problem is that I have loop (for), and when i = 0 connection happen, also like i = 1 and 2, but next the connection blocked

A: The following is an example of a conneection string I use against a linux db, hope it helps:
 dbSomeDBConnection = MySQLdb.connect(host="10.100.10.2",
                      user="root",
                      passwd="",
                      db="unitTestDB",
                      charset="utf8"
                      )

UPD:
I tested your code against my linux setup (CentOS 6 with MySQL 5.1.73) and I'm not able to reproduce your problem. You may want to try to simplify your credential portion like I did below and see if you still have the issue. Below is what I used to test your stuff and it works fine for me:
# -*- coding: utf-8 -*-

import MySQLdb

for i in range(5):
    print i
    db = MySQLdb.connect(host = "10.100.10.2", user = "root", passwd = "", db = "unitTestDB", charset = "utf8")
    db.close()

A: After googling I find that some times it happen, and reboot can solve problem. I reboot my system and script work correct.


text:
Q: Как сохранить текст формы в браузере при закрытие вкладки или окна? Такая задача.
Есть форма отправки сообщений, человек написал длинное сообщение и вдруг по невнимательности решил закрыть вкладку но при этом забыл отправить свое длинное сочинение.
Вот как сохранить текст который был набран но не отправлен в кеше браузера, чтобы если человек когда откроет снова форму отправки сообщения этот текст туда вставить.
Я так понимаю набранный текст при закрытие вкладки или окна нужно занести в кеш и с текстом id формы куда в будущем нужно будет вставить этот текст, но если сообщение было отправлено то нужно наверное удалять то что заносили в кеш.
Подскажите в какую сторну копать?

A: Обзор доступных методов
На клиенте вы можете хранить информацию с помощью:

*

*Cookies

*HTML 5 Web Storage

До HTML5 единственным способом локального хранения данных было использование механизма файлов cookies, который первоначально был разработан для обмена небольшими объемами идентифицирующей информации между веб-серверами и браузерами. Файлы cookies подходят идеально для хранения небольших объемов данных, но модель JavaScript для работы с ними несколько неуклюжа. Система файлов cookies также вынуждает разработчика возиться со сроками действия и бесполезно пересылать данные туда и обратно по интернету с каждым запросом страницы.
Поэтому, если информация, которую вы собираетесь хранить, не нужна серверу с каждым или большинством запросов, то лучше использовать другое решение.
В HTML5 для этих целей появился Web Storage API, который предоставляет возможность сохранять данные в хранилище браузера посетителя, и дает возможность удобно работать с постоянными данными (localStorage) или временными данными, которые удаляются при закрытии вкладки (sessionStorage)
Для вашей задачи, а именно хранения текста формы обратной связи, идеально подходит использование веб-хранилища, а именно localStorage.
Пример работы с localStorage
Запись данных в хранилище по ключу:
localStorage.setItem("key", "value");

Получение данных из хранилища по ключу:
localStorage.getItem("key");

Удаление данных из хранилища :
localStorage.removeItem("key");

Подробная информация о работе с HTML5 Web Storage

A: Дополню примером:
// при загрузке страницы (когда DOM готова)
document.addEventListener('DOMContentLoaded', () => {
  // восстановление ранее сохраненных данных
  let savedFormData = localStorage.getItem('formData');  // пробуем считать JSON-строку с объектом, хранящим введенные пользователем данные
  if (savedFormData) {                                   // если ранее мы ничего не сохранили, getItem вернет null (и тогда условие не выполнится)
    savedFormData = JSON.parse(savedFormData);           // преобразуем JSON-строку с данными в объект
    // к примеру, у нас есть поля ввода #subject и #message
    document.getElementById('subject').value = savedFormData.subject;
    document.getElementById('message').value = savedFormData.message;
    localStorage.removeItem('formData');                 // после того как мы восстановили сохраненные данные, удаляем запись в localStorage
  }

  // сохранение данных, введенных пользователем
  window.addEventListener('beforeunload', e => {           // назначаем слушателя события, которое возникает при уходе со страницы
    let subj = document.getElementById('subject').value,   // получаем значения содержимого полей ввода
        msg  = document.getElementById('message').value;
    if (subj.length || msg.length) {                       // если текст хотя бы в одном из полей ввода не нулевой длины
      let formData = {                                     // создаем объект, содержащий введенные пользователем данные
        subject: subj,
        message: msg
      };
      // записываем JSON-строку только что созданного объекта с данными
      localStorage.setItem('formData', JSON.stringify(formData));
    }
  });
});


text:
Q: Scanner only reads for loop once? - Java I'm trying to make a class where you input any number of grades (A-F) and calculates the GPA and returns the GPA and eligibility to extracurricular activities. It seems like the scanner only allows one input, then prints the GPA and eligibility.
So far this is what I have:
import java.util.Scanner;

public class Grades
{
    public static void main(String[] args)
    {
        double myGPA;
        int myNumClasses;
        double myValue;

        Scanner sc = new Scanner(System.in);

        System.out.println("Press any other lettter to calculate.");
        System.out.print("Enter grades: ");
        String input = sc.nextLine();

        myValue = 0;
        myNumClasses = 0;
        myGPA = 0;

        for (String next = sc.next(); input.equalsIgnoreCase("a") ||     input.equalsIgnoreCase("b") ||
        input.equalsIgnoreCase("c")|| input.equalsIgnoreCase("d") || input.equalsIgnoreCase("f"); next = sc.next())
        {
            if (input.equalsIgnoreCase("a"))
            {
                myValue += 4.0;
                myNumClasses += 1;
            }

            else if (input.equalsIgnoreCase("b"))
            {
                myValue += 3.0;
                myNumClasses += 1;
            }

            else if (input.equalsIgnoreCase("c"))
            {
                myValue += 2.0;
                myNumClasses += 1;
            }

            else if (input.equalsIgnoreCase("d"))
            {
                myValue += 1.0;
                myNumClasses += 1;
            }

            else if (input.equalsIgnoreCase("f"))
            {
               myNumClasses += 1;
            }

            myGPA = myValue / myNumClasses;

            if (myGPA >= 2.0 && myNumClasses >= 4)
            {
                System.out.println("Eligible");
            }
            else if (myNumClasses < 4)
            {
                System.out.println("Ineligible, taking less than 4 classes");
            }
            else if (myGPA >= 2.0 && input.equalsIgnoreCase("f"))
            {
                System.out.println("Ineligible, gpa above 2.0 but has F grade");
            }
            else if (myGPA <= 2.0 && input.equalsIgnoreCase("f"))
            {
                System.out.println("Ineligible, gpa below 2.0 and has F grade");
            }
            else if (myGPA < 2.0)
            {
                System.out.println("Inelligible, gpa below 2.0");
            }
            System.out.println("Your GPA = " + myGPA);
         }
      }
}

A:     // It looks like your missing a for loop. I just copied some of your
    //code and ran it through a for loop. The rest of the code is kind of unclear.

    System.out.println("Enter the number of grades you will enter: ");
    int userAns = sc.nextInt();

    for (int index = 0; index <= userAns; index++)
    {
       System.out.println("Press any other letter to calculate.");
       System.out.print("Enter grades: ");
       String input = sc.nextLine();
    }


text:
Q: Highstock points don't align with tick correctly I tried to make a line chart with highstock but I got a problem with aligning points with ticks on X-axis.

Here are some of my code snippets for the chart.
 jQuery('#chart-area').highcharts('StockChart', {

                    xAxis: {
                        minRange: 7 * 24 * 3600000,
                        minTickInterval: 24 * 3600000

                    },
                    rangeSelector: {
                        inputEnabled: true,
                        selected: 1,
                        buttons: [
                            {
                                type: 'week',
                                count: 1,
                                text: '1w'
                            },
                            {
                                type: 'week',
                                count: 2,
                                text: '2w'
                            },
                            {
                                type: 'month',
                                count: 1,
                                text: '1m'
                            },
                            {
                                type: 'month',
                                count: 2,
                                text: '2m'
                            },
                            {
                                type: 'month',
                                count: 3,
                                text: '3m'
                            },
                            {
                                type: 'month',
                                count: 6,
                                text: '6m'
                            }
                        ]
                    },

                    title: {
                        text: 'Test Execution Trend'
                    },

                    subtitle: {
                        text: $scope.currentStream
                    },

                    series: [
                        {
                            name: 'Test Success Percentage',
                            pointInterval: 24 * 3600 * 1000,
                            data: $scope.data,

                            marker: {
                                enabled: true,
                                radius: 3
                            },
                            shadow: true,
                            tooltip: {
                                valueDecimals: 0
                            }
                        }
                    ]
                }
            );
        });
    }

I don't even know why this could happen. Is there any problems in my codes?
Here is jsfiddle
http://jsfiddle.net/U85D6/

A: The problem is that your data isn't starting at specific day, but it's about 16:00. Highcharts ticks are placed at 00:00. That example should explain you better:  http://jsfiddle.net/U85D6/1/
I have addeed
    tooltip: {
        xDateFormat: '%A, %b %e, %H:%M'
    },

to show full date for points.


text:
Q: Does each level in a binary search tree need to be ordered? I'm reading about binary search trees, and most resources state that binary search trees need to abide by two rules (vs. regular trees):

*

*Each node has a maximum of up to two children.

*For each node, the values of its left descendent nodes are less than that of the current node, which in turn is less than the right descendent nodes (if any).

But does that mean we can have a tree where the levels are not in chronological order? For example, I found this image online and wasn't sure if it was a valid binary search tree since the third level from the top is not in order. So if I wanted to search for the number 4 I wouldn't know whether to search for it in the left or right branch.

A: This is not a binary search tree, as descendent nodes of a node u include all nodes that can be accessed going down a path starting at u.
Here 11 -> 12 -> 4 is a path down from 11, going first through the right child 12, so 4 is a right descendent node of 11. Since its value is smaller, this tree is not a binary search tree.
As a consequence of these rules, all layers are indeed sorted. In fact the whole in-order traversal is sorted.


text:
Q: VS Code + Git retains files of other branches I'm using VS code + git version 2.20.1 on macOS. Sometimes, when I switch throughout branches, files of other branches are wrongly retained in the current one.
Those files are not present in .gitignore and they are not uncommitted changes.
For example if I have those committed files:

*

*branch_a: file1,file2

*branch_b: file2

if I checkout branch_a in VS Code, I commit all changes and then I switch to branch_b, I still have file1 in my working dir.
Oddly enough, file1 is somehow "invisible" to git. Indeed, this is not considered a potential change to branch_b. This is just ignored even if it is actually on the file system. Let me clarify this from the command line point of view.
$ [git: branch_a] ls
file1   file2
$ [git: branch_a] git status
nothing to commit, working tree clean

$ git checkout branch_b
Switched to branch 'branch_b'
Your branch is up to date with 'origin/branch_b'.

$ [git: branch_b] ls
file1   file2

however, file1 shouldn't be here, but...
$ [git: branch_b] git status
nothing to commit, working tree clean

working tree is considered clean, and even if I rm or I modify the file, git does not detect any changes:
$ [git: branch_b] rm file1
$ [git: branch_b] ls
file2

$ [git: branch_b] git status
nothing to commit, working tree clean

This issue is not systematic but it happens only sometimes. A similar problem has been reported in this SO question and it seems related to a kind of lock managed by VS Code (or by other Code Editors)
I'm wondering if there is a way to avoid this behavior and therefore if I can avoid to clean stale files with git reset --hard + git clean -f -d.

A: Before shifting to other branches make sure you have committed all files in one branch then files of other branches will not be reflected in current branch.


text:
Q: deferredLocationUpdate iOS 6 I have looked up about 3 different pages on how this works. But, I could really use some help because I am getting kCLError = 15. Here is what I have so far then I will explain more.
locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self]
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager startUpdatingLocation];

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *currentLocation = [locations lastObject];
    NSLog(@"%@",[locations lastObject];
    NSLog(@"%d",[CLLocationManager deferredLocationUpdatesAvailable]);
    [locationManager allowDeferredLocationUpdatesUntilTraveled:CLLocationDistanceMax timeout:CLTimeIntervalMax];

After this I have my error code
-(void)locationManager:(CLLocationManager *)manager didFinishDeferredUpdatesWithError:(NSError *)error
{
    NSString *stringError = [NSString stringWithFormat:@"error: %@",[error description]];
    _whatMonitor.text = stringError;
}

So, anyone that can help me I will seriously be so thankful. I have a count of the locations array as well, but this never changes from 1.. It is my understanding that after closing app to home screen and locking the device, the deferredUpdates should kick in. I have checked the [locations count] and it is still 1. I am expecting it to be greater than this..
I do not claim to be very good at this, so if I am making a careless mistake please let me know. I did not copy and paste so there may be some small typos. Thanks in advance.
I am running iOS 6.0 on an iPhone 5.

A: For significant change service and deferred location updates you have to move for the system to record an update.  You have specified CLLocationDistanceMax which is a high value for distance.  You can specify a lower distance to get more frequent changes for example you could specify every 100 meter change to trigger an update as follows:
[locationManager allowDeferredLocationUpdatesUntilTraveled:CLLocation(100) timeout:CLTimeIntervalMax];

Reference: http://developer.apple.com/library/ios/#documentation/CoreLocation/Reference/CLLocationManager_Class/CLLocationManager/CLLocationManager.html


text:
Q: Instagram embeds render HTML in caption It seems today the captions on instagram embeds have started to output HTML instead of the rendered text.
See here: https://www.qthotelsandresorts.com/melbourne/qt-blog/viktor-rolf-fashion-artists/
I noticed this also happens on Instagram's own website
https://www.instagram.com/developer/embedding/

Is there anything wrong with Instagrams code at the moment?

A: Looks like a temporary issue with html entities being encoded, it's fixed now.


text:
Q: Visual studio 2015 RC insallation fatal error I'm facing below issue when I trying to install Visual Studio 2015 RC to my windows 10 OS(Insider preview, Evaluation copy 10130)

A: As of today, VS2015 is already in RTM and Windows 10 has been out for a couple of months now. Have you tried upgrading to the current version of Windows 10 and the latest version of VS2015?
Hope that helps you get around any installation issues.
I have the latest VS2015 on multiple machines running on Windows 10, without any installation issues at the moment. (I did have installation errors in some pre-release versions earlier this year)

A: I got a similar problem. Solved by "Run as Administrator" :)


text:
Q: Bootstrap grid text writing I am working with bootstrap. I have created one grid. A circle is there inside that grid at left side. Now, I want to write some texts besides of that circle. But, whenever I am writing something, it's overlapping with circle. Text should not overlap with circle and vice versa. Specially, It should be responsive. That text part should have a proper margin. In mobile device, suppose content is large, then text should not go to the back of circle. It should increase the height of grid vertically to fill all the contents in it.
This is the problem which is happening, http://s24.postimg.org/8fp4y8c8l/Screen_Shot_2015_08_24_at_7_28_35_am.png
I am expecting something like this one,http://s3.postimg.org/951vbnupf/Screen_Shot_2015_08_24_at_7_31_00_am.png
This is my code :-

.demo-content{
        padding: 15px;
        font-size: 18px;
        min-height: 140px;
        background: #abb1b8;
        margin-bottom: 20px;

padding-top: 40px;
padding-bottom: 10px;
border-radius:5px;

}

#circle {
    background: #FFC40C;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    position:absolute;
    left:5%;
    top:13%;
    }
    .circle-posiiton {
        position:relative;
    }

<title>Example</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

Hi, Stack overflow. It is good.

A: This is a job that the CSS3 calc function could solve. Calculating a padding on content div from the position and width of the circle puts the text in the write place. Here's the CSS I added to your .demo-content class:
padding-left: -webkit-calc(5% + 105px);
padding-left: -moz-calc(5% + 105px);
padding-left: calc(5% + 105px);

I used vendor-prefixed versions too for maximum compatibility. And I used 5% for the position of the circle and 105px for the width of the circle with a 5px margin.

.demo-content{
        padding: 15px;
        font-size: 18px;
        min-height: 140px;
        background: #abb1b8;
        margin-bottom: 20px;
        padding-left: -webkit-calc(5% + 105px);
        padding-left: -moz-calc(5% + 105px);
        padding-left: calc(5% + 105px);

padding-top: 40px;
padding-bottom: 10px;
border-radius:5px;

}

#circle {
    background: #FFC40C;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    position:absolute;
    left:5%;
    top:13%;
    }
    .circle-posiiton {
        position:relative;
    }

<title>Example</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

Hi, Stack overflow. It is good.

A: Adding .demo-content h1 { margin-left: 10%; } in your css should help.


text:
Q: How do I move a window across screens using the same keyboard shortcut for "half-screen"? In my current setup when I press Super+Left the window I'm on snaps to the left, but let's say I want to move it across my current screen to jump another screen to the left, if I press Super+Left again, nothing happens, it just stays snapped to the left.
I know I can press Shift as well to move it across, but I want it to act the same as on Windows, one press to the left snaps it to the left, the next press -> moves it across to the other screen.
I've tried installing compiz-config but haven't been able to find the option I'm looking for there.
I'm running on:

*

*Ubuntu 20.04

*GNOME Shell 3.36.4


text:
Q: How to use hidden parameters in jsp While i click employee name it will open new tab and this employee code has fetched in the value of textbox. That new page has filter process so only need that employee code has value of textbox.
 function view_emp(ecode){
       window.open('SomeServlet?operation=view&&empcode='+ecode ,'_blank');
 }

In that servlet i will redirect new jsp page, and fetch value in textbax. Here that parameters has displayed in the url. How can i pass these value has hidden.

A: The parameter is displayed in url because  you are sending GET request to the server, instead change the request method type to POST and submit, it won't be visible in url now, but you need to some minor changes in servlet/controller code.


text:
Q: Select removes hover state in parent I have a container with some info and a select input. This container opens when you hover over it's parent container. My problem is that in IE and Chrome beta (not too worried about Chrome beta), whenever I try to open the select, the container loses focus and closes.
Check this fiddle: Demo

    Some title

            <select>Select label
                <option>item 1</option>
                <option>item 2</option>
                <option>item 3</option>
            </select>

So I'm wondering if anybody out there has a clever trick or fix for this.
/* EDIT */
So I managed to work around this issue to some extent. It's not perfect but it works. Any improvements you can think of are welcome but for now this is my solution.
var listDropdown = $('.cp-listDropdown');
    var dropdownContent = $('.cp-dropdown-content');

    listDropdown.on("mouseover", function () {
        dropdownContent.css('visibility', 'visible');
    }).on("mouseout", function () {
        setTimeout(function () {
           var isHovered = listDropdown.is(':hover');
           if (!isHovered) {
               dropdownContent.css('visibility', 'hidden');
           }
        }, 1500);
    });


text:
Q: Strange AJAX bug with IE 11 I'm currently working on a purely HTML and JavaScript driven web app that uses CORS for consuming a remote web service but currently having trouble with IE 11 making a GET request. The funny thing is we've got it working fine in IE8/9/10 just not 11.
The problem is that IE 11 appears to timeout and not wait for a response from the server. The ajax call is simply:
$.ajax(url, {
    dataType: 'json',
    complete: complete,
    type: 'GET',
    global: true,
    success: success,
    crossDomain: true,
    xhrFields: {
        withCredentials: true
    }
});

In the network tab and using Fiddler I can see IE never even sends the request.
Does anyone have any ideas please?
EDIT: I forgot to mention I've already tried cache: false. I've also found something very strange in that if I switch document mode in dev tools from Edge to 9 then back again the call works everytime, even after I've cleared IE and restarted it, whether cache is true or false. Very bizarre. :\

A: i'm not sure, maybe it's caching, try to set property "cache: false"
otherwise, you can also try add a datetime at the end of your url, so you have everytime a different url and IE won't cache
url +""+ (new Date()).getTime()

A: Uses this in your in head tag
<meta http-equiv="X-UA-Compatible" content="IE=9,chrome=1">

A: IE is famous for caching. Make sure you are not getting a cached response. You can either set the cache property value to false or add a unique timestamp to the url so that it will not be a cached response. You may use the $.now() method to get a unique timestamp.
Setting the cache property
$.ajax(url, {
    dataType: 'json',
    cache : false,
    //Other things ...
}

Adding a unique timestamp to URL
var url="somePage.php?"+$.now();
//Use this url now for making the ajax call

The $.now() method is a shorthand for the number returned by the expression (new Date).getTime()

A: If you are running local, try switching crossDomain to false.  I spent quite a bit of time stuck on that.  Chrome handled the crossDomain, but in IE if you are not using crossDomain and you have it set to true it will silently fail.

A: I know this thread is old, but just as an extra check for those that encounter this issue, check that your Trusted Sites Zone settings allow access across domains. The first setting under "Miscellaneous" is the setting you want.
Set "Access data sources across domains" to "Enable".


text:
Q: How execute certain function on clicking on the widget? I want to change a boolean variable value and the background of the widget on clicking it ?
here is the the widget xml file
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f15"
android:padding="@dimen/widget_margin"
android:id="@+id/appwidget_layout">

<TextView
    android:id="@+id/appwidget_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:layout_margin="8dp"
    android:textColor="#ffffff"
    android:textSize="24sp"
    android:textStyle="bold|italic" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/appwidget_button"/>

and here is the widget java acticity
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    for (int appWidgetId : appWidgetIds) {

    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.example_app_widget_provider);

        Intent intent = new Intent(context, ExampleAppWidgetProvider.class);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);

        PendingIntent buttonPendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
        views.setOnClickPendingIntent(R.id.appwidget_button, buttonPendingIntent);

        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
}

public boolean buttonState = false;
@Override
public void onReceive(Context context, Intent intent) {

    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.example_app_widget_provider);

    if (intent.getAction()!= null) {

        Bundle extras = intent.getExtras();

        if (buttonState) {
            buttonState = false;
            views.setInt(R.id.appwidget_layout, "setBackgroundColor", Color.GREEN);
            views.setInt(R.id.appwidget_text, "setBackgroundColor", Color.GREEN);
            Toast.makeText(context, "Clicked!!", Toast.LENGTH_SHORT).show();
        } else {
            buttonState = true;
            views.setInt(R.id.appwidget_layout, "setBackgroundColor", Color.RED);
            views.setInt(R.id.appwidget_text, "setBackgroundColor", Color.RED);
            Toast.makeText(context, "Clicked!!", Toast.LENGTH_SHORT).show();
        }

        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        appWidgetManager.updateAppWidget(new ComponentName(context, ExampleAppWidgetProvider.class),
                views);
    }
}

}
when the code runs, the part in the onRecieve method is not executed. I want to know how to receive the click from the same widget that sent the intent, so that I can modify it.
Thanks in advance

A: On top of your Widget class, create a static variable, which will be your onClick:
private static final String MyOnClick = "myOnClickTag";

Define a helper method to automate the creation of each PendingIntent:
protected PendingIntent getPendingSelfIntent(Context context, String action) {
    Intent intent = new Intent(context, getClass());
    intent.setAction(action);
    return PendingIntent.getBroadcast(context, 0, intent, 0);
}

Set this onClick tag to your view as below:
remoteViews.setOnClickPendingIntent(R.id.button,
getPendingSelfIntent(context, MyOnClick));

create an onReceivemethod in your Widget class and set this onClick event inside it:
public void onReceive(Context context, Intent intent) {

    if (MyOnClick.equals(intent.getAction())){

    Bundle extras = intent.getExtras();

    if (buttonState) {
        buttonState = false;
        views.setInt(R.id.appwidget_layout, "setBackgroundColor", Color.GREEN);
        views.setInt(R.id.appwidget_text, "setBackgroundColor", Color.GREEN);
        Toast.makeText(context, "Clicked!!", Toast.LENGTH_SHORT).show();
    } else {
        buttonState = true;
        views.setInt(R.id.appwidget_layout, "setBackgroundColor", Color.RED);
        views.setInt(R.id.appwidget_text, "setBackgroundColor", Color.RED);
        Toast.makeText(context, "Clicked!!", Toast.LENGTH_SHORT).show();
    }

    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    appWidgetManager.updateAppWidget(new ComponentName(context, ExampleAppWidgetProvider.class),
            views);
    }
};

Whenever the view that you set the tag is pressed, onReceive will capture that and will do the action just the same as our everyday, standard onClick event
As for your onUpdate:
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
    for (int appWidgetId : appWidgetIds) {

    RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget_det);
    thisWidget = new ComponentName(context, MyWidgetProvider.class);
    remoteViews.setOnClickPendingIntent(R.id.widget_button_stayarm, getPendingSelfIntent(context, MyOnClick1));
    remoteViews.setOnClickPendingIntent(R.id.widget_button_awayarm, getPendingSelfIntent(context, MyOnClick2));
    remoteViews.setOnClickPendingIntent(R.id.widget_button_dissarm, getPendingSelfIntent(context, MyOnClick3));
    remoteViews.setTextViewText(R.id.widget_textview_gpscoords, "gps cords");
    appWidgetManager.updateAppWidget(thisWidget, remoteViews);
 }
 }


text:
Q: How to insert pseudo between two div? I got a tricky situation when I'm inserting pseudo element to the div element. Here's my html structure.

...

...

...

  (where I want to put the pseudo element)

...

  ...

What I want to do is to add a pseudo element which has {content: ''} and other styles. I've tried to use css selector:
div.methods-collections-lander div.collection:nth-child(3n)::after

But that will insert pseudo element into the div .collection. I don't want to create an element and add it between divs because I do want to change the DOM and bind many js functions with it.
Is that possible to use css to do that?

A: Here's a solution using flexbox and the order property.
Unlike the other answers, this answers your question by inserting a pseudo-element into .collections-list between .collection elements, rather than inserting the pseudo-element into a .collection div.

.collections-list {
  display: flex;
  flex-direction: column;
}

.collections-list::after {
  content: 'Pseudo';
  order: 1;
}

.collection:nth-child(n+4) {
  order: 2; /* the 4th and onward .collection elements have a higher order */
}

1

2

3

4

5


text:
Q: Overwriting a file programmatically in Cocoa This code copies the referenced file and places it in the Docs Directory. I'm trying to build a simple backup solution. The problem is this operation does not overwrite the existing file if the operation is repeated.
Two questions:
What's the best way to overwrite in code?
How difficult would it be to append the current date to each copied file? In this case there would be no overwrite operation. This would be much more useful for keeping incremental backups. If I decide to do it this way I understand I would need to create a new path in order to keep things organized.
Thanks.
Paul
    NSString * name  = @"testFile";
NSArray  * files = [NSArray arrayWithObject: name];

NSWorkspace * ws = [NSWorkspace sharedWorkspace];

[ws performFileOperation: NSWorkspaceCopyOperation
                  source: @"~/Library/Application Support/testApp"
             destination: @"~/Documents/"
                   files: files
                     tag: 0];

A: You could try using NSFileManager, example below (untested):
// Better way to get the Application Support Directory, similar method for Documents Directory
- (NSString *)applicationSupportDirectory {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory();
    return [basePath stringByAppendingPathComponent:@"testApp"];
}

- (void) removeFile {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *applicationSupportDirectory = [self applicationSupportDirectory];
    NSError *error = nil;

    NSString* filePath = [applicationSupportDirectory stringByAppendingPathComponent: @"testFile"];
    if ([fileManager fileExistsAtPath:filePath isDirectory:NULL]) {
        [fileManager removeItemAtPath:filePath error:&error];
    }
}

Edit:
Take a look at the NSFileManager Class Reference for other functions that might be useful (for your second question).


text:
Q: IE8 addon, coded in javascript I've made a small IE8 add-on, the button in the tools bar appears as it should be, but once it is clicked, gives error:
Script: secret
Line: 1
Char 8
Error: Expected ';'
Code: 800A03EC
Source: Microsoft JScript compilation error.

The .js was saved under utf-8, checked with three complicators, there are no syntax errors or ';' missing in there.
The script is of 20 lines, and pretty much all of them  are getElementById() functions.
The first line is a mirror to: var secretVar = document.getElementById('secretId').value;
Yes, I tried content.document.getElementById('secretId').value;
but the same error appears.
Is there something specific that I am missing in the script?
Should there be an additional line to target exactly the page on my IE?


text:
Q: RecyclerView and NestedScrollView take only half of the screen I have a layout where there is an EditText and Button on the bottom of the screen. I want the NestedScrollView along with the RecyclerView to take up the space above the 2 elements. However, they only take a part of it.
Here is my code
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".HomeActivity">

    <androidx.core.widget.NestedScrollView
        android:id="@+id/nestedScrollView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/etMessage"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:context=".HomeActivity">

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/rvMessages"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:nestedScrollingEnabled="true" />

    </androidx.core.widget.NestedScrollView>

    <EditText
        android:id="@+id/etMessage"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter your message"
        android:inputType="text"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/btnSend"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/btnSend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/etMessage" />

</androidx.constraintlayout.widget.ConstraintLayout>

A: Add this line in NestedScrollView
android:fillViewport="true"

A: It will have the same height as your NestedScrollView has if RecyclerView has necessary amount of items in it. You can calculate necessary height of items.
And I aslo don't really think that you need NestedScrollView in your layout 'cause RecyclerView can be scrolled without it.


text:
Q: What is the proof of the formula for $\delta(g(x))$? Consider a function $g(x)$ such that the delta-function is given by $\delta(g(x))$, with $g(x)=0$ at $x_i$. Then we have that $$\sum_i=\frac{\delta(x-x_i)}{|g(x_i)|}.$$
Can someone suggest me a page with a good proof or show me the proof themselves? Thanks.


text:
Q: How to implement Cascaded lookup in SP 2010? In sp 2007, I have used jquery to do the cascade. But now I hear sp 2010 provides cascaded lookup. I have 3 level to drill down (Country > State > City). Is/are there any good instruction on how to implement cascaded lookup? All the lists have been created with parent-child relation.

A: Have a look at the $().SPServices.SPCascadeDropdowns function within SPServices.

A: Read this article, which would help you in creating the cascading dropdowns in SharePoint
Cascading or Filtered Lookup columns in SharePoint
Cascading drop down in SharePoint using REST API (for SP 2013, 2016 versions & SP Online)
Hope this helps you!


text:
Q: Flutter/Riverpod - StateNotifier - call state change before end of method - safe? In my Flutter app I am using two providers to manage a list display...

*

*a 'goalListFutureProvider ' Future provider that retrieves the list of entries to display

*a 'goalCrudProvider' StateNotifier provider that handles add/edit/delete actions on entries in the list

The code for the list provider is shown below, where state changes in the CRUD provider will trigger a refresh of the future list provider
final goalListFutureProvider = FutureProvider<List<GdGoal>>((ref) {
  ref.watch(goalSchedulingProvider);
  ref.watch(goalCrudProvider);
  final aSearch = ref.watch(goalListSearchProvider);
  return ref.watch(goalServiceProvider).find(aSearch);
});

Within my CRUD provider I am calling a state change as part of the process logic,  the 'update' code is shown below..
class GdGoalNotifier extends StateNotifier<bool> {

  Future<bool> update(GdGoal aGoal) async {
    final aRes = await _goalService.update(aGoal);
    state = !state;
    return aRes;
  }

Within the 'update' method is it correct to call 'state = !state' before the end of the function call?   Or should I break out this state refresh to a separate CRUD provider method?


text:
Q: Java Interações Bom dia a todos caros programadores.
Estou iniciando recentemente a liguagem JAVA, gostaria de saber se é possivel realizar como no javascript interatividade do usuario com o software.
Como por exemplo um hover que desfoca uma imagem, ou que muda a cor de um objeto, algo neste sentido.
Venho da linguagem web utilizava javascript, css e html e é muito facil realizar esses procedimentos nestas linguagem.

A: Até consegue. Quando se desenvolve em Java para Desktop é possível criar diferentes interações com o usuário já que existe o conceito das janelas que são construídas em Java mesmo então tem muitas funções que criam esses efeitos. Só que na Web o Java serve como uma linguagem backend, ou seja, rodando no servidor e transparente para o usuário, então o papel de interação é do Javascript, CSS, etc.
O Java na web vai servir mesmo para processar os dados e fazer as lógicas. A interação com o usuário normalmente não é o foco do Java para a web.
Para o Java Desktop é bastante comum usar os recursos Swing ou JavaFX (mais novo) e as IDEs como o Eclipse e Netbeans deixam você criar as telas apenas "arrastando e soltando", para poder se preocupar só com a lógica por trás.


text:
Q: SQL query performance for huge data I have a query:
SELECT c.somecolumn,p.someothercolumn
FROM table1 co
INNER JOIN table2 p(NOLOCK) ON co.COLUMN = p.COLUMN
INNER JOIN table3 c(NOLOCK) ON co.column11 = c.column11
WHERE co.filterColumn = 1

Table2 is a junction table and the join between table1 and table2 is on a column without distinct values (that's the requirement and can't be changed) and hence there are cross joins.
Output of this query results in 180 million records.
Record count:
table 1:  2 190 561
table 2:    568 277
table 3:    300 150

How to optimize the above query? Execution plan:

A: Make sure you at least have indexes on the columns in the joins that include the columns you're returning (for example, in table2, you should have a non-clustered index that is keyed on "p.COLUMN" and includes "p.someothercolumn".  For table 3, key on c.column11 and include c.somecolumn.  You should have an index on table1.filtercolumn.
Consider also, that you have to return 180 million rows to the caller, that takes time.  Try just inserting that data into a throwaway table just to keep the network load time out of your equation.

A: These could be ideally the indexes that are required:

*

*For table1 - filtered index on COLUMN and column11 where co.filterColumn = 1

*For table2 - Index on COLUMN include someothercolumn

*For table3 - Index on column11 include somecolumn

A:

SELECT c.somecolumn
    ,tmp.someothercolumn
FROM table1 co
INNER JOIN table3 c(NOLOCK) ON co.column11 = c.column11
            AND co.filterColumn = 1
CROSS APPLY (SELECT TOP (1) p.SomeOtherColumn
             FROM table2 p(NOLOCK)
    WHERE p.COLUMN = co.Column) tmp


text:
Q: Prolog If Then Else fail with member predicate Hello guys I am working on a prolog game and I need to write a piece of code that will:

*

*Take a number (ArmyNo) from the user.

*Take an X coordinate

*Take an Y coordinate.

Then I have a list that is named TempBoard and it looks like this:
([
    (1,1,-,-),(1,2,-,-),(1,3,-,-),(1,4,-,-),
    (2,1,-,-),(2,2,-,-),(2,3,-,-),(2,4,-,-),
    (3,1,-,-),(3,2,-,-),(3,3,-,-),(3,4,-,-),
    (4,1,-,-),(4,2,-,-),(4,3,-,-),(4,4,-,-)
]).

before I add this (X,Y,w,ArmyNO) to the list I first want to check it if it is already there.
I attempted to do that by using this code but it does not seem to work properly:
%#######Got the number####
        repeat,
    %Get Cordinates X & Y.
    writelist( [TempBoard,'select coordinates for the horizontal axis 1 to 4 to place          your soldier Mr. Human',nl]),
    read(X),
    writelist(['select coordinates for the vertical axis 1 to 4 to place your soldier Mr. Human',nl]),
    read(Y),
    %Check if they are in the list.
          (
              member( (X,Y,w,ArmyNo),TempBoard )  ->
                       (  replace((X,Y,w,ArmyNo),TempBoard,NewBoard) ) ;
                 (
             writelist(['selected positions are not available in the table Mr.Human',nl]) , fail
             )
          ).

          %%

A: (X, Y, w, ArmyNo)

cannot be unified with any member of your example list because w doesn't unify with -. You may have meant W.


text:
Q: I cannot get file handling to work and have followed all the posts I added a text file via As you can see from my code I implemented their code. On running, it gets System.AggregateException with message "access denied to path"
I read the posts:https://learn.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/data/files?tabs=windows
https://forums.xamarin.com/discussion/64887/how-to-read-write-files
Here is my code:
using System.IO;
using System.Reflection;
using System.ComponentModel;

using Xamarin.Forms;
using System;
using System.Threading.Tasks;

namespace ReadTxt
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {

        public MainPage()
        {
            InitializeComponent();

                Label l = new Label()
                {
                    Text = ReadTextLine().Result
                };
                StackLayout s = new StackLayout();
                s.Children.Add(l);
            Content = new ScrollView { Content = s };

            async Task<string> ReadTextLine()
            {
                var backingFile = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "TextFile1.txt");
                using (var writer = File.CreateText(backingFile))
                {
                    await writer.WriteLineAsync("Updated text");
                }

                using (var reader = new StreamReader(backingFile, true))
                {
                    string line;
                    while ((line = await reader.ReadLineAsync()) != null)
                    {

                    }

                    return line;
                }
            }
        } } }

A: You need to add permissions to Android.Manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Check this answer. Maybe it will help you
Xamarin Forms access denied when writing to file with FileStream

A: General, the easier way to handle file is using those methods in the document, something like:
   public MainPage()
    {
        InitializeComponent();

        Label l = new Label()
        {
        };
        StackLayout s = new StackLayout();
        s.Children.Add(l);
        Content = new ScrollView { Content = s };

        var backingFile = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "TextFile1.txt");

        File.WriteAllText(backingFile, "updatedText");
        string text = File.ReadAllText(backingFile);

        l.Text = text;
    }

When debugging your code, it seems you are updating the text in a sub thread which is not allowed both in iOS and Android. Also, I don't think the while statement is necessary while reading the text from the file. I modified your code like below and it works on my side:
public MainPage()
{
    InitializeComponent();

    Label l = new Label()
    {
    };
    StackLayout s = new StackLayout();
    s.Children.Add(l);
    Content = new ScrollView { Content = s };

    ReadTextLine();

    async void ReadTextLine()
    {
        var backingFile = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "TextFile1.txt");
        using (var writer = File.CreateText(backingFile))
        {
            await writer.WriteLineAsync("Updated text");
        }

        using (var reader = new StreamReader(backingFile, true))
        {
            string line;

            line = await reader.ReadLineAsync();

            Device.BeginInvokeOnMainThread(() => {
                l.Text = line;
            });
        }
    }
}

I don't add permissions and it works on Android Q emulator and iOS 13 simulator. You can try to add :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

to AndroidManifest.xml to ask for permissions in Android project as Юра Кириченко mentioned in his answer.


text:
Q: How to communicate with more than one USB Serial devices and Android I am trying to make android code work which can communicate with multiple USB serial devices and android tablet. For this purpose I am using USB Serial Library by FELHR85 https://github.com/felHR85/UsbSerial.
I am able to communicate with single USB device at a time. but, now when I try to connect and communicate with multiple USB serial device App is failing. I am using below code to test with multiple devices.
public class UsbService extends Service {

public static final String ACTION_USB_READY = "com.felhr.connectivityservices.USB_READY";
public static final String ACTION_USB_ATTACHED = "android.hardware.usb.action.USB_DEVICE_ATTACHED";
public static final String ACTION_USB_DETACHED = "android.hardware.usb.action.USB_DEVICE_DETACHED";
public static final String ACTION_USB_NOT_SUPPORTED = "com.felhr.usbservice.USB_NOT_SUPPORTED";
public static final String ACTION_NO_USB = "com.felhr.usbservice.NO_USB";
public static final String ACTION_USB_PERMISSION_GRANTED = "com.felhr.usbservice.USB_PERMISSION_GRANTED";
public static final String ACTION_USB_PERMISSION_NOT_GRANTED = "com.felhr.usbservice.USB_PERMISSION_NOT_GRANTED";
public static final String ACTION_USB_DISCONNECTED = "com.felhr.usbservice.USB_DISCONNECTED";
public static final String ACTION_CDC_DRIVER_NOT_WORKING = "com.felhr.connectivityservices.ACTION_CDC_DRIVER_NOT_WORKING";
public static final String ACTION_USB_DEVICE_NOT_WORKING = "com.felhr.connectivityservices.ACTION_USB_DEVICE_NOT_WORKING";
public static final int MESSAGE_FROM_SERIAL_PORT = 0;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private static int BAUD_RATE = 4800; // BaudRate. Change this value if you need
public static boolean SERVICE_CONNECTED = false;

private IBinder binder = new UsbBinder();

private Context context;
private Handler mHandler;
private UsbManager usbManager;
private UsbDevice device;
private UsbDeviceConnection connection;
private UsbSerialDevice serialPort;

private boolean serialPortConnected;
UsbInterface intf;
SessionManager sessionManager;

/*
 *  Data received from serial port will be received here. Just populate onReceivedData with your code
 *  In this particular example. byte stream is converted to String and send to UI thread to
 *  be treated there.
 */
private UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
    @Override
    public void onReceivedData(byte[] arg0) {
        try {
            String data = new String(arg0, "UTF-8");
            data.concat("\0");
            if (mHandler != null)
                mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT, data).sendToTarget();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
};
/*
 * Different notifications from OS will be received here (USB attached, detached, permission responses...)
 * About BroadcastReceiver: http://developer.android.com/reference/android/content/BroadcastReceiver.html
 */
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) @Override
    public void onReceive(Context arg0, Intent arg1) {

        if (arg1.getAction().equals(ACTION_USB_PERMISSION)) {
            boolean granted = arg1.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
            if (granted) // User accepted our USB connection. Try to open the device as a serial port
            {
                Intent intent = new Intent(ACTION_USB_PERMISSION_GRANTED);
                arg0.sendBroadcast(intent);
                connection = usbManager.openDevice(device);
                serialPortConnected = true;
                new ConnectionThread().run();
            } else // User not accepted our USB connection. Send an Intent to the Main Activity
            {
                Intent intent = new Intent(ACTION_USB_PERMISSION_NOT_GRANTED);
                arg0.sendBroadcast(intent);
            }
        } else if (arg1.getAction().equals(ACTION_USB_ATTACHED)) {
            if (!serialPortConnected)
                findSerialPortDevice(); // A USB device has been attached. Try to open it as a Serial port
        } else if (arg1.getAction().equals(ACTION_USB_DETACHED)) {
            // Usb device was disconnected. send an intent to the Main Activity
            if(intf != null && intf.getInterfaceClass() == UsbConstants.USB_CLASS_HID){
                Intent intent = new Intent(ACTION_USB_DISCONNECTED);
                arg0.sendBroadcast(intent);
                serialPortConnected = false;
                if(serialPort != null)
                    serialPort.close();
            }
        }
    }
};

/*
 * onCreate will be executed when service is started. It configures an IntentFilter to listen for
 * incoming Intents (USB ATTACHED, USB DETACHED...) and it tries to open a serial port.
 */
@Override
public void onCreate() {
    this.context = this;
    serialPortConnected = false;
    UsbService.SERVICE_CONNECTED = true;
    setFilter();
    sessionManager = new SessionManager(context);
    usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    findSerialPortDevice();
}

/* MUST READ about services
 * http://developer.android.com/guide/components/services.html
 * http://developer.android.com/guide/components/bound-services.html
 */
@Override
public IBinder onBind(Intent intent) {
    return binder;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return Service.START_NOT_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    UsbService.SERVICE_CONNECTED = false;
}

/*
 * This function will be called from MainActivity to write data through Serial Port
 */
public void write(byte[] data) {
    if (serialPort != null)
    {
        //Log.e("Serialport Found","Serialport Found");
        serialPort.write(data);
    }
    //Log.e("Serialport Not Found","Serialport Not Found");
}

public void setHandler(Handler mHandler) {
    this.mHandler = mHandler;
}

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) private void findSerialPortDevice() {
    // This snippet will try to open the first encountered usb device connected, excluding usb root hubs
    HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
    System.out.println("<====================== Counter Settings =========================>");
    System.out.println("Counter Baudrate =============>"+sessionManager.getCOUNTER_BAUDRATE());
    System.out.println("Counter DataBits =============>"+sessionManager.getCOUNTER_DATA_BITS());
    System.out.println("Counter StopBits =============>"+sessionManager.getCOUNTER_STOP_BITS());
    System.out.println("Counter Parity =============>"+sessionManager.getCOUNTER_PARITY());
    System.out.println("Counter Flow Control =============>"+sessionManager.getCOUNTER_FLOW_CONTROL());

    System.out.println("<====================== Scale Settings =========================>");
    System.out.println("Scale Baudrate =============>"+sessionManager.getSCALE_BAUDRATE());
    System.out.println("Scale DataBits =============>"+sessionManager.getSCALE_DATA_BITS());
    System.out.println("Scale StopBits =============>"+sessionManager.getSCALE_STOP_BITS());
    System.out.println("Scale Parity =============>"+sessionManager.getSCALE_PARITY());
    System.out.println("Scale Flow Control =============>"+sessionManager.getSCALE_FLOW_CONTROL());

    if (!usbDevices.isEmpty()) {
        boolean keep = true;
        for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
            device = entry.getValue();
            int deviceVID = device.getVendorId();
            int devicePID = device.getProductId();
            intf = device.getInterface(0);
            if(device != null && !device.equals(""))
                Utils.writeIntoFile(getBaseContext(),"device =============>"+device+"\n"+"getInterface Count =============>"+device.getInterfaceCount());

            if (intf.getInterfaceClass() != UsbConstants.USB_CLASS_HID) {
                if (deviceVID != 0x1d6b && (devicePID != 0x0001 || devicePID != 0x0002 || devicePID != 0x0003)) {
                    if(device.getDeviceName().equalsIgnoreCase("/dev/bus/usb/001/004")){
                        BAUD_RATE = Integer.valueOf(sessionManager.getCOUNTER_BAUDRATE());
                        System.out.println("getCOUNTER_BAUDRATE=============>"+BAUD_RATE);
                    }else if(device.getDeviceName().equalsIgnoreCase("/dev/bus/usb/001/003")){
                        BAUD_RATE = Integer.valueOf(sessionManager.getSCALE_BAUDRATE());
                        System.out.println("getSCALE_BAUDRATE=============>"+BAUD_RATE);
                    }
                    // There is a device connected to our Android device. Try to open it as a Serial Port.
                    requestUserPermission();
                    keep = false;
                } else {
                    connection = null;
                    device = null;
                }
            }

            if (!keep)
                break;
        }
        if (!keep) {
            // There is no USB devices connected (but usb host were listed). Send an intent to MainActivity.
            Intent intent = new Intent(ACTION_NO_USB);
            sendBroadcast(intent);
        }
    } else {
        // There is no USB devices connected. Send an intent to MainActivity
        Intent intent = new Intent(ACTION_NO_USB);
        sendBroadcast(intent);
    }
}

private void setFilter() {
    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_USB_PERMISSION);
    filter.addAction(ACTION_USB_DETACHED);
    filter.addAction(ACTION_USB_ATTACHED);
    registerReceiver(usbReceiver, filter);
}

/*
 * Request user permission. The response will be received in the BroadcastReceiver
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) private void requestUserPermission() {
    PendingIntent mPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
    usbManager.requestPermission(device, mPendingIntent);
}

public class UsbBinder extends Binder {
    public UsbService getService() {
        return UsbService.this;
    }
}

/*
 * A simple thread to open a serial port.
 * Although it should be a fast operation. moving usb operations away from UI thread is a good thing.
 */
private class ConnectionThread extends Thread {
    @Override
    public void run() {
        serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
        if (serialPort != null) {
            if (serialPort.open()) {
                serialPort.setBaudRate(BAUD_RATE);
                serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
                serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
                serialPort.setParity(UsbSerialInterface.PARITY_NONE);
                serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
                serialPort.read(mCallback);

                // Everything went as expected. Send an intent to MainActivity
                Intent intent = new Intent(ACTION_USB_READY);
                context.sendBroadcast(intent);
            } else {
                // Serial port could not be opened, maybe an I/O error or if CDC driver was chosen, it does not really fit
                // Send an Intent to Main Activity
                if (serialPort instanceof CDCSerialDevice) {
                    Intent intent = new Intent(ACTION_CDC_DRIVER_NOT_WORKING);
                    context.sendBroadcast(intent);
                } else {
                    Intent intent = new Intent(ACTION_USB_DEVICE_NOT_WORKING);
                    context.sendBroadcast(intent);
                }
            }
        } else {
            // No driver for given device, even generic CDC driver could not be loaded
            Intent intent = new Intent(ACTION_USB_NOT_SUPPORTED);
            context.sendBroadcast(intent);
        }
    }
}

}
do anybody have any idea how can I achieve this. I am also open to use another library that can help me connect multiple USB serial devices at a time.


text:
Q: wcf reference not being generated correctly Ran across a weird problem with my WCF references this morning. In a nutshell, I have a duplex service set up so that a server can notify a client by sending objects in a data contract. When a client connects, it runs a function on the server to return a List(Of NewItem) based on what's in the shared queue of the service class. The trouble is, when I update my service reference in the client, it says the function returns a NewItem object, not a List(Of NewItem) object. I can go into the reference and manually change it to a List object and it'll transfer just fine. Any ideas why the service reference generator would arbitrarily change my return type?
Here's the relevant code:
<ServiceContract(
    CallbackContract:=GetType(INotifyCallback),
    SessionMode:=ServiceModel.SessionMode.Required)>
Public Interface INotifyService
    <OperationContract()>
    Function GetNewServerItems() As List(Of NewItem)
End Interface

<DataContract>
<Serializable>
Public Class NewItem
    <DataMember()>
    Public Property ItemNum As String

    <DataMember()>
    Public Property Timestamp As DateTime
End Class

<ServiceBehavior(
    ConcurrencyMode:=ServiceModel.ConcurrencyMode.Single,
    InstanceContextMode:=ServiceModel.InstanceContextMode.Single)>
Public Class NotifyService
    Implements INotifyService

    Shared _server_items As New List(Of NewItem)

    Public Function GetNewServerItems() As List(Of NewItem)
        Return _server_items
    End Function
End Class

And in Reference.vb (simplified):
<System.ServiceModel.OperationContractAttribute(Action:="http://tempuri.org/INotifyService/GetNewServerItems", ReplyAction:="http://tempuri.org/INotifyService/GetNewServerItemsResponse")>  _
Function GetNewServerItems() As NotifyGateway.NewItem()

A: You and I fell into the same trap: we both misread the VB.NET code generated for the proxy method as returning a single item. In fact, it is returning an array.
WSDL uses XML Schema to describe the shape of the request and response. XML Schema has no concept of a "list", only of a sequence. By default, when it sees a sequence of items, "Add Service Reference" generates an array. You can change this to generate a "List", simply by changing the collection type on the "Advanced" tab of the "Add Service Reference" or "Configure Service Reference" dialogs.

A: When adding a reference the way you did, you should change the "Collection type" in the Advanced Service Reference Settings (Add Service Reference dialog) to "system.Collections.Generic.List". By default it is "System.Array".
I would not recomend though using the Add Reference way because you lose control over the configuration of your WCF service, and VS adds a lot of garbage that you do not need, and that would make your client/service link harder to maintain.
Hope this helps.

A: There is another, less well-known, but more powerful mechanism for preserving the collection types without resorting to using the default collection type setting.
This mechanism is especially useful if you have CollectionDataContract classes that you use in your code on both sides of a WCF pipe.
The solution involves editing the svcmap that is generated as part of the WCF service reference and adding specific CollectionMapping entries for each of the collection types that you want to serialize. The primary thing to watch out for here is generics: if WCF finds more than one match for a given class, it will refuse to generate the code.
To actually make the changes:
1) Show all of the files in the project which contains your WCF service reference.
2) Expand your service reference
3) Double-click on the Reference.svmap file to edit it.
4) Add your entries in the CollectionMappings section (if it does not exist, you can add it).
For example, in order to transfer generic Dictionaries and Lists, and to transfer StringCollections, you can have the following entries:
<CollectionMappings>
  <CollectionMapping TypeName="System.Collections.Generic.Dictionary`2" Category="Dictionary" />
  <CollectionMapping TypeName="System.Collections.Generic.List`1" Category="List" />
  <CollectionMapping TypeName="System.Collections.Specialized.StringCollection" Category="List" />
<CollectionMappings>

The first item with a category of Dictionary will serve as the default Dictionary collection type and the first item with a category of List will serve as the default Collection type.
We have over 200 collection classes that we use this way for Silverlight and Windows Forms clients and it is an extremely efficient way to reuse your own code on both sides of a WCF pipe.
One important note: to reuse your classes, you need to ensure that the "Reuse types in referenced assemblies" flag in the service reference configuration is checked or that that the GenerateInternalTypes flag in the reference.svmap is set to false (these are the same thing).


text:
Q: "Data Repository" software solution I am trying to find a software solution that will allow our group to easily upload datasets (scriptable and or through some UI), tag those datasets, retrieve those datasets, access control for the datasets, search the tags, search the files name/attributes/metadata (e.g. file creation date). The datasets can be anything from CSV files, image(binary) datasets, texts, server logs, folders within folders of images, zip files of csv data. It can be anything. We will need to be storing GBs to potentially PBs of data. A single file can range from a few KB to 100's of GB. Usable API to retrieve these datasets programmatically.
We just want to have a centralized location of finding information and we want to be able to answer a question such as "Hey do you know if we have any lightening strike datasets?" If there is a file/folder/zip file tagged with "lightening" when I search it should pull back that dataset.
A possible solution would be something like Dataverse, Dspace, Fedora Commons, CKAN. However, those seem to be really geared towards academia and publications or small datasets. On top of that they remove any type of complex folder structure that might exist (e.g. Folder1-->subFolder1-->subFolder2). I also question the scalability of having a 10 million 100kb files within one of these systems.
A filesystem share would allow us to simply store whatever we want but I don't know of a reasonable way of enabling tagging of data.
It is almost like I am looking for a combination of the two. Does someone know of a tool preferably open source that would be able to do something like this?

A: From what you have described so far, DSpace does seem to be a good fit.
With following examples I want to address the concerns you raised:
Scalability
Here's an example of a multi-terabyte item:
https://ore.exeter.ac.uk/repository/handle/10871/14881
Complex structure
Dryad is based on DSpace and uses a more complex data model, with data files, data packages and the original publication each being represented as separate objects:
http://datadryad.org/resource/doi:10.5061/dryad.322vn
If that's what you want, you can also start your project off the Dryad codebase, since this one is open source as well:
https://github.com/datadryad/dryad-repo


text:
Q: How to expand * on Bash command line I understand that if you type ls * it is actually expanded to ls a b c when the current directly has files a, b and c.
I was wondering if there is a way to expand this before I hit enter. Similar to how Ctrl+X works, or tab complete works.
So to make myself clear
$ ls *
<press magic key>
$ ls a b c

in a similar way to:
$ ls ~/
<press tab>
$ ls /home/username

I thought I'd seen this before but I might have been mistaken.

A:
$ bind -q glob-expand-word
glob-expand-word can be invoked via "\C-x*".

$ bind -q insert-completions
insert-completions can be invoked via "\e*".

So to use these we can do
ls * Ctrl+x *
or
ls * Esc *
Expand complicated lines before hitting enter

A: In bash, the readline capability is called glob-expand-word and is bound to CtrlX* by default.

A: You can use the glob-expand-word function, from man bash:

The word before point is treated as a pattern for pathname
expansion, and the list of matching file names is inserted,
replacing the word. If a numeric argument is supplied, an
asterisk is appended before pathname expansion.

Add something like this to your ~/.inputrc:
Control-x: glob-expand-word

So $ ls * followed by Ctrl-X will expand to $ ls a b c, in your example.

A: When you are in vi mode (set -o vi), the "magic key" is Esc*. This works with both bash and ksh.

A: An alternative to glob-expand-word (\C-x*) is insert-completions (\e*). It works without an asterisk at the end, but it also includes other completions like hidden files. I have rebound both in ~/.inputrc:
# insert glob results (\C-x* by default)
"\C-g": glob-expand-word

# insert completion list (\e* by default)
"\ei": insert-completions

glob-complete-word (\eg) can be used to convert for example /System/Library/Launch*/*Finder to /System/Library/LaunchAgents/com.apple.Finder.plist.


text:
Q: EF Core 2 cross database migrations I am trying to create a cross database migration by using EF Core 2.0
When I am at the office I work by using a shared sql server database with the team. For this reason the code uses a configuration that reference the sql server provider
optionsBuilder.UseSqlServer(connectionString, serverOptions => {
    serverOptions.MigrationsHistoryTable("__EFMigrations", "dbo");
});

When a new migration is created this make the migration code use specific configuration of the sql server provider like
migrationBuilder.CreateTable(
    name: "Customers",
    schema: "dbo",
    columns: table => new
    {
        EntityID = table.Column<int>(nullable: false)
            .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
        Name = table.Column<string>(maxLength: 255, nullable: false)
    },
    constraints: table => {
        table.PrimaryKey("PK_Customers", x => x.EntityID);
    });

Please note the Annotation method.
When out of office I am using a postgreSQL instance installed on my mac and I need to have a slightly different migration which makes use of the specific postgreSQL provider
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),

I know that I can manually modify the migration to specify both annotation as this does not have impact when running on a specifica database type.
However manually modify the migration is a tedious and error prone job that I would like to avoid.
Is there any way to make EF generate both Annotation methods automatically?
I have also tried to use the DbContext OnModelCreating method by specifying options on the ModelBuilder
modelBuilder
    .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn)
    .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

or
modelBuilder.ForNpgsqlUseSerialColumns();
modelBuilder.ForSqlServerUseIdentityColumns();

but the generated migration it is always related to the provider used at that specific moment.

A: There is no way to get EF Core to do it for you. What you're doing is the best approach. A slightly less tedious approach is to keep two separate sets of migrations--one for each provider.
See EF Core Migrations with Multiple Providers for more details.


text:
Q: How can a perform a repeated measures ANOVA if assumptions aren't met + error message 0 (non-NA) cases? I hope one of you is able to give me some help with the correct statistical test for my data. I've been studying the effect of temperature on the physiology of large benthic foraminifera. Right now, I am analyzing my PAM data, so I have 3 variables

*

*Yield; my response variable => a proportion between 0 and 1

*Temperature; factor with 5 levels (33.1, 30.3, 24.4, 18.6 and 15.6 degrees Celsius)

*Time; photosynthetic yield is measured over 4 weeks so Factor with 4 levels (T1, T2, T3 and T4)

So I have Yield ~ Temperature * Time (not sure yet if the interaction is significant because I can't seem to find the right model to check this)
The data is highly left-skewed, the variance is not homogenous and my data contains some outliers but these are actual measurements. First I thought of transforming my data. So I tested the ascsine transformation (p'=arcsin[sqrt(p)]), square transformation (Y'=Ysq2) and the antilog transformation (Y'=e(sqY)). All of these transformation still don't make the data normally distributed.
Since it's proportion data, I was thinking of using a two-way ANOVA with binomial distribution, but I get underdispersion. When I correct for this using a quasibinomial, the "Residual deviance: 0.91405 on 80 degrees of freedom" stays exactly the same so it remains underdispersed.
model_binom <- glm(Yield ~ Temperature * Time, data=pam, binomial)
model_quasibinom <- glm(Yield ~ Temperature * Time, data=pam, quasibinomial(link="logit"))

Another thought I had was performing a Repeated Measures ANOVA because I measured the same pool of individuals over the different time points. But the assumptions aren't met. However if I do continue trying to perform the test I get an error message.
res.aov <- anova_test(
data = pam, dv = Yield, wid = Vial,
within = c(Temperature, Time)
)
get_anova_table(res.aov)

Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) : 0 (non-NA) cases I've tried to solve this by adding another column "id" making it a factor, but this doesn't solve the problem.
I read there are no non-parametric alternatives to the two-way and the three-way repeated measures ANOVA.
Does anyone have a suggestion of how to properly analyze this data and which test to use in R? Thanks a lot in advance!


text:
Q: $P(\vert X \vert < \vert Y \vert)$ where $X$, $Y$ are independent normal Is there a non-vacuous upper bound (always < 1) in terms of elementary functions (polynomials and exponentials) for $P(\vert X \vert < \vert Y \vert)$ where $X \sim N(0, \sigma_1^2)$, $Y \sim N(0, \sigma_2^2)$?
One approach I have attempted is to apply Gaussian tail bound as follows:
$$
\begin{aligned}
P(\vert X \vert < \vert Y \vert)
&= \int P(\vert x \vert < \vert Y \vert) P(x) dx \\
&\leq \int 2 \exp \left( - \frac{x^2}{2\sigma_2^2} \right) \frac{1}{\sqrt{2\pi} \sigma_1} \exp \left( - \frac{x^2}{2\sigma_1^2} \right) dx \\
&= \frac{2 \hat{\sigma}}{\sigma_1} \\
\end{aligned}
$$
where $\hat{\sigma} = \frac{1}{\frac{1}{\sigma_1^2} + \frac{1}{\sigma_2^2}}$.
Unfortunately, this bound is vacuous as in $\frac{2 \hat{\sigma}}{\sigma_1}$ could be greater than 1.