text:
Q: Get rownames associated with each column based on binary matrix in R I have a matrix with binary data representing whether each column field is relevant to each row element. I'm looking to create a two column dataframe identifying the name of each field associated with each row. How can I do this in R?
Here is an example of what I'm starting with:
   A B C
 W 1 1 0
 X 0 1 1
 Y 1 1 1
 Z 0 1 1

And I'm looking to end up with this:
Element | Relevant Field
       W|A
       W|B
       X|B
       X|C
       Y|A
       Y|B
       Y|C
       Z|B
       Z|C

Any hints? Thanks!

A: If your starting value is a matrix like this
mm <- matrix(c(1L, 0L, 1L, 0L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L),
  ncol=3, dimnames = list(c("W", "X", "Y", "Z"), c("A", "B", "C")))

You can treat it like a table and unroll the data faairly easily
subset(as.data.frame(as.table(mm)), Freq>0)
#    Var1 Var2 Freq
# 1     W    A    1
# 3     Y    A    1
# 5     W    B    1
# 6     X    B    1
# 7     Y    B    1
# 8     Z    B    1
# 10    X    C    1
# 11    Y    C    1
# 12    Z    C    1

A: We can use base R methods
data.frame(Element = rep(rownames(m1), each = ncol(m1)),
    Relevant_Field = rep(colnames(m1), nrow(m1)))[as.vector(t(m1))!=0,]

Or with CJ
library(data.table)
CJ(Element = row.names(m1), Relevant_Field = colnames(m1))[as.vector(t(m1)!=0)]
#    Element Relevant_Field
#1:       W              A
#2:       W              B
#3:       X              B
#4:       X              C
#5:       Y              A
#6:       Y              B
#7:       Y              C
#8:       Z              B
#9:       Z              C

Or as @Frank suggested, we can melt (using reshape2) to a three column dataset, convert to data.table and remove the 0 values
library(reshape2)
setDT(melt(m1))[ value == 1 ][, value := NULL][]

A: Here is another base R method that uses with and subsetting.
# get the positions of 1s in matrix (row / column) output
posMat <- which(mm==1, arr.ind=TRUE)

# build the data.frame
myDf <- data.frame(rowVals=rownames(mm)[posMat[, 1]],
                  colVals=colnames(mm)[posMat[, 2]])

or other structures...
# matrix
myMat <- cbind(rowVals=rownames(mm)[posMat[, 1]],
               colVals=colnames(mm)[posMat[, 2]])

# vector with pipe separator
myVec <- paste(rownames(mm)[posMat[, 1]], colnames(mm)[posMat[, 2]], sep="|")


text:
Q: Garbage Collection for BinaryReader/FilesStream I am currently baffled by C# garbage collection of the following code. It is almost as if it doesn't believe the object should be thrown away.
using (br = new BinaryReader(new FileStream("mydata.bin", FileMode.Open, FileAccess.Read, FileShare.Read)))
{
    byte[] blah = br.ReadBytes(364000000);
}

I have tried System.GC.Collect(); br.Close(); br.Dispose(); all to no avail. Unfortunately, because I need to open multiple large files, I get an out of memory exception. Obviously I can read the bytes incrementally instead of all at once, but I am trying to understand/resolve the underlying issue of it holding onto the memory.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Popup when click button I have a simple html with a button
I subscribed to mailchimp (newsletter and forms widget)
and I got from them a code for my site that works when
you load the page.
I want the page to execute the code (open the pop up)
only when I click the button. can you help me with it?
(I feel it's kind of a easy one but I'm get a bit scared
cause it's a script code - I don't know why...)
this is my page - in the head there's the script
<html>
<head>

<script type="text/javascript" src="//s3.amazonaws.com

/downloads.mailchimp.com/js/signup-forms/popup/embed.js" data-dojo-`config="usePlainJson: true, isDebug: false"></script>`

<script type="text/javascript">require(["mojo/signup-forms/Loader"], function(L) { L.start({"baseUrl":"mc.us7.list-manage.com","uuid":"d5b6774fb8bf432d69df52d93","lid":"3ed431a3b6"}) })</script>

</head>
<body>

<button type="button">Click Me!</button>

</body>
</html>

also,
I upload it to a server - so this is the page online:
http://judamenahem.com/popuplp2/popup.html

A: You can use standard popup boxes (those boxes that most sites use for: "Hey, you won X, do you really want to leave?") to ask the person a question via alert().
Here is some documentation on them. http://www.w3schools.com/js/js_popup.asp
You would simply need to attach a ClickEventHandler onto your button in your JS that triggers alert().

A:

function myFunction() {
    alert("I am an alert box!");
}
<button type="button" onclick="myFunction()">Click Me!</button>

So when you Click on Submit button then it open alert box

A: There is also prompt() function, which lets the user interact with the box

A: You just have to add to the onClick of the button the code which is in the head who load the current popup.
function myFunction() {
    require(["mojo/signup-forms/Loader"], function(L) { L.start({"baseUrl":"mc.us7.list-manage.com","uuid":"d5b6774fb8bf432d69df52d93","lid":"3ed431a3b6"}) });
 }

and use :
 <button type="button" onclick="myFunction()">Click Me!</button>


text:
Q: QF_NIA script terminates instantly with Z3 4.3.2, but not with 4.4.2 This script produces a correct model in almost no time with Z3 4.3.2, but runs seemingly forever with Z3 4.4.2 and timeouts after a few seconds on Rise4fun.  A version of the script for n=5 (the one linked has n=4) runs for a long time also on 4.3.2.  I tried changing sat.random_seed and smt.random_seed, but to no avail.  What else can I try?

A: Thanks for the example. The bit-blaster now detects that this is finite domain. It was not handling "distinct" so therefore falling back to the default solver that uses a super-expensive Groebner bases computation. It can be turned off, but better to fix the finite domain detection.


text:
Q: Create IT-system for a private company in NemLog-in Is it only possible to create public IT-systems in NemLog-in or not? I'm using the ITfoxtec Identity Saml 2.0 component. It looks like the ITfoxtec SAML 2.0 sample is configured with an IT-system for a private company.

A: The 'old' NemLog-in 2 supporting NemID only support public IT-systems. Where the new NemLog-in 3 supporting MitID (and NemID) both support public IT-systems an IT-systems for private companies.
Updated
The ITfoxtec SAML 2.0 sample is configured with a private IT-system in NemLog-in 3.


text:
Q: Two videos on one page carousel - Chromium I have 2 vides hosted on a server.
In Chromium browser (Version 65.0.3325.181) https://server/index.html is loaded.
Using Javascript,  2 video elements are inserted after window.onload and the 1st one is started.
Both inserted like:
let video = document.createElement('video');
        video.setAttribute('width', '100%');
        video.setAttribute('height', '100%');
        video.setAttribute('preload', 'auto');

        let source = document.createElement('source');
        source.setAttribute('src', <http://server/video/path>);
        source.setAttribute('type', 'video/mp4');

        video.appendChild(source);

After finish video.on('ended') video element becomes hidden. And next video element becomes visible and started.
Everything works fine:
2 video elements created and hidden.
Immediately 1st video element started and playing ..
On 1st video ended - it becomes hidden
Second video becomes visible and started ... successfully reach its end and becomes hidden again...
then start again from 1st video...
I have following observation.
First video is always playing smootly after initially cached.
Second video is always playing with glitches and freezes of few milliseconds.
I am using Chromium on Raspberry Pi 3.
When first video starts: CPU is like 40-50-60%
Everytime the second video starts: CPU is like 120-220% and with glitches and freezes.
The issue is not video or encoding related, because when i switch places: the new 2th video (which was 1st before) becomes the problematic one. Always the second video!
Why this can be?
Can you give me some clue or direction what it might be?

A: One possible reason is that the first video is using the Raspberry PI's built in Broadcom HW video decoding, but the second one is having to fall back to SW decoding.
The same affect can be seen on many computers if you play multiple videos and exceed what decoding the platform can handle in HW - a typical approach is to fall back on some form of SW decoding, or perhaps to simply give priority to the first video(s) playing.
There are also restrictions to the codec and frame rates supported on most video cards, although this does not sound like the issue you are seeing as the video sounds like it plays fine when it is the only or the first video.


text:
Q: picture viewer in c# .net Regarding .Net technology,What will be the basic element of a picture viewer(like Windows Picture and Fax Viewer)? Is it a user control inside a form, or is it something other components. Could you please give me an idea in the context of C#.Net

A: You don't really get one that's bundled into .NET Framework (and that's probably a good thing, it's fairly large already).
If using WinForms, the nearest thing you do get is the PictureBox component, and the BackgroundImage property of some other components like Form and Panel. But you have to implement the rest of the functionality of an image viewer yourself.
WPF certainly has its own equivalents but I can't name them off the top of my head.

A: for making picture viewer is better to have PictureBox to show Pictures, ImageList   to hold list of images due to have more that one picture and also two buttons for next   pictur and previews picture.
a simple code which I suggest is as follow:
private void btnLoadImage_Click(object sender, EventArgs e)
    {
        imageList1.Images.Clear();
        if (openFDialogImage.ShowDialog() == DialogResult.OK)
        {
            for (int i = 0; i < openFDialogImage.FileNames.Length; i++)
            {

imageList1.Images.Add(Image.FromFile(openFDialogImage.FileNames[i]));
            }
            pictureBox1.Image = imageList1.Images[currentIndex];
        }
    }

    private void BtnForward_Click(object sender, EventArgs e)
    {
        if(currentIndex!=imageList1.Images.Count-1 && imageList1.Images.Count > 0)
        {
            pictureBox1.Image = imageList1.Images[currentIndex++];
        }

    }

    private void btnBack_Click(object sender, EventArgs e)
    {
        if (currentIndex!=0)
        {
            pictureBox1.Image = imageList1.Images[--currentIndex];
        }
    }

Thats all, :)


text:
Q: Invalid url's throw an exception - python import httplib
import urlparse

def getUrl(url):
   try:
     parts = urlparse.urlsplit(url)
     server = parts[1]
     path = parts[2]
     obj = httplib.HTTPConnection(server,80)
     obj.connect()
     obj.putrequest('HEAD',path)
     obj.putheader('Accept','*/*')
     obj.endheaders()
     response = obj.getresponse()
     contentType = response.getheader("content-type", "unknown")
     obj.close()
     if response.status !=200:
       print 'Error'
     else:
       print 'Awesome'
   except Exception, e:
     print e

I wrote the code above to check if a given URL is valid or not. But somehow when I test it, for every invalid url it throws an exception.
>>> getUrl('http://www.idlebrfffain.com')
[Errno -2] Name or service not known

Python version:
chaitu@ubuntu:~$ python -V
Python 2.6.4

Can anyone help me find out where exactly is the mistake?

A: That's supposed to happen.  An exception is being thrown because the URL cannot be resolved.  This is thrown prior to your if response.status != 200 line which turns control over to your except block.
You need to spend some time looking into how Exceptions work.  Here's an example of something you could try.
def getUrl(url):
    status = None
    try:
        # do your normal stuff...
        status = response.status
    except Exception, e:
        # do whatever you want here...
        pass
    finally:
        if status != 200:
            print "Error"
        else:
            print "Awesome"

A: You have to catch socket.error:
import httplib, socket
import urlparse

def getUrl(url):
    parts = urlparse.urlsplit(url)
    server = parts[1]
    path = parts[2]
    obj = httplib.HTTPConnection(server,80)

    try:
        obj.connect()
    except socket.gaierror:
        print "Host %s does not exist" % server
        return
    except socket.error:
        print "Cannot connect to %s:%s." % (server, 80)
        return

    obj.putrequest('HEAD',path)
    obj.putheader('Accept','*/*')
    obj.endheaders()
    response = obj.getresponse()
    contentType = response.getheader("content-type", "unknown")
    obj.close()
    if response.status !=200:
        print 'Error'
    else:
        print 'Awesome'

getUrl('http://www.idlebrfffain.com') # not a registered domain
getUrl('http://8.8.8.8') # not a http server

Only try: except: around specific lines and only if you know what happens. Python will show you tracebacks for uncaught exceptions, so you can find out where the problem is with ease.

A: #The following code validates a url. This is a 2 step process, to do that. First I validate the domain and next the path attached to the domain.
from urlparse import urlparse
import urllib2
import socket
class ValidateURL:
    def __init__(self, url):
        self._url = url

    def startActivity(self):
        self._parts = urlparse(self._url)
        a = self._checkDomain(self._parts[1])
        if a:
            b = self._checkUrl(self._url)
            if b == 1:
                print self._url,' is valid'
            else:
                print 'The path ',self._parts[2],' is not valid'
        else:
            print self._parts[1],' domain does not exist'

    #Checks whether the domain is right or not
    def _checkDomain(self,domain):
        x = 1
        try:
            socket.gethostbyname_ex(domain)
        except socket.gaierror:
            x = 0
        except socket.error:
            x = 0
        finally:
            return x

    #Checks whether the path is right or not
    def _checkUrl(self,url):
        x = 1
        self._req = urllib2.Request(url)
        try:
            urllib2.urlopen(self._req)
        except urllib2.URLError, e:
            #print e
            x = 0
        finally:
            return x

if __name__ == "__main__":
    valid = ValidateURL('http://stackoverflow.com/questions/invalid-urls-throw-an-exception-python')
    valid.startActivity()
    valid1 = ValidateURL('http://stackoverflow.com/questions/6414417/invalid-urls-throw-an-exception-python')
    valid1.startActivity()

Hope the solution I derived is sensible.


text:
Q: Checking PCNTL extension installed in PHP One of background scripts in my project uses PCNTL to fork. Also, I have a requirement checker script that should be run by user before script installation. Since pcntl can be accessed only in CGI mode, both function_exists('pcntl_fork') and extension_loaded('pcntl') return FALSE in Web mode, so my checker shows always requirement error, as it launched via browser, even if it is enabled. Is there any method to check pcntl support is enabled from web mode?

A: Since nobody has answered, I thought I should just point out that you can create a standalone PHP script that checks for the existence of pcntl, then run that script with PHP CLI using, for example, exec or system.


text:
Q: Trying to settle on a database model for words and translations? So right now my model looks like this...
class Language()
    name= Char()

class Word
    id = pk()
    language = ForeignKey(language)
    name = Char()

class Translation()
    original = FoeignKey(word)
    L2 = ForiegnKey(language)
    definition = Text()
    translation = Char()

The problem I have with this is that say I have two languages (English/Spanish) and two words (el/la, the). With my current model I would have to have two translation objects for these two words.
class Language()
    name= Char()

class Word
    id = pk()
    language = ForeignKey(language)
    name = Char()

class Translation()
    language1 = FoeignKey(word)
    language2 = ForiegnKey(word)
    definition_language1 = Text()
    definition_language2 = Text()

Although I tried to do option 2 and I think it wouldn't let me directly have to ForeignKeys to the word class.
I think I have thought myself into a corner, and I can't decide if it is totally necessary to do option 2 or not. Is it even possible?

A: Isn't what you have more of the structure where you have a Word table, a Language table, and then your translation table is a through table connecting the Word table with itself. Then you can put all that additional information on the through table, and query it as a connection between two Word objects
If you don't know what a through table is, the documentation for how to use it can be found here: https://docs.djangoproject.com/en/1.8/topics/db/models/#extra-fields-on-many-to-many-relationships

A: Why not use your second example with a related_name?
class Translation()
        language1 = ForeignKey(word, related_name = 'masculine')
        language2 = ForeignKey(word, related_name = 'feminine')


text:
Q: Using Set Interval Function to Animate <html>

canvas {
    background-color: lightgreen
}

<script>
var ctx = canvas.getContext("2d");

    var n = 5;
    const PI = 3.14;

    var randomWalk = function (n) {

        var list = [0, 1];
        var l = list.length;
        start = Math.round(n / 2);
        count = 0;

        while (start > 0 && start < n + 1) {

            rand = list[Math.floor(Math.random() * l)];
            if (rand == 1) { start = start + 1 }
            else { start = start - 1 };
            count = count + 1;

        };

        console.log(count);

    };

    var drawSquares = function (n) {
        for (i = 50; i <= n * 50; i = i + 50) {

            ctx.beginPath();
            ctx.rect(i, 50, 50, 50);
            ctx.stroke();

        };

    };

    var drawDot = function (n) {
        x = ((50 * n) / 2) + 50;

        ctx.beginPath();
        ctx.arc(x, 75, 5, 0, 2 * PI);
        ctx.stroke();
        ctx.fill();

    };

    var resetCanvas = function () {

        ctx.clearRect(0, 0, canvas.width, canvas.height);
    };

    var moveDot = function (n) {
        drawSquares(n);
        drawDot(n);

        var list = [0, 1];
        var l = list.length;
        start = ((50 * n) / 2) + 50;
        count = 0;

        while (start > 50 && start < ((n * 50) + 50)) {

            rand = list[Math.floor(Math.random() * l)];
            if (rand == 1) { start = start + 50 }
            else { start = start - 50 };
            count = count + 1;
            //console.log(start);

            resetCanvas();
            drawSquares(n);
            ctx.beginPath();
            ctx.arc(start, 75, 5, 0, 2 * PI);
            ctx.stroke();
            ctx.fill();

        };

        console.log(count);

    };

    //moveDot(n);

   setInterval(moveDot(n), 1500);

    </script>

The function below is the function that isn't working properly within the set interval function. This function takes the number of boxes as the input and based on a random choice of 0 or 1, it moves the dot to the left or to the right however it's not being shown.
I created the function titled moveDot to move the dot, however when placed in the set interval function the dot does not move. Any ideas as to why the function is not working properly would be greatly appreciated! Thanks in advance for your help!


text:
Q: How to set multiple columns and selected rows in data table to value from other data table The Question is somewhat related with this question (How to set multiple columns in a data table to values from different columns in the same data table?).
set.seed(1)
df <- data.frame(matrix(sample(1:100,30),ncol=6))
#  X1 X2 X3 X4 X5 X6
#1 27 86 19 43 75 29
#2 37 97 16 88 17  1
#3 57 62 61 83 51 28
#4 89 58 34 32 10 81
#5 20  6 67 63 21 25
library(data.table)
dt <- data.table(df)

df1 <- data.frame(matrix(sample(1:100,30),ncol=6))
df1
#   X1 X2 X3 X4 X5 X6
#1  49 64 74 68 39  8
#2  60 75 58  2 88 24
#3 100 11 69 40 35 91
#4  19 67 98 61 97 48
#5  80 38 46 57  6 29
dt1 <- data.table(df1)

This time, I want to change the certain row and column.
dt[1:3, c("X1","X2"), with = F] = dt1[1:3, c("X3","X5"), with = F]

But this one give an error:
Error in `[<-.data.table`(`*tmp*`, 1:3, c("X1", "X2"), with = F, value = list( :
  unused argument (with = F)

I will do with the data had many columns. I hope that the name of column should be character at first.

A: By using the = operator as you do, you are trying assign the values to the desired spots in the data.table. Instead you should update your data.table dt by reference with the := operator inside dt[...]. A slight adaptation of @thelatemail's comment (the second with = FALSE is not needed):
dt[1:3, c("X1","X2") := dt1[1:3, c("X3","X5"), with = FALSE]]


text:
Q: How to load HTML code into a table using Javascript? I'm building a simple website which consists of a header (the title and a menu) and a table, in which the content is placed (because then I can make the layout easier). The problem is that each time I change the category (click a link in the menu), the whole site becomes white for a short period of time, while it's loading. I'd like it so this doesn't happen, so I only need to load the content of the table, not the whole page. I guess this could easily be done using frames, but I was told that they will stop being supported soon, and that it's a bad practice using them. Is there a way to do this?
For the time being, the site is here, so you can see the effect I'm talking about: http://bljak.org:1235/index.html.
Also, it would be the best if site was just HTML and Javascript, because I'm not really familiar with PHP (and I'm coding on a netbook with 512Mb of RAM, so I doubt I could start a server there).

A: You can use innerHTML to rewrite the text between the tag and its close tag:

<input type="button" onclick="javascript:changeText()" value="Change Text"/>

A: I will give way based on jQuery - this is the most simple and short way.
First, download the latest jQuery library - can be found here.
Suppose you name your local file "jquery.min.js" have such line in your existing HTML code to "include" the jQuery library:

Now all you need is this code in your page and you're done:

Replace the Container with the ID of the actual element in your page that should contain the "body" then clicking any link will cause the linked page to be loaded into the container without full page reload.
The code is pretty much straightforward, feel free to ask if you want to understand any part of it though.
jQuery is less than 100K so with modern internet speed it really shouldn't be any problem - pure JavaScript is of course possible, but will cause lots of headache in keeping it cross browser.


text:
Q: using pre_get_posts to exclude I am trying to use pre_get_posts to exclude categories from posting to the homepage. If I do it like so it works just fine
 $query->set( 'cat', '-13,-7,-19,-12,-24,-21,-14');

that is hard coded in. I am building a custom admin that lists the categories in the admin menu. So now I want to use the id's that get selected in the admin menu. So I have assigned my id's to a variable and when I var_dump the variable, this is what I get
 string(2) "13"
 string(1) "7"
 string(2) "19"
 string(2) "12"
 string(2) "24"
 string(2) "21"
 string(2) "14"

So all those are assigned to the variable $category and so I thought I could do this
 $category = get_option( 'excludecats' );
 foreach( $category as $exclude ){
    $query->set( 'cat', '-'.$exclude );
 }

when I view the source, I expect there to be 1987 lines of code but what I end up with is 3117 lines of code trying to use the foreach to exclude them. What am I doing wrong?

A: When you use the pre_get_posts action you have access to alter any of the query_vars using the set method.
According to the codex documentation linked above you can use your array and set it as the value of the 'category__not_in' query_var.
$query->set( 'category__not_in', $category );

A: try to implode $category with "," as a glue. Mentioned code in each foreach run rewtites the cat variable of $query.
$query->set('cat', implode(',', $category));

A: This is the final code I went with
 function wpa83038_posts_and_pages_on_home( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
    $query->set( 'post_type', array( 'post', 'page') );
    //GETTING THE OPTION FROM TEH ADMIN TO EXCLUDE THE BLOG POSTS FROM THE HOMEPAGE.
            //using option tree for the WordPress admin area
    if( function_exists( 'ot_get_option' )){
        $category = ot_get_option( 'excludecats' );

        $exclude = implode(",-",$category);
        $exclude = '-'.$exclude;
        $query->set( 'cat', $exclude);
    }
  }
}


text:
Q: Use CloudInit cloud-config file to add authorized_keys for multiple users Is it possible to add ssh authorized keys for multiple users using a #cloud-config file with CloudInit?
I'm trying to initialize a new EC2 instance created from an Amazon Linux AMI using CloudInit. I'm able to add custom ssh authorized public keys to the ec2-user account using something like this:
#cloud-config

ssh_authorized_keys:
  - ssh-rsa AAAAB3NzaC1yc2EAAA...

What I'd really like to do is create several new users an add a separate public key for each of them. Is it possible to do this using a standard cloud-config directive, or do I just need to write a custom shell script to do that?

A: Looks like you can do this now
#cloud-config
users:
  - default
  - name: jdoe
    gecos: John Doe
    ssh-authorized-keys:
      - ssh-rsa ...
  - name: jroe
    gecos: Jane Roe
    ssh-authorized-keys:
      - ssh-rsa ...

from https://cloudonaut.io/avoid-sharing-key-pairs-for-ec2/

A: CloudInit doesn't support specifying multiple users to install SSH keys for. You'll need to write your own script to accomplish this.


text:
Q: Algorithm to calculate new position of items in a list Assume there is an unsorted list of items, and we know the initial position (index) of every item in the list. Now we start to perform insertion and deletion operations. Once all operations are done, I want to be able to calculate the new index of the item that was in the n-th position.
For example. Assume we have the following list:
['a', 'x', 'b', 'w', 'e'].

We perform the following operations (indices are zero based):

*

*Insert 'u' at 3

*Delete at 5

*Insert 'j' at 0

*Delete at 1

The new list is:
['j', 'x', 'b', 'u', 'w']

and I want to know the new index of the item that was at index 3 ('w' - the answer is 4).
Of course, I can always loop through the list and find the index of 'w' - which would require O(N).
I am looking for an algorithm that will provide the answer to "what is the new position of the item that was at position n". The algorithm may add O(1) calculations to the Insert and Remove operations. When asked, the algorithm should return the new position of an item, in less than O(N). (O(log n) perhaps, or even O(1) if its possible).
Edit
Just to be more specific. The algorithm I am looking for starts after the set of modifications is done. We can have a one time setup that creates a data structure, which can later be queried for the new position of an item given it's original position. Assume the size of the list is N, the number of operations was M. Also assume K = Max(N, M).

*

*Setup time may take O(k*log K), but preferably take O(K) is possible.

*Single Query time should take less than O(K) (for example O(log K) or O(1))

Also, the algorithm can assume that all queries look for items that are still in the list.

A: Modify your list structure to store the initial position of each element, for example storing a tuple of index, value instead of value for each element:
 ['a', 'x', 'b', 'w', 'e']

becomes
 [{'a', 0}, {'x', 1}, {'b', 2}, {'w', 3}, {'e', 4}]

Then run your insertions and removals, giving each new insertion an index of -1 to indicate that it wasn't in the original list:
 [{'j', -1}, {'x', 1}, {'b', 2}, {'u', -1}, {'w', 3}]

Now create an array 'newIndexArray' equal to the original list size, initialize all values to -1 and then iterate over the new list, incrementing a counter starting from zero to keep track of the new position. For each element, set:
 newIndexArray[elementTuple.Item2] = counter

newIndexArray will now containg the following values:
 newIndexArray[0] = -1
 newIndexArray[1] = 1
 newIndexArray[2] = 2
 newIndexArray[3] = 4
 newIndexArray[4] = -1

-1 means the element that was originally at that position has been removed.
Algorithm is O(N) for the entire list, or O(1) per element. There is O(1) additional cost per insertion and (initializing the index to -1)

A: Here's an algorithm to do this in O(log n) per operation and O(1) per query. We store the elements in an implicit treap (or some other similar cartesian tree structure), which allow insertions, deletions, and access by index all in O(log n). After we perform all the operations, we iterate over the implicit treap and construct a table of the positions of the elements. Then we can answer queries in O(1) as described in samgak's answer.


text:
Q: Displaying Album Info via JSON Facebook Graph API I've been looking through the different threads on the Facebook Graph API and displaying the results via JSON. The examples are great but I only want to output the info for a particular album not loop through various results.
Here is a link to the Coca-Cola Wall Photos album. https://graph.facebook.com/99394368305
What I would like to do is display the Name of the Album and the Link.
Any help is much appreciated!

A: You can choose only the fields you want by specifying the fields query parameter:
https://graph.facebook.com/99394368305/?fields=name,link
From http://developers.facebook.com/docs/reference/api/#reading:

Selection
By default, most object properties are returned when you make a query. You can choose the fields (or connections) you want returned with the "fields" query parameter. For example, this URL will only return the id, name, and picture of Ben: https://graph.facebook.com/bgolub?fields=id,name,picture
You can also request multiple objects in a single query using the "ids" query parameter. For example, the URL https://graph.facebook.com?ids=arjun,vernal returns both profiles in the same response.


text:
Q: Modify HTML of loaded pages using chrome extensions How can I add some HTML code to the loaded page if page's title contains specific text?
Chrome extensions are new grounds to me and your help would be greatly appreciated.

A: References:

*

*Content Scripts

*Manifest File
You can take the following code as a reference for adding some HTML Code.
manifest.json
This file registers content script to extension.
{
"name":"Inject DOM",
"description":"http://stackoverflow.com/questions/14068879",
"version":"1",
"manifest_version":2,
"content_scripts": [
    {
      "matches": ["http://www.google.co.in/*","https://www.google.co.in/*"],
      "js": ["myscript.js"]
    }
  ]
}

myscript.js
A trivial script for adding a button to Google page
// Checking page title
if (document.title.indexOf("Google") != -1) {
    //Creating Elements
    var btn = document.createElement("BUTTON")
    var t = document.createTextNode("CLICK ME");
    btn.appendChild(t);
    //Appending to DOM
    document.body.appendChild(btn);
}

Output
You see a button added to a desired page

A: @Sudarshan 's answer explains page specificity, Great, but what about the comments added? here's how to do what he missed in an easier more practical manner
to modify existing content or to create content on an page the easiest method would be:

Modify

single item modification:
document.getElementById("Id").innerHtml = this.innerHtml + "<some code here>";

or to modify attributes:
document.getElementById("Id").class = "classname";

//or ->

document.getElementById("Id").style.color = "#a1b2c3";

for adding multiple lines of code do the following:
document.getElementById("Id").innerHtml = this.innerHtml + `
 <some code here>
 and we're on multiple lines!` + "variables can be inserted too!" + `
 <this code will be inserted directly **AS IS** into the DOM
`
;

*

*but now  what about easy element insertation?

Create

large code injection (example from coding project done a while back) see insertAdjacentHtml API :
var bod = document.getElementsByTagName('body')[0];

bod.insertAdjacentHTML('afterbegin', `

            <embed id="IframeThingyA" src="` + "url" + `" type="text/html">
            </embed>

    `);

references:

*

*insert - Adjacent - Html

*content specific code


text: Q: Why does my website redirect in some browsers for some users? My organization recently launched a new website. In order to keep good search engine ranking we used a 301 redirect in IIS to point the old traffic to the new site. However, when doing this our internal site was also pointed to the new site,  and now on some devices it wants to redirect to the new site. I have removed the redirect from the internal site and restarted iis, and the app pool. In IE the site redirects but in chrome it does not for the devices that are not working. Is there another way to resolve this issue?


text:
Q: How can we store the value of a Modal in Pycord (2.x) in a method/function and then return it? class title_input_modal(Modal):
    def __init__(self):
        super().__init__("Audio Title Input")

        self.add_item(InputText(label = "Audio Title", style = discord.InputTextStyle.short))

    async def callback(self, interaction: discord.Interaction):

        val = self.children[0].value
        await interaction.response.send_message(val)

How can I make a method and store the value of the response? If I try accessing title_input_modal.children[0] from another cog's class method, this error pops up:-
Ignoring exception in view <View timeout=180.0 children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Play' emoji=<PartialEmoji animated=False name='▶' id=None> row=None>:
Traceback (most recent call last):
  File "C:\Users\Chinmay Krishna\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 371, in _scheduled_task
    await item.callback(interaction)
  File "d:\Programming\python\intellij\intellij_python\AxC-777-Music\no_upload.py", line 137, in play_button_callback
    print(title_input_modal.children[0].value)
AttributeError: type object 'title_input_modal' has no attribute 'children'
Ignoring exception in view <View timeout=180.0 children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Play' emoji=<PartialEmoji animated=False name='▶' id=None> row=None>:
Traceback (most recent call last):
  File "C:\Users\Chinmay Krishna\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 371, in _scheduled_task
    await item.callback(interaction)
  File "d:\Programming\python\intellij\intellij_python\AxC-777-Music\no_upload.py", line 137, in play_button_callback
    print(title_input_modal.children[0].value)
AttributeError: type object 'title_input_modal' has no attribute 'children'

A: You can store the value in your class as a property and access it once the modal has been dismissed.
To do so you will have to modify your class like this.
class title_input_modal(Modal):
    def __init__(self):
        super().__init__("Audio Title Input")

        #
        self.val = None

        self.add_item(InputText(label = "Audio Title", style = discord.InputTextStyle.short))

    async def callback(self, interaction: discord.Interaction):

        self.val = self.children[0].value
        await interaction.response.send_message(val)
        self.stop()

Then from where you call your modal, you will have to initialise it like this so that you can then access its properties
title_modal = title_input_modal()
await ...send_modal(title_modal)
await title_modal.wait()
print(title_modal.val)

Without the stop and wait methods, your bot won't wait for the modal interaction to be over, so you won't be able to access the value from the user.


text:
Q: Asp Net core web API. EF Core не отслеживает изменения Entity Использую net core 3.1 + Entity framework core. Есть модель User и UserType, которую сохраняю в БД. К ним использую отдельные DTO для создания и чтения.
В контроллер приходит Dto, маплю ее в модель юзер. Далее модель отправляю в бд, сохраняю. Потом в контроллере обратно маплю в Dto, и там Ид и юзер тип не обновленные, хотя все в базу сохранено. Отслеживание не отключал.
Проблему в контроллере решил созданием новым экземпляров модели, но это неверно.
Как решить вопрос?
Модельки:
public class User
{
    [Key]
     public int Id { get; set; }

    [Required]
    [StringLength(50, MinimumLength = 5)]
    public string Nickname { get; set; }

    [EmailAddress]
    public string Email { get; set; }

    [Phone]
    public string PhoneNumber { get; set; }

    [Required]
    [StringLength(50, MinimumLength = 5)]
    public string Password { get; set; }

    public int UserTypeId { get; set; }

    public virtual UserType UserType { get; set; }
}

public class UserType
{
    [Key]
    public int Id { get; set; }

    [Required]
    [StringLength(50, MinimumLength = 5)]
    public string Name { get; set; }
}

К ним DTO для создания
public class UserCreateDto
{
    [Required(AllowEmptyStrings = false, ErrorMessage = "Nickname not specified")]
    [StringLength(50, MinimumLength = 5)]
    public string Nickname { get; set; }

    [EmailAddress]
    public string Email { get; set; }

    [Phone]
    public string PhoneNumber { get; set; }

    [Required(AllowEmptyStrings = false, ErrorMessage = "Password not specified")]
    [StringLength(50, MinimumLength = 5)]
    public string Password { get; set; }

    [Required(AllowEmptyStrings = false)]
    [Compare("Password", ErrorMessage = "Passwords don't match")]
    public string PasswordConfirm { get; set; }
}

public class UserTypeCreateDto
{
    [Required(AllowEmptyStrings = false, ErrorMessage = "User's type not specified")]
    [StringLength(50, MinimumLength = 3)]
    public string Name { get; set; }
}

и для чтения
public class UserReadDto
{
    public int Id { get; set; }
    public string Nickname { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public UserTypeReadDto UserType { get; set; }
}

public class UserTypeReadDto
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Реализация метода в репозитории юзера. Уже тут пришлось возвращать обновленный юзер. Иначе в контроллере после вызова этого метода данные не обновлялись. Отслеживание для EF Core не отключал, метод AsNoTracking() не вызываю.
public async Task<User> AddAsync(User user)
{
    var context = dbContextFactory.Create(typeof(UserRepository));

    var userTypeId = await context.UserTypes
                                  .Where(x => x.Name == "Client")
                                  .Select(x => x.Id)
                                  .FirstOrDefaultAsync();
    if (userTypeId == 0)
    {
        UserType userType = new UserType
        {
            Name = "Client"
        };

        await context.UserTypes.AddAsync(userType);
        await context.SaveChangesAsync();

        userTypeId = userType.Id;
    }

    User newUser = new User
    {
        Nickname = user.Nickname,
        Email = user.Email,
        PhoneNumber = user.PhoneNumber,
        Password = user.Password,
        UserTypeId = userTypeId
    };

    await context.Users.AddAsync(newUser);
    await context.SaveChangesAsync();

    return newUser;
}

И собственно контроллер.
[HttpPost("")]
public async Task<IActionResult> CreateUserAsync(UserCreateDto userDto)
{
    if (userDto == null || !ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var user = mapper.Map<User>(userDto);

    //after saving to the database(context.SaveChangesAsync()), the user model is not updated.
    //I was unable to fix this.So I do the following:

    var userResult = await userRepository.AddAsync(user); // get user with Id from database.

    userResult = await userRepository.GetByIdAsync(userResult.Id); // get user with userType from
    database.

    var userReadDto = mapper.Map<UserReadDto>(userResult);

    return CreatedAtAction(nameof(GetUserByIdAsync), new { id = userReadDto.Id }, userReadDto);
}

A: Подсказали то, что лежало на поверхности. Я в репозитории создавал новый экземпляр юзера вместо обновления существующего. В этом была вся проблема.


text:
Q: Can you set x == y equal to a Boolean in any any programming languages where x and y are of the same primitive type? This may be an odd question, and generally I would just go test it, but I'm not near a computer with any IDEs, but can you set a Boolean equal to the expression x==y?  The only reason I ask this is because in an if statement you can say... if(x==y) which is asking if the two are equal then do.... And if that is true then the statement x == y is evaluating to true can you set a variable to it

A: Yes you can, in Java you can do:
boolean z = (x==y);


text:
Q: The right way to distribute my php libraries on Bitbucket I'm a litte confused about the right way to use Composer and Bitbucket regarding the distribution of my libraries, maybe because I'm a newbie both in Composer and Bitbucket.
My problem is: I have two repositories on Bitbucket, the first one is a simple utility library (Utility) and the second one is the main project (MainProject). Both have one single branch, the master one.
I want to use Utility in MainProject, so I wrote two composer.json.
Mainproject composer.json:
{
    "require": {
       "vendor/utility": "*"
     },
    "repositories": [
        {
            "type": "vcs",
            "url":  "https://MyUsername@bitbucket.org/MyUsername/utility.git"
        }
    ]
}

Utility composer.json:
{
    "name": "vendor/utility",
    "autoload": {
        "psr-4": {
            "Vendor\\": "src/"
        }
    }
}

This configuration works perfectly, I mean, if I launch 'composer install' on MainProject, Utility is correctly cloned. But in the vendor directory in MainProject I get all the Utility files, including test directory and useless files like phpunit.xml.
I've tried to use the solution offered here:  https://www.reddit.com/r/PHP/comments/2jzp6k/i_dont_need_your_tests_in_my_production/, I created the archive via Sourcetree, but after? How I should use this archive? I suspect I miss some basic knowledge.
If I want to distribute Utility via composer as a package also for other applications, but without its tests and other files, which is the right way?
Should I use .gitattribute or is there a simple way to create a dist version? I don't understand how to do with Bitbucket, maybe because I'm a newbie.
A little help?

A: I understand that the situation looks a bit unsatisfying, but that Reddit thread "I don't need your tests in my production" is only one side of the story. The other side is "I need your test in my pre-deployment checks to verify your code works as well as mine".
So there's two conflicting wishes: Either have no tests, or have them.
Composer doesn't solve this for you. If you don't like the files that you get by the process, you can write a script that does delete them before putting the project live.
There currently is no automatic help planned via Composer because it is easier for those people that want less files to delete them after composer install than the other way round.


text:
Q: How to get file timestamps at maximum resolution? man 2 stat shows that the values st_atime, st_mtime and st_ctime returned in the struct stat are of type time_t, that has seconds resolution. How to get those same values in higher resolution, maybe as struct timespec or struct timeval, or just the missing subsecond part?
I need this for a C++ on Linux, but I am tagging with C too because I think the answer will probably be the same for both languages.

A: According to the NOTES section of man 2 stat:
   Since kernel 2.5.48, the stat structure supports nanosecond resolution  for  the  three  file  timestamp  fields.   Glibc
   exposes the nanosecond component of each field using names of the form st_atim.tv_nsec if the _BSD_SOURCE or _SVID_SOURCE
   feature test macro is defined.  These fields are specified in POSIX.1-2008, and, starting with version 2.12,  glibc  also
   exposes  these  field  names if _POSIX_C_SOURCE is defined with the value 200809L or greater, or _XOPEN_SOURCE is defined
   with the value 700 or greater.  If none of the aforementioned macros are defined, then the nanosecond values are  exposed
   with names of the form st_atimensec.  On file systems that do not support subsecond timestamps, the nanosecond fields are
   returned with the value 0.


text:
Q: android map application runtime error while testing on q mobile I am trying Load a Simple Map using Android but their is problem when i run this application on mobile device.here is My Log Cat
07-22 14:47:12.207: D/AndroidRuntime(3241): Shutting down VM
07-22 14:47:12.207: W/dalvikvm(3241): threadid=1: thread exiting with uncaught exception (group=0x40d17258)
07-22 14:47:12.215: E/AndroidRuntime(3241): FATAL EXCEPTION: main
07-22 14:47:12.215: E/AndroidRuntime(3241): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.adeel.map/com.adeel.map.MainActivity}: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
07-22 14:47:12.215: E/AndroidRuntime(3241):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2001)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2028)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at android.app.ActivityThread.access$600(ActivityThread.java:127)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1179)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at android.os.Looper.loop(Looper.java:137)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at android.app.ActivityThread.main(ActivityThread.java:4508)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at java.lang.reflect.Method.invokeNative(Native Method)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at java.lang.reflect.Method.invoke(Method.java:511)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at dalvik.system.NativeStart.main(Native Method)
07-22 14:47:12.215: E/AndroidRuntime(3241): Caused by: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
07-22 14:47:12.215: E/AndroidRuntime(3241):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:699)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:741)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at android.view.LayoutInflater.inflate(LayoutInflater.java:491)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:252)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at android.app.Activity.setContentView(Activity.java:1837)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at com.adeel.map.MainActivity.onCreate(MainActivity.java:23)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at android.app.Activity.performCreate(Activity.java:4479)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1050)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1965)
07-22 14:47:12.215: E/AndroidRuntime(3241):     ... 11 more
07-22 14:47:12.215: E/AndroidRuntime(3241): Caused by: java.lang.ClassCastException: com.google.android.gms.maps.MapFragment cannot be cast to android.support.v4.app.Fragment
07-22 14:47:12.215: E/AndroidRuntime(3241):     at android.support.v4.app.Fragment.instantiate(Fragment.java:394)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at android.support.v4.app.Fragment.instantiate(Fragment.java:369)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:272)
07-22 14:47:12.215: E/AndroidRuntime(3241):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:671)
07-22 14:47:12.215: E/AndroidRuntime(3241):     ... 21 more
07-22 14:47:14.132: I/Process(3241): Sending signal. PID: 3241 SIG: 9

And Here is My Source Code
package com.adeel.map;

import android.os.Bundle;
import android.view.Menu;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.SupportMapFragment;

import com.google.android.gms.maps.GoogleMap;
import java.io.InputStream;
import org.json.JSONArray;
import com.adeel.map.R;

public class MainActivity extends FragmentActivity  {
    JSONArray jArray;
    String result = null;
    InputStream is = null;
    StringBuilder sb=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //GoogleMap mMap;
        //mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
        //String readTwitterFeed = readpoints();
        SupportMapFragment fm = (SupportMapFragment)  getSupportFragmentManager().findFragmentById(R.id.map);
        GoogleMap mMap = fm.getMap();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

Here is My XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment" />

</RelativeLayout>

here is Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.adeel.map"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" android:maxSdkVersion="16" android:targetSdkVersion="16"/>

    <permission
        android:name="com.adeel.map.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="com.adeel.map.maps.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:debuggable="true" >
        <activity
            android:name="com.adeel.map.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyCHTWS_mHN-2a0oTC2NiC4_a0......." />
    </application>

</manifest>

Any One Please Help Me What Is Problem here.

A: The problem is that you use in your XML:
class="com.google.android.gms.maps.MapFragment"

instead:
class="com.google.android.gms.maps.SupportMapFragment"

This is the error:
Caused by: java.lang.ClassCastException: com.google.android.gms.maps.MapFragment cannot be cast to android.support.v4.app.Fragment


text:
Q: Args.slice is not a function in a Discord bot I'm new in this, I need a little help. I'm doing Discord bot, I know is silly but I like this. My problem is to do a command with a function, when I execute this command in the console I get this:
TypeError: args.join is not a function or TypeError: args.slice(...).join is not a function
(Are two possibilities)
I don't know what are the problem. Anyone can help me
Thanks.
module.exports.run = async (bot, message, args) => {
if(!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send('You can\'t use that!')
if(!message.guild.me.hasPermission("BAN_MEMBERS")) return message.channel.send('I don\'t have the right permissions.')

const member = message.mentions.members.first() || message.guild.members.cache.get(args[0]);

if(!args[0]) return message.channel.send('Please specify a user');

if(!member) return message.channel.send('Can\'t seem to find this user. Sorry \'bout that :/');
if(!member.bannable) return message.channel.send('This user can\'t be banned. It is either because they are a mod/admin, or their highest role is higher than mine');

if(member.id === message.author.id) return message.channel.send('Bruh, you can\'t ban yourself!');

let reason = args.slice(1).join(' ');

if(!reason) reason = 'Unspecified';

member.ban(`${reason}`).catch(err => {
  message.channel.send('Something went wrong')
    console.log(err)
})


text:
Q: for loop to while conversion Here I have a C++ code with for loops.
for(int A=1;A<=3;A++)
    {
     cout<<A*2;
     for(int B=1;B<=A;B++)
     cout<<"*";
     cout<<endl;
    }

and it gives me this output.
2*
4**
6***
I need to do the same thing using while loops. so I convert the above code to this one.
while(A<=3)
    {
    cout<<A*2;
        while(A>=B)
        {cout<<"*";
            B++;}

    cout<<endl;
    A++;
    }

but this code give me the output
2*
4*
6*
Can someone tell me what I'm doing wrong there in my while loop.

A: int A = 1;
int B;

while (A <= 3)
{
    cout << A * 2;
    B = 1;
    while (B <= A)
    {
        cout.put('*');
        ++B;
    }

    cout.put('\n');
    ++A;
}

ioccc-style:
#include <iostream>

int main()
{
    int A{1};while(!(A>>2)&&std::cout.put((A<<1)|0x30)){
        int B{A++};while(std::cout.put((!B)["*\n"]),B--);}
}

A: You are not giving A or B initial values.
void func()
{
    int A = 1;
    while (A<=3)
    {
        std::cout << A*2;
        int B = 1;
        while(A>=B)
        {
            std::cout << "*";
            B++;
        }

        std::cout<<endl;
        A++;
    }
}

A: Your second snippet doesn't show where you declared A or B. I'm assuming it's outside of the outer while loop which won't work. You have to declare B inside the first while or reinitialize it every loop.
int A = 1;
while(A <= 3)
{
  cout << A * 2;
  int B = 1;
  while(A >= B)
  {
    cout << "*";
    ++B;
  }
  ++A;
  cout << endl;
}

Result.

A: You should use B as local variable, alson change the while comparation to less and equal.
int A = 1;

while(A<=3) {
    cout<<A*2;
    int B = 1; // B as local variable
    while(B<=A) {
        cout<<"*";
        B++;
    }
    cout<<endl;
    A++;
}

Output:
2*
4**
6***

A: int A = 1;
while(A <= 3)
{
    cout<<A*2;
    int B = 1;
    while(A >= B){
        cout<<"*";
        B++;
    }
    cout<<"/n";
    A++;
}

output :
2*
4**
6***


text:
Q: Confirm Password not validated in angular material This is my code.If i enter wrong confirm password it doesn't show password does not match.
how can i validate this in angular.
          <mat-form-field>
              <input matInput id="password" name="password" type="password" [(ngModel)]="password" required minlength="6"
              #passwordValidation="ngModel">
            <mat-error *ngIf="passwordValidation.hasError('required')">Required</mat-error>
            <mat-error *ngIf="passwordValidation.hasError('minlength')">Password should be of minimum 6 characters</mat-error>
          </mat-form-field>
          <mat-form-field>
              <input matInput name="confirmPassword" type="password"[(ngModel)]="confirmPassword" required validateEqual="password"
              #confirmPasswordValidation="ngModel" placeholder="Confrim password*">
            <mat-error *ngIf="confirmPasswordValidation.hasError('required')">Required</mat-error>
            <mat-error *ngIf="confirmPasswordValidation.hasError('validateEqual')">Password does not match</mat-error>
          </mat-form-field>


text:
Q: Date Time range if crash the some date time range I have a problem writing the condition to set the appointment date in C#
For example:
If I want to make the Date & Time of the Appointment start on 07 Nov 2022 11:30 AM, and end appointment date time will be 07 Nov 2022 02:30 PM.
But in the HR organizer has set the lunch hour as 1pm - 2pm. The start form 07 Nov 2022 and end date is 11 Nov 2022.
So the result should be cannot make an appointment.
Sample UI for an appointment:

Sample UI for Schedule Organizer:

I try to write the condition query to detect if the appointment DateTime is crashed in the schedule organizer.
Below is my sample coding, but cannot work:
if ((DateTime.Parse(currentStartDate, CultureInfo.InvariantCulture) <=  DateTime.Parse(currentDate, CultureInfo.InvariantCulture) &&
DateTime.Parse(currentDate, CultureInfo.InvariantCulture) <= DateTime.Parse(currentEndDate, CultureInfo.InvariantCulture)) &&(DateTime.Parse(currentAptStartTime, CultureInfo.InvariantCulture) >= DateTime.Parse(currentStartTime, CultureInfo.InvariantCulture) &&
DateTime.Parse(currentAptStartTime, CultureInfo.InvariantCulture) <= DateTime.Parse(currentEndTime, CultureInfo.InvariantCulture)) &&
(DateTime.Parse(currentAptStartDate, CultureInfo.InvariantCulture) >= DateTime.Parse(currentStartDate, CultureInfo.InvariantCulture) &&
DateTime.Parse(currentAptStartDate, CultureInfo.InvariantCulture) <= DateTime.Parse(currentEndDate, CultureInfo.InvariantCulture)))
{
return false;
}else
{
return true;
}

Variable sample value:
currentAptStartTime = "07 Nov 2022 11:30 AM"
currentAptEndTime = "07 Nov 2022 02:30 PM"
currentStartTime = "1pm"
currentEndTime = "2pm"
currentStartDate = "07 Nov 2022"
currentEndDate = "11 Nov 2022"

May I know how to properly or good practice to write the condition to meet the above requirements? Hope someone can guide me on how to solve this. Thank you.

A: You can extract a method which will do all the parsings:
    private static bool TryMyParse(string text, out DateTime result) {
        return DateTime.TryParseExact(
            text,
            new[] { //TODO: put all the accepted formats here
                "h tt",    // Today + provided time
                "h:m tt",  // Today + provided time
                "htt",     // Today + provided time
                "h:mtt",   // Today + provided time
                "d MMM yyyy",
                "d MMM yyyy h:m tt",
            },
            CultureInfo.InvariantCulture,
            DateTimeStyles.AssumeLocal,
            out result);
    }

Then you can use it as: parse the dates and allpy your logic
if (TryMyParse(currentStartDate, out var dtCurrentStartDate) &&
    TryMyParse(currentEndDate, out var dtCurrentEndDate) &&
    TryMyParse(currentDate, out var dtCurrentDate) &&
    TryMyParse(currentAptStartTime, out var dtCurrentAptStartTime) &&
    TryMyParse(currentAptStartDate, out var dtCurrentAptStartDate)) {
     // Dates are valid, your logic comes here

     return !(dtCurrentStartDate <= dtCurrentDate &&
              dtCurrentDate <= dtCurrentEndDate &&
              dtCurrentAptStartTime >= dtCurrentStartTime &&
              dtCurrentAptStartTime <= dtCurrentEndTime &&
              dtCurrentAptStartDate >= dtCurrentStartDate &&
              dtCurrentAptStartDate <= dtCurrentEndDate);
}
else {
    // at least one date is of wrong format
}


text:
Q: How does the map() function in Processing work? I'm taking a class which uses Processing.
I having a problem understanding the map() function.
According to it's documentation(http://www.processing.org/reference/map_.html):

Re-maps a number from one range to another.
In the first example above, the number 25 is converted from a value in the range of 0 to 100 into a value that ranges from the left edge of the window (0) to the right edge(width).
As shown in the second example, numbers outside of the range are not clamped to the minimum and maximum parameters values, because out-of-range values are often intentional and useful.

Is is similar to a random function but the range is set by the user? Also, i cant understand the explanation for the first example: it says the number is converted to a value of 0 to 100 into a value that ranges from edge to edge of the screen. im thinking why not just convert directly, the number 25 to the range of value pertaining to the screen?

A: The map() function is a useful shortcut and you won't regret the time spent at understanding it.
This is its syntax:
variable2 = map(variable1, min1, max1, min2, max2);
The function establishes a proportion between two ranges of values:
min1 : min2 = max1 : max2
you can read it as: min1 is to min2 as max1 is to max2.
variable1 stores a value between the first range min1~max1.
variable2 gets a value between the second range min2~max2.
This is the equation the function solves for the programmer:
variable2 = min2+(max2-min2)*((variable1-min1)/(max1-min1))
This is the Java code behind the Processing map() function:
static public final float map(float value,
                              float istart,
                              float istop,
                              float ostart,
                              float ostop) {
    return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
}

A: think of it this way: divide a range of 0 to 10 into 100 equal parts. (you will get 0.1 per part) now divide the range 0 to 100 into 100 equal parts (you will get 1 per part) so 0.1 in the range of 0 to 10 is equal to 1 in the range 0 to 100. if you want to find where 5 in the range of 0 to 10 belongs in the range of 0 to 100, divide 5 by the size of a 0 to 10 part and multiply that number by the size of a 0 to 100 part and you will have your answer! (50)
P.S. I know this isn't how it actually works, but I just thought I would give an example to clarify things.

A: If you think it a bit more carefully,
Its nothing more than just calculating the percentage,
in percentage you have final range is 0-100 and initial range as 0 - max(example like you have maximum marks in all subjects is 500, then initial range is 0 - 500),
Now for the solution what you can do:
for step by step to understand
n - your number
(initialMin - initialMax) your initial range
(finalMin - finalMax) your final range
then,
n
________________________    X   (finalMax - finalMin) = say N
(initialMax - initialMin)
now N is exactly like percentage,, instead 0 to 100 as range, you have 0 to (finalMax-finalMin) as range
so for converting it into finalMin to finalMax range that map() function do in processing,
just do N = N + finalMin
Now you get the answer that is N
Hope you guys understand the solution>>>


text:
Q: Adelic integral factorization In order to calculate Tamagawa numbers, I need to justify that for a nice (say Schwartz-Bruhat) function, the following identity holds :
$$\int_{\mathbf{A}^2} f(x)dx = \int_{SL_2(\mathbf{A})/SL_2(K)} \left( \sum_{a \in K^2 - 0} f(ua) \right) du$$
where $\mathbf{A}$ are the adeles on $K$, and $du$ is a Tamagawa measure on $SL_2(\mathbf{A})/SL_2(K)$. It seems to be easy if we know the Tamagawa numbers, but obviously it would be vicious...
The natural decomposition I want to star from is that of the transitive action of $SL_2(\mathbf{A})$ on $\mathbf{A}^2 - 0$, hence $\mathbf{A}^2 - 0 \cong SL_2(\mathbf{A}) / \mathbf{A}$, $N(\mathbf{A}) \cong \mathbf{A}$ being the stabilizer of $(1,0)$. But then, trying to decompose I cannot go further, for instance (dropping the integrands) and neglecting 0 (should I ?) :
$$\int_{A^2} = \int_{A^2/K^2} \sum_{K^2}$$
and then
$$\int_{A^2/K^2} = \int_{(SL_2(A)/A)/(SL_2(K)/K)}$$
is there so an isomorphism theorem I don't see how to use efficiently here ?
Thanks in advance for any help or idea, I'll dig further any clue. And sorry if it is indeed a trivial affair.


text:
Q: Adding an image in an html code I am new to html. I have been trying to insert an image

http://placehold.it/1000x500

in the following html code
<!doctype html>

    <meta charset="utf-8">
    <title>Framework Test page</title>
    <link rel="stylesheet" href="css/main.css">
    <link href='http://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>

2 Columns

ss

3 Columns

9 Columns

4 Columns

4 Columns

4 Columns

with the css file
*{
    border: 1px solid red !important;
}
*{
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    -ms-box-sizing: border-box;
    box-sizing: border-box;
}
.grid{
    margin: 0 auto;
     max-width: 1200px;
    width: 100%;
}
.row{
    width:100%;

    display: flex;
    flex-wrap: wrap;
}
*{
    font-family: 'Lato', sans-serif;
}
.text{
    margin:20px;
}
.col-1{
    width:8.33%;
}
.col-2{
    width:16.66%;
}
.col-3{
    width:25%;
}
.col-4{
    width:33.33%;
}
.col-5{
    width:41.66%;
}
.col-6{
    width:50%;
}
.col-7{
    width:58.33%;
}
.col-8{
    width:66.66%;
}
.col-9{
    width:75%;
}
.col-10{
    width:83.33%;
}
.col-11{
    width:91.66%;
}
.col-12{
    width:100%;
}

But I am not getting the image when I am opening the file in my browser. But the same image is getting displayed for another html code. Please tell the problem and the solution.

A: You have an error with

You have forgottton to add the src= part.
Instead, use:

A: You are missing the src.
The correct syntax for an image is:

A: Change this line

To

A: Use This

A:

A: you can use this code:-

A: Replace the image code with this

A: You have an error in your html..
Replace this line:

With this line

Check out the demo here:
http://jsfiddle.net/4h5e0ha5/

A: The Syntax in wrong you should add src(source) attribute to link any image from drive or from web site
Just add

and dont forget to close the tag :P


text:
Q: VueJS: dynamic component loses it`s props after reloading I have a django rest_framework as a server and vuejs for a client side. There is an index page like '/' where i`m using v-for to iterate an array of objects to show some item's cards. Each card has a button to the '/info'(which is dynamically changed with /:slug in a router) like so:
...
<RouterLink :to="{name: 'contentItemInfo', params: {item: item, slug: item.slug} }">
   <button class="card-button btn fade-in">
      ...
   </button>
</RouterLink>
...

Then, when we press the button, we are going to '/:slug' and passing the item param to props, using it like so:
...
<video class="video" type="video/mp4" autoplay loop :src="item.trailer"/>

{{ item.title }}

{{ item.subtitle }}

{{ item.description }}

...

export default {
  name: "ContentItemInfo",
  components: {Footer, Navbar},
  props: [
    'item'
  ],
}

Works for now, but when i reload the page, all the content disappeare and got undefined of all item`s values
How should i make it work after reloading?

A: Passing complex objects by route param only works in-memory. Once you reload the page, the only data you have is strings from the URL. You'll have to load the item data from your backend for fresh page loads.
Try something like this, making the item prop optional and loading the data if it's not set
export default {
  name: "ContentItemInfo",
  components: {Footer, Navbar},
  props: {
    item: {
      type: Object,
      default: null
    },
    slug: String // set from the route param
  }
  data: vm => ({
    video: vm.item // initialise a local copy so you can update it if required
  }),
  async created () {
    if (this.video === null) {
      // just guessing with this bit
      const { data } = await axios.get(`/api/video-for-slug/${encodeURIComponent(this.slug)}`)
      this.video = data
    }
  }
}

and your template

  <video
    class="video"
    type="video/mp4"
    autoplay
    loop
    :src="video.trailer"
  />

{{ video.title }}

{{ video.subtitle }}

{{ video.description }}

Loading...

In the above, I assumed that your routes are passing params as props. If not, see https://router.vuejs.org/guide/essentials/passing-props.html


text:
Q: Converting a uint64_t rdtsc value to a uint32_t I have a RNG function xorshift128plus that takes a Xorshift128PlusKey:
/**
        * \brief Keys for scalar xorshift128. Must be non-zero.
        * These are modified by xorshift128plus.
        */
        struct Xorshift128PlusKey
        {
            uint64_t s1;
            uint64_t s2;
        };

        /**
        * \brief Return a new 64-bit random number.
        */
        uint64_t xorshift128plus(Xorshift128PlusKey* key);

I would like to seed my RNG using rdtsc (processor time stamp). The problem is that the __rdtsc intrinsic under msvc returns a 64 bit unsigned integer and the seed must be a 32 bit unsigned integer. What is the best way to convert the rdtsc to a seed while preserving randomness. The conversion must be as fast as possible.
I can't use the std lib or boost. (It's for a game engine)

A: The 64-bit processor timestamp isn't random at all, so there is no need to preserve randomness when narrowing it to 32 bits. You can simply use the least-significant 32 bits as your seed. Randomness is the responsibility of the PRNG, not of the seed.
unsigned __int64 tsc = __rdtsc();
uint32_t seed = static_cast<uint32_t>(tsc & 0xFFFFFFFF);


text:
Q: Writing CSV values to file results in values being separated in single characters (Python) Kinda knew to Python:
I have the following code:
def printCSV(output, values, header):
 63     """
 64         prints the output data as comma-separated values
 65     """
 66
 67     try:
 68         with open(output, 'w') as csvFile:
 69             #print headers
 70             csvFile.write(header)
 71
 72             for value in values:
 73                 #print value, "\n"
 74                 csvFile.write(",".join(value))
 75                 csvFile.write("\n")
 76     except:
 77        print "Error occured while writing CSV file..."

Values is a list constructed somewhat like this:

values = []

for i in range(0,5):
    row = "A,%s,%s,%s" % (0,stringval, intval)
    values.append(row)

When I open the file created by the above function, I expect to see something like this:
Col1,Col2,Col3,Col4
A,0,'hello',123
A,0,'foobar',42

Instead, I am seeing data like this:
Col1,Col2,Col3,Col4
A,0,'h','e','l','l','o',1,2,3
A,0,'f','o','o','b','a','r',4,2

Anyone knows what is causing this?
I even tried to use fopen and fwrite() directly, still the same problem exists.
Whats causing this?

A: The problem you're encountering is that you're doing ",".join(value) with value being a string.  Strings act like a collection of characters, so the command translates to "Join each character with a comma."
What you could do instead is use a tuple instead of a string for your row values you pass to printCSV, like this:
values = []

for i in range(0,5):
    row = ('A', 0, stringval, intval)
    values.append(row)


text:
Q: Is it possible to use NHibernate Filters to filter through references? Contrived example, but let's say I have a these entities:
public class Root
{
    public virtual Customer Customer { get; set; }
}

public class Customer
{
    public virtual CustomerData Data { get; set; }
}

public class CustomerData
{
    public virtual string FooName { get; set; }
}

Now, let's say I want to create a filter for Root based on the value of FooName. Intuitively, I tried this in my FooMap class. Using Fluent mappings.
ApplyFilter("FooNameFilter", "Customer.Data.FooName in (:argument)");

This doesn't work. A SqlClient.SqlException is thrown stating The multi-part identifier "Customer.Data.FooName" could not be bound.
Is there a way to make filters work this way, or am I forced to move that logic into all Query<Root>()s instead?

A: What could be working, is to move the filter to the CustomerData object if possible, or to create "more sophisticated SQL condition" applied on the Customer mapping. But it is about pure SQL, no references. How do the filters work?
The filters are the same as the where clause, but could be adjusted in a runtime. The extract from documentation 18.1. NHibernate filters

NHibernate adds the ability to pre-define filter criteria and attach
  those filters at both a class and a collection level. A filter
  criteria is the ability to define a restriction clause very similiar
  to the existing "where" attribute available on the class and various
  collection elements. Except these filter conditions can be
  parameterized. The application can then make the decision at runtime
  whether given filters should be enabled and what their parameter
  values should be. Filters can be used like database views, but
  parameterized inside the application.

The definition of the where:

where (optional) specify an arbitrary SQL WHERE condition to be used when retrieving objects of this class

Other words, these settings act as "add on" to our mapping. They are extending it (both where and filter) with more SQL balast. The filter could be shared among many mappings and applied to all queries inside one session, but it must target the column:
condition=":myFilterParam = MY_FILTERED_COLUMN"


text:
Q: Proving the Functor laws for free monads; am I doing it right? I'm having a bit of a hard time understanding how to prove the Functor and Monad laws for free monads.  First off, let me put up the definitions I'm using:
data Free f a = Pure a | Free (f (Free f a))

instance Functor f => Functor (Free f) where
    fmap f (Pure a) = Pure (f a)
    fmap f (Free fa) = Free (fmap (fmap f) fa)

instance Functor f => Monad (Free f) where
    return = Pure
    Pure a >>= f = f a
    Free fa >>= f = Free (fmap (>>=f) fa)

{-

Functor laws:
(1) fmap id x == x
(2) fmap f (fmap g x) = fmap (f . g) x

Monad laws:
(1) return a >>= f   ==  f a
(2) m >>= return     ==  m
(3) (m >>= f) >>= g  ==  m >>= (\x -> f x >>= g)

-}

If I understand things correctly, the equational proofs require appeal to a coinductive hypothesis, and it goes more or less like this example:
Proof: fmap id == id

Case 1: x := Pure a
fmap id (Pure a)
  == Pure (id a)   -- Functor instance for Free
  == Pure a        -- id a == a

Case 2: x := Free fa
fmap id (Free fa)
  == Free (fmap (fmap id) fa)  -- Functor instance for Free f
  == Free (fmap id fa)         -- By coinductive hypothesis; is this step right?
  == Free fa                   -- Functor f => Functor (Free f), + functor law

I've highlighted the step where I'm not sure if I'm doing things right.
If that proof is right, then the proof for the Free constructor case of the second law is as follows:
fmap f (fmap g (Free fa))
  == fmap f (Free (fmap (fmap g) fa))
  == Free (fmap (fmap f) (fmap (fmap g) fa))
  == Free (fmap (fmap f . fmap g) fa)
  == Free (fmap (fmap (f . g)) fa)           -- By coinductive hypothesis
  == fmap (f . g) (Free fa)

A: Yes, this is correct. The 'base case' for the coinduction is the Pure constructor, and the induction is over levels of nesting of the Free constructor.
The complete proofs are
-- 1. First functor law

--   a. Base case

fmap id (Pure a) = Pure (id a) -- Functor instance for Free
                 = Pure a      -- definition of id

--   b. Inductive case

fmap id (Free fa) = Free (fmap (fmap id) fa) -- Functor instance for Free
                  = Free (fmap id fa)        -- coinductive hypothesis
                  = Free fa                  -- 1st functor law for f

-- 2. Second functor law

--   a. Base case

fmap f (fmap g (Pure a)) = fmap f (Pure (g a))   -- Functor instance for Free
                         = Pure (f (g a))        -- Functor instance for Free
                         = Pure ((f . g) a)      -- Definition of (.)
                         = fmap (f . g) (Pure a) -- Functor instance for Free

--   b. Inductive case

fmap f (fmap g (Free fa)) = fmap f (Free (fmap (fmap g) fa))        -- Functor instance for Free
                          = Free (fmap (fmap f) (fmap (fmap g) fa)) -- Functor instance for Free
                          = Free (fmap (fmap f . fmap g) fa)        -- 2nd functor law for f
                          = Free (fmap (fmap (f . g) fa))           -- Coinductive hypothesis
                          = fmap (f . g) (Free fa)                  -- Functor instance for Free


text:
Q: 400 response: service unavailable (am i doing a a sell wrong or is it coinbase?) I'm trying to get a quote for a small amount of bitcoin and it's been giving me back a 400 response back with the error saying the service is unavailable{'errors': [{'id': 'service_unavailable', 'message': 'It looks like we encountered a problem. Sorry for the trouble!'}]}
The following code is what is what i'm using and I have the (wallet:buys:create) buy scope on as well
    def sell(self):

    link="https://api.coinbase.com/v2/accounts/"+self.id+"/sells"

    data = {
    'amount': '.001',
    'currency': "BTC",
    'payment_method': self.method[1][1],#id of the payment method
    "quote":"true"
}
    headers = {
    'Content-Type': 'application/json',
    'Authorization': f'Bearer {self.tokens[0]}'
}
    r = requests.post(link, data=data, headers=headers)
    print(r.json())

A: 400 is bad request, they do have it labeled wrong like @klausd suggested.
That said, the docs for sells shows the request type is get and you're using post which would be a bad request.
https://developers.coinbase.com/api/v2#list-sells

GET https://api.coinbase.com/v2/accounts/:account_id/sells


text:
Q: JS/Jquery: how to check whether dropdown has selected values? I've googled and tried a number of ways to do this but none work for me so far. What I am looking for is quite simple: I want to be able to tell whether a dropdown has a selected value or not. The problem is that selectedIndex, :selected, val(), etc. do return results for the following case:
<select>
<option value="123">123</option>
<option value="234">234</option>
</select>

Obviously the browser will display this dropdown with the 123 option being selected but it will be selected only because there are no other options, in reality this dropdown doesn't have a selected value because there is no "selected" property. So basically I am trying to find how to tell apart the above dropdown from this one
<select>
<option selected value="123">123</option>
<option value="234">234</option>
</select>

A: Quick solution:
<select>
<option selected></option>
<option value="123">123</option>
<option value="234">234</option>
</select>

Then see if you have a .val()

A: var hasValue = ($('select > [selected]').length > 0);

Alternatively,
var hasValue = $('select').has('[selected]');

A: The approved answer doesn't seem to work for me.
Here is how I do it to check if all select options are selected:
if($('select option:selected').length > 0) {
/* Do your stuff here */
}

A: As far as I can tell, there is no functional distinction between your two examples.  Essentially, the browser automatically selects the first option.
See, for example, the result of
$('option:selected')

on your first example.
If you really want to prevent this happening, you have two options.  The first is to introduce a new, empty element into the select, per Jason's answer.  The other option is to deselect the automatically selected value:
$(document).load(function(){
    $('option:selected').attr('selected', false);
});

This clears the selection.  Any result of $('select').val() that isn't an empty string will therefore be a change by the user.


text:
Q: GWT Async call execution order problem I have a problem with a throw execution in GWT. So I want to show a simple String list in Client side located on "Server Side". Ok, I have in my Main class this atributes:

private final GreetingServiceAsync greetingService = Util.getInstance(); // This is like > typing GWT.create( GreetingService.class );
  public  ArrayList songs = new ArrayList();

and in my onModuleLoad() method I have a call to another private method that make the Async call to the Server class:

songs.addAll(getSongsList());

So my getSongsList method is as follow:
public ArrayList<String> getSongsList() {
        final int defaultSize = 4;
        final ArrayList<String> temp = new ArrayList<String>();

        GWT.log("Enter in getSongsLists");
        greetingService.greetSongMostPopular(defaultSize,
                new AsyncCallback<ArrayList<String>>() {

                    public void onSuccess(ArrayList<String> result) {
                        GWT.log("Result is:" + result);
                        temp.addAll(result);
                        GWT.log("Case 1 TEMP= " + temp);
                    }

                    public void onFailure(Throwable caught) {
                        // throw new
                        // UnsupportedOperationException("Not supported yet.");
                        Window.alert("Error greeting data");

                    }

                });
        GWT.log("CASE 2 TEMP = " + temp);
        return temp;

    }

My problem is that in Case 1 I get

[INFO] [MainModule] - Case 1 TEMP= [Song 1, Song 2, Song 3, Song 4]

but in CASE 2 I get the ArrayList empty!!!

[INFO] [MainModule] - Case 1 TEMP= []

What am I doing wrong?
Thanks in advance!

A: The call to greetSongsMostPopular is asynchronous. This means that the call begins and the code continues directly to the next line of code, in your case GWT.log("CASE 2 TEMP..."). When this line of code is executed, the results are not yet available and you end up with an empty list.
Later, in the background, onSuccess is called with the results. At this point you should call a function to process the results. You can use a pattern similar to the AsyncCallback class, with an onSuccess and onFailure so the caller of this code can handle both cases, or you can just have the caller pass in their own AsyncCallback instance which would make it a thin wrapper around your greetSongsMostPopular RPC function.

A: This is normal :  the callback is called when your server send the answer but the greetSongMostPopular return imediatly.
The call is asynchronous.
All code must be done in the callback (call a function)
Here is the exact process :

*

*greetingService.greetSongMostPopular is called

*temp is empty

*the second GWT.log is called : temp is always empty

*the getSongsList method return : temp is always empty

*the server send the answer to the callback : temp is filled

A: You are not doing anything wrong. This is expected since you are not dealing with synchronous calls. So the case 2 is only invoked after the asynchronous call returns from the server side.


text:
Q: Parsing Google Maps API for Latitude and Longitude (Bash) I am using curl
`curl "https://maps.googleapis.com/maps/api/geocode/json?address=$WHERE&key=$API_KEY"`

and the result is
`
{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Saket",
               "short_name" : "Saket",
               "types" : [ "political", "sublocality", "sublocality_level_1" ]
            },
            {
               "long_name" : "New Delhi",
               "short_name" : "New Delhi",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "South Delhi",
               "short_name" : "South Delhi",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Delhi",
               "short_name" : "DL",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "110017",
               "short_name" : "110017",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "Saket, New Delhi, Delhi 110017, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 28.529262,
                  "lng" : 77.2166529
               },
               "southwest" : {
                  "lat" : 28.517834,
                  "lng" : 77.20113789999999
               }
            },
            "location" : {
               "lat" : 28.5245787,
               "lng" : 77.206615
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 28.529262,
                  "lng" : 77.2166529
               },
               "southwest" : {
                  "lat" : 28.517834,
                  "lng" : 77.20113789999999
               }
            }
         },
         "place_id" : "ChIJ3T8F3fDhDDkRnxNgWBpc2Zc",
         "types" : [ "political", "sublocality", "sublocality_level_1" ]
      }
   ],
   "status" : "OK"
}`

How can I just get the north-east latitudes and longitudes using bash ? Could you please tell me how I should parse it through jq, or another alternative. I need the values to be either saved in different text files. i.e lat.txt and long.txt.
I'm planning to pass the latitude and longitude as variables and the use them in another api to get the air quality using the latitude and longitude. Even an alternative would work from which I can scrape the lat and long.

A: This is fairly straight forward we given know that there is only two lines we are concerned with (longitude and latitude) and given that the format of the json is fixed so piping the curl command through awk:
curl "https://maps.googleapis.com/maps/api/geocode/json?address=$WHERE&key=$API_KEY" | awk '/northeast/ {getline;print;getline;print;exit}'

Search for a pattern match northeast and then then read in the next record/line, print (longitude) and then read in the next record and print (latitude)

A: You can try with jq something like this:
curl ... | jq -r '.results[0].geometry.bounds.northeast | "\(.lat) \(.lng)"'

Output:
28.529262 77.2166529

Or:
curl ... | jq '.results[0].geometry.bounds.northeast | .lat, .lng'

Output:
28.529262
77.2166529


text:
Q: Closed subsets of a compact metric space with distance zero from each other I am currently taking a Metric Spaces course, and during an activity, I had to prove the following result:
Let $(X,d)$ be a compact metric space and $A,B \subset X$ two closed subsets such that $d(A,B)=0$. Then $A \cap B \neq \emptyset$.
My reasoning was the following. Using the fact that $d(A,B) = 0$, for every $n \in \mathbb{N}$, we may obtain $a_n \in A$ and $b_n \in B$ such that $d(a_n,b_n) < \frac1n$. This gives us two sequences $(a_n)_{n \in \mathbb{N}} \subset A$ and $(b_m)_{m \in \mathbb{N}}\subset B$ with the property that for every $\epsilon>0$, there is a natural number $n_0$ such that $d(a_n,b_n) < \epsilon$ for every $n \geq n_0$.
From the compactness of $X$ we obtain a subsequence $(a_{n_k})_{k \in \mathbb{N}}$ of $(a_n)$ which converges to some point $a \in X$. We know that in fact $a \in A$ because $A$ is closed. Now the claim is that $a \in A \cap B$. To show this, it is sufficient to show that $a \in \overline{B}$.
For any real number $r>0$ we know that there exists an $n_0 \in \mathbb{N}$ such that $d(a_n,b_n)< \frac r2$ for every $n \geq n_0$, and from the convergence of the subsquence $(a_{n_k})$, there exists and $n_{k_0} \in \mathbb{N}$ such that $d(a,a_{n_k}) < \frac r2$ for every $n_k \geq n_{k_0}$. Then, taking any $n_k \geq \max\{n_0,n_{k_0}\}$ we have
$$d(a,b_{n_k}) \leq d(a,a_{n_k})+d(a_{n_k},b_{n_k}) < \frac r2 + \frac r2 = r,$$
so that $b_{n_k}$ lies in the open ball of radius $r$ centered in $a$, thus showing that $a \in \overline{B}$.
While I was discussing my attempt of proof with the person that was applying the activity, she claimed that it was not correct because I had to be more careful when using the indexes of the subsequence $(a_{n_k})$ to identify specific terms of the sequence $(b_n)$ as I did in the last inequality above. She argued that I should first consider the sequence $(b_{n_k})_{k \in \mathbb{N}}$ with the same indices of the subsequence $(a_{n_k})$, obtain a convergent subsequence of $(b_{n_k})$ and then use this new subsequence during the proof. I didn't really understand why this would be necessary or what is the problem with the argument above.
So I would like some help to know if what I did is correct, or to understand where is the problem if the proof happens to be wrong. Thanks in advance!

A: This is a long comment to illustrate a slightly different method. It uses some  results that you might not be familiar with.

*

*For any metric space $(U,e)$ and $\phi\ne V\subset U,$ the function $f(u)=\inf\{e(u,v):v\in V\}=e(u,V)$ is continuous from $U$ to $\Bbb R.$ The proof is elementary.

*The continuous image of a compact space is compact.  The proof is elementary. And for a  subspace $A$ of a compact Hausdorff space $X$ (for example, when $X$ a compact metric space) we have: $A$ is compact iff $A$ is closed in $X$.

*So in your Q, assuming $A\ne \phi \ne B$, the function $f_A(a)=d(a,B)$ for $a\in A$ is continuous from $A$ to $\Bbb R $. So $f_A(A)$  is a compact non-empty subset of $\Bbb R$  and therefore $\min f_A(A)$ exists.
If $\min f_A(A)=r>0$ then $\forall a\in A\;\forall b\in B\;(d(a,b)\geq r)$, that is, $d(A,B)\geq r>0.$
If $\min f_A(A)=0$ then  there exists $a_0$ in $A$ with $f_A(a_0)=0.$ That is $\inf \{d(a_0,b):b\in B\}=0.$  So every open ball of positive radius, centered at $a_0,$ contains a member of $B.$ So $a_0\in \overline B=B.$
Remark. If $C,D$ are closed non-compact subsets of a metric space $(Y,e)$ it may be that $\inf \{e(a,b):a\in A,\;b\in B\}=0$ and $A\cap B=\phi.$ For example let $Y=\Bbb R$ with $e(x,y)=|x-y|.$ Let $A=\Bbb Z^+$ and $B=\{n+2^{-n}: n\in \Bbb Z^+\}.$


text:
Q: How to get the eclipse project Dependency? I'm trying to write a method (in java) which prints all the project dependencies.
Is there a file which eclipse saves this project dependencies list ?
I look at the files in example eclipse project:
.  ..  .indexes  .location  .markers  org.eclipse.jdt.core
but none of them contains the relevant information.

A: It's the .classpath file in the root of your project folder. It might be hidden by the file system so you would need to reveal it by changing some settings of your file system.


text:
Q: Compress grayscale image using its histogram I have a background on mathematics and Machine Learning, but I'm quite new on image compression. The other way I was thinking in the optimal way to compress an image just using a lookup table. This means, given an original image which has N unique values, change it to a new image with M unique values being M<N. Given a fixed value of M, my question was how to pick those values. I realized that if we take as figure of merit the total error (MSE) of all the pixels, all the information has to be in the histogram of the pixel intensities. Somehow, the most common values should be mapped to a closer value than the uncommon values, making the higher regions of the histogram more "dense" in the new values that the low regions.Hence I was wondering if it exists a mathematical formula that:
-Given the histogram h(x) of all the pixels intensities
-Given the number of uniques new values M
Defines the set of new M values {X_new} that minimizes the total error.
I tried to define the loss function and take the derivative, but it appeared some argmax operations that I don't know how to derivate them. However, my intution tells me that it should exist a closed formula.....
Example:
Say we have an image with just 10 pixels, with values {1,1,1,1,2,2,2,2,3,3}. We initially have N=3
and we are asked to select the M=2 unique values that minimizes the error. It is clear, that we have to pick the 2 most common ones, so {X_new}={1,2} and the new image will be "compressed" as {1,1,1,1,2,2,2,2,2,2}. If we are asked to pick M=1, we will pick {X_new}=2 to minimize the error.
Thanks!

A: This is called color quantization or palettization. It is essentially a clustering problem, usually in the 3D RGB space. Each cluster becomes a single color in the downsampled image. The GIF and PNG image formats both support palettes.
There are many clustering algorithms out there, with a lot of research behind them. For this, I would first try k-means and DBSCAN.
Note that palettization would only be one part of an effective image compression approach. You would also want to take advantage of both the spatial correlation of pixels (often done with a 2-D spatial frequency analysis such as a discrete cosine transform or wavelet transform), as well as taking advantage of the lower resolution of the human eye in color discrimination as opposed to grayscale acuity.
Unless you want to embark on a few years of research to improve the state of the art, I recommend that you use existing image compression algorithms and formats.


text:
Q: Ploting a Buffer Around a Point on a Map - R SF I've been trying to plot a buffer around a point on a map but when I do the buffer doesn't appear in the right place like this.
Faulty R Map
The correct location is in California.
Here's my code:
library(tigris)
library(sf)
library(tidyverse)

projection <- 102003

options(tigris_use_cache =  TRUE)
county_polys <- counties(class = 'sf') %>%
  filter(STATEFP %in% c('06','41','53','04','16','32','49')) %>%
  st_transform(projection)

  centroids <- county_polys %>%
  as_tibble %>% select(INTPTLON,INTPTLAT) %>%
  mutate(
    INTPTLON = as.double(INTPTLON),
    INTPTLAT = as.double(INTPTLAT)) %>%
  st_as_sf(coords = c('INTPTLON','INTPTLAT'), crs = projection)

 pt <- centroids[2,]
 pt_buffer <- st_buffer(pt,150000)

 ggplot() + geom_sf(data = county_polys) + geom_sf(data = pt_buffer,color = 'red')

A: We can use the st_centroid function to get the centroid to avoid errors. There is no need to convert the sf object to other classes.
# This is the only thing I changed from your original code
# Get the centroid by st_centroid
centroids <- county_polys %>% st_centroid()

pt <- centroids[2,]
pt_buffer <- st_buffer(pt,150000)

ggplot() + geom_sf(data = county_polys) + geom_sf(data = pt_buffer,color = 'red')


text:
Q: Additional table not created I'm trying to add a second table to my application but I'm not having any luck.  The two tables are their own classes and are singletons.  I pass in a reference of the database in the onUpgrade method and again as an instance variable.
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    transTable = TransactionTable.getInstance(db);
    sysTable = SystemTable.getInstance(db);

    onCreate( db );

    transTable.updateTable();
    sysTable.updateTable();
}

The onCreate method just calls the create methods in all the tables.
@Override
public void onCreate(SQLiteDatabase db) {
    transTable.createTable();
    sysTable.createTable();
}

The second table, sysTable, doesn't throw and exception while executing the following create statement.
public void createTable() {
    db.rawQuery("CREATE TABLE IF NOT EXISTS " + tableName + " ("
            + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + lastUsed
            + " INTEGER, " + balance + " INTEGER, " + accountName
            + " TEXT, UNIQUE ( " + accountName + " ) )", null);
}

But, when I run a simple query such as the following:
 db.rawQuery("select * from " + tableName, null);

I get an error stating
 android.database.sqlite.SQLiteException: no such table: system_t: ,
 while compiling: select * from system_t

There is no issue with the first table being dropped or created.  Any ideas?

A: change createTable method the code:
 db.rawQuery

to
db.execSQL()


text:
Q: Difference between io.r2dbc.pool.PoolingConnectionFactoryProvider.MAX_SIZE vs ConnectionPoolConfiguration max size in r2dbc I am trying to understand the difference between 2 configurable parameters while creating a connection pool using r2dbc-pool.
I was able to configure the connection pool with the help of the below post:
Connection pool size with postgres r2dbc-pool
But wanted to understand the difference while configuring max size and initial size while creating
ConnectionFactory connectionFactory = ConnectionFactories.get(ConnectionFactoryOptions.builder()
        .option(DRIVER, "pool")
        .option(PROTOCOL, "postgresql")
        .option(HOST, host)
        .option(USER, user)
        .option(PASSWORD, password)
        .option(MAX_SIZE, 30)
        .option(INITIAL_SIZE, 10)
        .option(DATABASE, database)
        .build());
ConnectionPoolConfiguration configuration = ConnectionPoolConfiguration.builder(connectionFactory)
        .maxIdleTime(Duration.ofMinutes(30))
        .initialSize(initialSize)
        .maxSize(maxSize)
        .initialSize(20)
        .maxCreateConnectionTime(Duration.ofSeconds(1))
        .build();

A: There isn't a difference really, these are just different ways to create a connection pool.
The initial size is the number of open connections to the database once the application starts.
You can check that with the query:
select * from pg_stat_activity;

You'll see exactly the number you specified as initial size.
Max size is the maximum nuber of connections that can be open at the same time (you do not control that directly, underlying pool implementation will scale the number of opened connections with higher load)


text:
Q: Javascript and C# COM interaction I am using C# COM Interop techniques to interact with some device from website using ActiveX. Right now I can call C# codes from javascript and pass only string values. But I intend to pass javascript structure into C# method and the reverse. How can I do that.
Right now as an alternative I pass JSON formatted string from C# code and generate javascript object runtime using eval. But I want more control on that.
Thanks
Maksud

A: I ended up using NewtonSoft's JSON Library as I could not find native solution.