text:
Q: Ajax serialize with other parameters, I am very close on this working. I am just having issues with one variable (q3).
I have been working to get some data into a database using ajax, php and MySQL. It is all working except question 3. All of the data submits but question 3, in the database, is always empty...
Does anyone have any ideas? I am new to using serialize() but logging it in the console shows a string of all checked boxes.
Please note this is only a subset of code. Thank you.
HTML:

3. If you don't use the bus system, please let us know why (pick your top 3 reasons):

    <input type="checkbox" name="question3_answer[]" class="question3_answer" value="Buses do not go where I want to go" /> Buses do not go where I want to go
    <input type="checkbox" name="question3_answer[]" class="question3_answer" value="Buses do not run when I need it" /> Buses do not run when I need it
    <input type="checkbox" name="question3_answer[]" class="question3_answer" value="Buses are too crowded" /> Buses are too crowded
    <input type="checkbox" name="question3_answer[]" class="question3_answer" value="Buses are too crowded" /> Buses are unreliable
    <input type="checkbox" name="question3_answer[]" class="question3_answer" value="Transfers between bus routes are difficult" /> Transfers between bus routes are difficult
    <input type="checkbox" name="question3_answer[]" class="question3_answer" value="Waiting times are too long" /> Waiting times are too long
    <input type="checkbox" name="question3_answer[]" class="question3_answer" value="I don't live near a bus route" /> I don't live near a bus route
    <input id="question3_other" type="checkbox" name="" class="question3_answer other" value="other" />Other:
    <input type="text" id="question3_textanswer" name="question3_answer[]" class="question3_answer" placeholder="Your answer here" style="width:40%;display:none;">

    <button id="toPlay" onclick="submit_1();">Submit and continue</button>

Ajax:
function submit_1() {
        var q1 = document.getElementById("question1_answer").value;
        var q2 = document.getElementById("question2_answer").value;
        var q3 = $('.question3_answer:checked').serialize();
        var q4 = document.getElementById("question4_answer").value;
        var q5 = document.getElementById("question5_answer").value;

        var dataString = 'question1_answer=' + q1 + '&question2_answer=' + q2 + '&question3_answer=' + q3 + '&question4_answer=' + q4 + '&question5_answer=' + q5;

        $.ajax({
            type: "POST",
            url: "php/video_form_process.php",
            data: dataString,
            cache: false,
            success: function(html) {
                alert(html);
            }
        });
        return false;
    }

PHP
if (isset($_POST['question1_answer'])) {
// Gets data from URL parameters
$question1_answer = $_POST['question1_answer'];
$question2_answer = $_POST['question2_answer'];
$question3_answer = $_POST['question3_answer'];
$question4_answer = $_POST['question4_answer'];
$question5_answer = $_POST['question5_answer'];

    $query= "INSERT INTO `responses` (`uid`, `time`, `q1`,`q2`,`q3`,`q4`,`q5`, `ipaddr`) VALUES ('', '$today','$question1_answer','$question2_answer','$question3_answer','$question4_answer','$question5_answer')";

    if ($query_run = mysqli_query($server, $query)) {
        echo 'success';
    } else {
        echo 'error';
    }
}

WORKING Ajax:
    function submit_1() {
        var q1 = $(".question1_answer:checked").val();
        var q2 = document.getElementById("question2_answer").value;

        var q3 = [];
        $(".question3_answer:checked").each(function() {
            q3.push($(this).val());
        });

        var q4 = document.getElementById("question4_answer").value;
        var q5 = document.getElementById("question5_answer").value;

        var dataString = 'question1_answer=' + q1 + '&question2_answer=' + q2 + '&question3_answer=' + q3 + '&question4_answer=' + q4 + '&question5_answer=' + q5;

        $.ajax({
            type: "POST",
            url: "php/video_form_process.php",
            data: dataString,
            cache: false,
            success: function(html) {
                alert(html);
            }
        });
        return false;
    }

WORKING PHP:
if (isset($_POST['question1_answer'])) {
// Gets data from URL parameters
$question1_answer = mysqli_real_escape_string($server, $_POST['question1_answer']);
$question2_answer = mysqli_real_escape_string($server, $_POST['question2_answer']);
$question3_answer = mysqli_real_escape_string($server, $_POST['question3_answer']);
$question4_answer = mysqli_real_escape_string($server, $_POST['question4_answer']);
$question5_answer = mysqli_real_escape_string($server, $_POST['question5_answer']);

$query= "INSERT INTO `responses`
         (`time`, `q1`,`q2`,`q3`,`q4`,`q5`, `ipaddr`)
         VALUES ('{$today}', '{$question1_answer}', '{$question2_answer}', '{$question3_answer}', '{$question4_answer}', '{$question5_answer}', '127.0.0.1')";

if ($query_run = mysqli_query($server, $query)) {
    echo 'success';
} else {
    echo 'error';
}

}

A: Try something like this to post value.
using array push you can add your checkbox value in s3 variable see below code.
    var s3=[];
    $("input:checked").each(function() {
       s3.push($(this).val());
    });

A: Some advice ...
JS

*

*use an object for your data, not a string

*you can use map to create an array of ids or something from checkes elements

*add dataType to your ajax, to be sure

PHP

*where is your $today declared? are you sure it is there?

*remove uid from sql query when it's empty

*escape the values

*escape your sql query

*you set no IP address in your values

JS
function submit_1() {
    $.ajax({
        type: "POST",
        url: "php/video_form_process.php",
        dataType: "html",
        data: {
            question1_answer = $("#question1_answer").val(),
            question2_answer = $("#question2_answer").val(),
            question3_answer = $(".question3_answer:checked").map(function() {
                return $(this).val();
            }).get().join(","),
            question4_answer = $("#question4_answer").val(),
            question5_answer = $("#question5_answer").val()
        },
        cache: false,
        success: function(html) {
            alert(html);
        }
    });

    return false;
}

PHP
if (isset($_POST['question1_answer'])) {
    // Gets data from URL parameters
    $question1_answer = mysqli_real_escape_string($server, $_POST['question1_answer']);
    $question2_answer = mysqli_real_escape_string($server, $_POST['question2_answer']);
    $question3_answer = mysqli_real_escape_string($server, $_POST['question3_answer']);
    $question4_answer = mysqli_real_escape_string($server, $_POST['question4_answer']);
    $question5_answer = mysqli_real_escape_string($server, $_POST['question5_answer']);

    $query= "INSERT INTO `responses`
             (`time`, `q1`, `q2`, `q3`, `q4`, `q5`, `ipaddr`)
             VALUES ('{$today}', '{$question1_answer}', '{$question2_answer}', '{$question3_answer}', '{$question4_answer}', '{$question5_answer}', '127.0.0.1')";

    if ($query_run = mysqli_query($server, $query)) {
        echo 'success';
    } else {
        echo 'error';
    }
}

A: Instead of computing the data to send through Ajax, just use $(FORM_ID).serialize() where FORM_ID is a selector which selects your form.
And in the ajax call this line data: dataString, becomes $(FORM_ID).serialize(),

A: Your code should be
function submit_1() {
        var q1 = document.getElementById("question1_answer").value;
        var q2 = document.getElementById("question2_answer").value;
        var q4 = document.getElementById("question4_answer").value;
        var q5 = document.getElementById("question5_answer").value;

        var q3 = [];
        $('input[type="checkbox"][name="question3_answer[]"]:checked').each(function(){
            q3.push($(this).val());
        })

        var dataPost = {
            question1_answer:  q1,
            question2_answer: q2,
            question3_answer: q3,
            question4_answer: q4,
            question5_answer: q5
        };

        $.ajax({
            type: "POST",
            url: "php/video_form_process.php",
            data: dataPost,
            cache: false,
            success: function(html) {
                alert(html);
            }
        });
        return false;
    }


text:
Q: Detecting rows with the same combination of numbers in the first two columns, and selecting the one with the highest number in the third column I have a data.frame with only three columns but with many thousands of rows. The first and the second columns report numerical ID, and their combination indicate a link (e.g. A-B equal to B-A).
Now, I'd like to delete all rows that are duplicates for the link, selecting the row with the highest value in the third column.
Below a short example:
My input data.frame:
1   2    100
102 100  20000
100 102  23131
10  19 124444
10  15   1244
19  10   1242
10  19   5635
2   1    666
1   2     33
100 110     23

what I aim to get:
100 102  23131
10  19 124444
10  15   1244
2   1    666
100 110     23

I' trying to find the solution in R, otherwise postgreSQL would be fine too.
Thanks a lot!

A: The idea is similar to this one. You can create two additional columns using pmin an pmax to group as follows:
A data.table solution. But if you don't want data.table, then you can still use the idea. However, it is highly improbable you get faster than data.table solution with just R code.
# assuming your data.frame is DF
require(data.table)
DT <- data.table(DF)
# get min of V1,V2 on one column and max on other (for grouping)
DT[, `:=`(id1=pmin(V1, V2), id2=pmax(V1, V2))]
# get max of V3
DT.OUT <- DT[, .SD[which.max(V3), ], by=list(id1, id2)]
# remove the id1 and id2 columns
DT.OUT[, c("id1", "id2") := NULL]

#     V1  V2     V3
# 1:   2   1    666
# 2: 100 102  23131
# 3:  10  19 124444
# 4:  10  15   1244
# 5: 100 110     23

A: Here is an option in base R, mostly for sharing alternatives. As it involves transposing and sorting, it is, indeed, likely to be slow on your "thousands of rows" dataset. It assumes your data.frame is called "mydf":
myAggs <- as.data.frame(t(apply(mydf[1:2], 1, sort)))
mydf[1:2] <- myAggs
aggregate(V3 ~ ., mydf, max)
#    V1  V2     V3
# 1   1   2    666
# 2  10  15   1244
# 3  10  19 124444
# 4 100 102  23131
# 5 100 110     23

A: In postgresql ..
If your original table was constructed with three columns of integers - a, b, c - then you can use conditional functions to establish a unique key of max(a, b), min(a, b):
select
 case when a>=b then a else b end as key1,
 case when a>=b then b else a end as key2,
 c from table;

You can then use 'group' to get the maximum C for each key (key1, key2):
select
 key1,
 key2,
 max(c) as max_c
 from (
  select
  case when a>=b then a else b end as key1,
  case when a>=b then b else a end as key2,
  c from table
 ) query
 group by key1, key2;

A: Postgresql:
select distinct on (1, 2)
    least(a, b), greatest(a, b), c
from data_frame
order by 1, 2, c desc

redpajama_set_name: RedPajamaStackExchange


text:
Q: ng-change in select not working I'm trying to update a list2 from a list1, and i used ng-change for that.
My app is fully configured and the controller for the html page is well setted.
The only thing that when i select the elemt from my first list1 the method updateList2 never invocked
NameLIst1
<select ng-model="idLIST1"
        ng-change="updateList2(idLIST1)"
        ng-options="elt.id as elt.name for elt in list1">

        <option  value="">select one</option>
</select>

Name LIST 2
<select  ng-model="idLIST2"
        ng-options="elt.id as id.name for elt in list2">

        <option  value="">select one</option>
</select>

$scope.updateList2 = function(id){
alert("id ="+id);
}

A: I have code which are written in below ,try this
it's work fine,also work with param,
but you don't need to pass param in methods

    NameLIst1
    <select ng-model="idLIST1"
            ng-change="updateList2(idLIST1)"
            ng-options="elt.id as elt.name for elt in list1">

        <option value="">select one</option>
    </select>

    Name LIST 2
    <select ng-model="idLIST2"
            ng-options="elt.id as id.name for elt in list2">

        <option value="">select one</option>
    </select>

var app = angular.module("test", ["ngRoute"])
        .controller("TestController", ['$scope', function ($scope) {
            $scope.list1 = [
               { id: 1, name: 'data1' },
               { id: 2, name: 'data2' },
               { id: 3, name: 'data3' },
               { id: 4, name: 'data4' },
            ];
            $scope.updateList2 = function (id) {
                alert("id =" + id);
            }
        }
        ]);


text:
Q: Postfix, virtual aliases and catchall for undefined addresses In Postfix 2.10.2, I have a setup with multiple domains and several virtual aliases to assign mail addresses to local users. It works fine as long as I do not add a catchall.
Before I used virtual aliases, I had a catchall defined with
local_recipient_maps =
luser_relay = catchall

but as I need to sort out mail addresses from different domains, I had to use virtual aliases.
Now postfix.org says I should do it like this, which I did:
/etc/postfix/main.cf:
virtual_alias_domains = example.com
virtual_alias_maps = hash:/etc/postfix/virtual

/etc/postfix/virtual:
postmaster@example.com account1
info@example.com       account1
sales@example.com      account2
@example.com         catchall

But if I do so, the catchall address grabs all my mail instead of just the mail to not explicitly defined addresses. Why is that and how do I change it?
I did postmap virtual and also restarted Postfix. There are no errors in the log, it just logs the delivery to the catchall address. And there is a warning "do not list domain example.com in BOTH mydestination and virtual_alias_domains", but I did not do that! I don't even have a mydestination directive. (There is one in the config below, but I added that after NickW suggested so.)
Here is my complete conf:
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
append_dot_mydomain = no
biff = no
broken_sasl_auth_clients = yes
config_directory = /etc/postfix
home_mailbox = Maildir/
inet_interfaces = all
inet_protocols = all
mailbox_command = /usr/lib/dovecot/deliver -c /etc/dovecot/dovecot.conf -m "${EXTENSION}"
mailbox_size_limit = 0
mydestination = $myhostname
myhostname = mydomain.com
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
myorigin = /etc/mailname
readme_directory = no
recipient_delimiter = +
relayhost =
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtp_use_tls = yes
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
smtpd_recipient_restrictions = reject_unknown_sender_domain, reject_unknown_recipient_domain, reject_unauth_pipelining, permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
smtpd_sasl_auth_enable = yes
smtpd_sasl_authenticated_header = yes
smtpd_sasl_local_domain = $myhostname
smtpd_sasl_path = private/dovecot-auth
smtpd_sasl_security_options = noanonymous
smtpd_sasl_type = dovecot
smtpd_sender_restrictions = reject_unknown_sender_domain
smtpd_tls_auth_only = yes
smtpd_tls_cert_file = /etc/dovecot/dovecot.pem
smtpd_tls_key_file = /etc/dovecot/private/dovecot.pem
smtpd_tls_mandatory_ciphers = medium
smtpd_tls_mandatory_protocols = SSLv3, TLSv1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtpd_use_tls = yes
tls_random_source = dev:/dev/urandom
virtual_alias_domains = $myhostname, myotherdomain.com
virtual_alias_maps = hash:/etc/postfix/virtual

A: If you include catch all email address in virtual alias then it will work.
in main.cf:
 virtual_alias_maps = hash:/etc/postfix/virtual

in virtual:
user1@example.com           user1@example.com
user2@example.com           user2@example.com
...
catchall@example.com        catchall@example.com
@example.com                catchall@example.com

A: So, I figured it out. Some people suggest that the catch-all has to be on top of the virtual alias file, but I tried that before and it did not help (though I found that solution quite logical).
What worked is:

*

*Set mydestination=localhost (that is not $myhostname)

*Add the catchall on top of the virtual alias file: @domain.com catchall-account@localhost

*Add all other virtual aliases below: contact@domain.com contact@localhost
The example assumes you have UNIX users named catchall-account and contact. Mails to contact@domain.com will be delivered to the contact user while all other mail will be delivered to the catch-all account.
Maybe this is not necessary in all cases, but in my special case I want to use an account to save mail for some addresses, but mail sent directly to that account should end up in the catch-all.
After all, looks like Postfix is not working it's way through the virtual aliases from top to bottom, and additionally catch-alls have some special priority. I will be glad about further comments in case someone is actually able to explain this behaviour.

A: The important part is that all real mailbox users are also put into the virtual alias lookup. This works around the fact that aliases have priority over real accounts. So it's not about the order of the entries, or whatever your mydestination is set to, you just have to add your real mailboxes as aliases, too, and the catchall will work as intended and only collect the mail for the undefined addresses.
So in the end, your lookup must look like that
@example.org   catchall@example.org
actually-exists@example.org       actually-exists@example.org
concrete-alias1@example.org       actually-exists@example.org
concrete-alias2@example.org       actually-exists@example.org

That way, mails for "actually-exists", "concrete-alias1" and "concrete-alias2" will all go to "actually-exists", a user that does actually exist on the system, while mail for all other possible receipients is shoved into "catchall".
Shoutout to this article for the tip. Confirmed with postfix 3.4.13.

A: Try setting your mydestination = $myhostname, and make sure your hostname is configured in main.cf, for example, myhostname = mail.example.com.


text:
Q: How to write a Linq to Entities query given a list of entities as parameter I have 2 tables: Materials and Colors with two colums
Materials (guid and name)
Colors (guid and name)

One Material can have a lot of colors  and a Color can be in a lot of Materials. (many to many relationship)
Using LINQ I can write Material.colors and this send me a list of the entities of color contained in that material.
I would like to make function in which I pass a list of Color and return what materials have those Colors.
I am writing in VB.net
Public Shared Function getMaterialsFromColor(vColors As List(Of Entities.Color)) As List(Of Entities.Materials)

    Dim _materials As New List(Of Entities.Materials)

    _materials.AddRange(From vmaterial as Entities.Materials where vmaterial.color.name=)

    '(this is the part that I dont know)
end function

thanks a lot
I am using sqlserver express and linq to entities (ado.net)


text:
Q: Change apt-get install path to 2nd hard drive I am new to Linux. I've installed Xubuntu instead of Windows 10 and I am happy with it but I am really curious if I can change the path of applications installed via apt-get install (or by any other ways for installing applications, like .deb packages). I currently have two hard drives - 1) 128GB SSD (currently about 100GB free), which is the booting and system folder and 2) 1TB HDD where is the /home/ direcotry. I really wan't to be able to store my applications on the HDD instead of the SSD, because I am scared that I will run out of space soon (f.e. I want to play World of Warcraft which is about 80GB's so I dont want to have it on disk where is about 100GB of free space). Is there any possible solution? I will be really happy for any help, Thanks!

A: If your going to be using Steam to install your games you can select where the games library is stored.  And if your going to use wine to install WOW wine uses a folder in your home directory to store games so either way you should be good.
Hope this helps,
Jason C.


text:
Q: How do I fix my broken .NET 6 installation on Ubuntu? I have .NET 6 and .NET 7 on my Ubuntu system. When I try to execute a test in Rider it says dotnet 6 isn't installed. But it is. If I run dotnet --list-runtimes it shows only .NET 7.

A: Looks like you have only runtime for .NET 6, but not Framework .NET 6. Building Apps and running tests needs framework too.


text:
Q: Image in button doesn't load, i only get a blue square I am trying to add a button to a screen and edit it programmatically, but most of the edits don't respond.
This is the button code:
@IBOutlet weak var buttonTest: UIButton!

let screen = UIScreen.mainScreen().bounds

let buttonImg = ResizeImage(UIImage(named: "Blokker")!, targetSize: CGSize(width: 50, height: 50))
    buttonTest.frame = CGRect(x: 0, y: screen.height - 300, width: screen.width * 0.5, height: screen.width * 0.5)
    buttonTest.setImage(buttonImg, forState: .Normal)
    buttonTest.setTitle("Test", forState: .Normal)
    buttonTest.imageView?.contentMode = .ScaleAspectFit
    view.addSubview(buttonTest)

The ResizeImage function works, i've used it in other view controllers already. The code for this is quoted below. The buttonTest.frame method doesn't work, the button will always stay in the same place without edits to the size. The image doesn't load either, in the place where the image should be, I can only see a blue square.
Does anyone know how to solve this problem? Thanks in advance!
The ResizeImage func:
func ResizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
    let size = image.size

    let widthRatio  = targetSize.width  / image.size.width
    let heightRatio = targetSize.height / image.size.height

    // Figure out what our orientation is, and use that to form the rectangle
    var newSize: CGSize
    if(widthRatio > heightRatio) {
        newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio)
    } else {
        newSize = CGSizeMake(size.width * widthRatio,  size.height * widthRatio)
    }

    // This is the rect that we've calculated out and this is what is actually used below
    let rect = CGRectMake(0, 0, newSize.width, newSize.height)

    // Actually do the resizing to the rect using the ImageContext stuff
    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
    image.drawInRect(rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

A: Using FruitAddict's comment:
let buttonImg = ResizeImage(UIImage(named: "Blokker")!, targetSize: CGSize(width: 50, height: 50)).imageWithRenderingMode(.AlwaysOriginal)

solved the image problem, for people who experience the same problem!
The frame problem hasn't changed so far..

A: The first part of your question I already answered in comment
Use imageView.imageRenderingMode = .AlwaysOriginal if you want the image to be the same as the source
and imageView.imageRenderingMode = .AlwaysTemplate if you want the image to be the same color as its container (images with no alpha channel will be a colored square)
For the frame problem, why are you the following line? Remove it.
view.addSubview(buttonTest)

Buttontest already has a superview as it's an outlet from storyboard/xib. Also, do not change frame rect if you're designing the button using storyboard/xib. You should learn how to use constraints for this.

A: according to me please use SDWebImage ThirdParty library please follow below link:-
https://github.com/rs/SDWebImage
or you can also install through pod also and use this library....
i show you below code using swift language:-
 let imageurl: NSURL? =  NSURL(string: "")

  imageview1.sd_setImageWithURL(url, placeholderImage:UIImage(named:"Ahmedabad_BRTS.jpg"))


text:
Q: In a git repository, how to remove old renamed"capitalization" folders without losing Git history I have a git repository, on which I changed a folder's name to all lower caps.
I successfully pushed the change, and when I do a git pull, I only get the new folder name, but when I go to gitlab and I view my branch, I have both folders Foo and foo on my branch.
How do I purge this from my repository?

A: If depends on your remote repository hosting service.
On GitLab, for instance, you can go to the folder you don't want, and you can delete the files there: that folder will then disappear.
It would be easier to have a "delete" button for the folder itself, but that is still pending (issue 3518)
The idea remains: try and fix the issue on the remote side (the Git repo hosting service) instead of locally (the local clone).
Then clone again.

A: If we do
git log --follow [file]
we are able to see the file renaming history, but this is not an answer to the question that I asked initialy.
Essentially, it is not possible to do so


text:
Q: The model of a free particle in a box as an approximation for the translational motion of a particle in a gas According to the book Introduction to Physical Gas Dynamics (starting from page 120), the translational motion of a particle in a gas in thermal equilibrium may be approximated by a free particle in a rigid box. By solving the Schrödinger for this system one may show that the resultant translational partition function is given by
$$Q_{\text{tr}}(T,V)=V\left(\frac{2\pi mk_BT}{h^2}\right)^{\frac{3}{2}}\text{ ,}$$
where $T$ is the temperature, $V$ is the volume of the box, $m$ is the mass of the particle, $k_B$ is the Boltzmann's constant and $h$ is the Planck's constant.
My question is how should this rigid box be interpreted? Is it a box with the dimensions of the mean free path of the particle, such that it represents the space whose boundary the particle can't cross due to collisions with other particles?


text:
Q: Nothing happens when running my code [BigInteger] So I have a class that computes two prime numbers and then checks if they're prime
import java.util.*;
import java.math.*;

public class GeneratePrime{

  public static BigInteger calculatePPrime() {
    BigInteger pRandom;
    while (true) {
      pRandom = new BigInteger(512, new Random());
      pRandom = pRandom.setBit(0);
      if(isPrime(pRandom)){
        System.out.println("Got Random Prime P: "+pRandom);
        break;
      }
    }
    return pRandom;
  }

  public static BigInteger calculateQPrime() {
    BigInteger qRandom;
    while(true){
      qRandom = new BigInteger(512, new Random());
      if(isPrime(qRandom)){
        System.out.println("Got Random Prime Q: "+qRandom);
        break;
      }
    }
    return qRandom;
  }

  public static boolean isPrime(BigInteger number) {
    if (!number.isProbablePrime(5))
        return false;

    BigInteger two = new BigInteger("2");
    if (!two.equals(number) && BigInteger.ZERO.equals(number.mod(two)))
        return false;

    for (BigInteger i = new BigInteger("3"); i.multiply(i).compareTo(number) < 1; i = i.add(two)) {
        if (BigInteger.ZERO.equals(number.mod(i)))
            return false;
    }
    return true;
  }
}

This is more or less a conglomerate of things I have found on the internet. This class was originally not using any BigIntegers, but then I found out I am required to use it for my assignment, so I had to scratch everything and do this.
Anyway. I can't use any built in functions to calculate primes (idk if there even are any). My issue here is that when I run this code in:
import java.util.*;
import java.math.*;

public class RSA{
    public static void main(String[] args) {
        BigInteger p, q;
        GeneratePrime gp = new GeneratePrime();
        p = gp.calculatePPrime();
        q = gp.calculateQPrime();
    }
}

Both classes compile fine, but then when I run the RSA class, nothing happens. No errors no nothing. My terminal is just blank. Does anyone know why? Or can anyone see if this code works on their machine? I know I've probably missed something dumb here. Thanks

A: You want to get random primes? Then make that clear in your code:
public BigInteger randomPrime(int bits, Random random) {
  return new BigInteger(bits, random).nextProbablePrime();
  // or
  // return BigInteger.probablePrime(bits, random);
}

Use the methods at your disposal, in this case: nextProbablePrime(). This method is so much more efficient than the set of methods you wrote. This will significantly boost your application.
Your RSA class can then become:
import java.util.*;
import java.math.*;

public class RSA{
    public static void main(String[] args) {
        BigInteger p, q;
        GeneratePrime gp = new GeneratePrime();
        Random random = new Random();
        int bits = 512;
        p = gp.randomPrime(bits, random);
        q = gp.randomPrime(bits, random);
    }
}

A: If you are willing to use the 512 bits number and you want to randomly get it and hope it will be a prime. You will find no success with your kind of solution. This is just too large value to be handled with too many possibilities. Even if you use the BigInteger constructor with certainty in. Like so :
new BigInteger(int bitLength, int certainty, Random random);

Where the java doc says:

certainty - a measure of the uncertainty that the caller is willing to tolerate. The probability that the new BigInteger represents a prime number will exceed (1 - 1/(2certainty)).

The larger you make certainty, the smaller is the probablility that the number is not prime.
Still will not help you. You can consider on some point of taking just the next prime number if the randomed one is not a prime as @Olivier Grégoire suggested or just reduce the number of bits.

A: The value for maximum bitLength of the new BigInteger is very large. If you reduce it to a smaller number it will work. I'm referring to the value 512 in the code below. Try a small number like 12.
pRandom = new BigInteger(512, new Random());


text:
Q: Web API AuthorizeAttribute does not return custom response How can I make IsAuthorized return my custom object while function returns false?
In my WebAPI project I have a class like;
public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
        {

            StandardWebAPIResponse invalidUserResponse = new StandardWebAPIResponse()
                    {
                        code = (int) Constants.ErrorCodes.InvalidCredentials,
                        data = "InvalidCredentials.",
                        StatusCode = HttpStatusCode.Unauthorized
                    };
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
                        invalidUserResponse);
                    // if I set this to true I am getting 401 with my custom object
                    // otherwise it gives me default error message
                    // {"Message":"Authorization has been denied for this request."}
                    return false;
        }
    }

For some reason when I return false from IsAuthorized function, it does not return my custom invalidUserResponse object. But if I return true it returns it.
How can I resolve this issue?

A: I know this question has been answered but I feel like it is slightly wrong. I don't think that a message for unauthorized request should be handled by OnAuthorization but should be handled by HandleUnauthorizedRequest. I'm not sure if it will cause any major problems putting it in OnAuthorization, but presumably the reason you were getting the message when true and not false is because the base class writes over your response in HandleUnauthorizedRequest.
It is a subtle thing but the OnAuthorization directs to the HandleUnauthorizedRequest for a reason. It is mainly a separation of responsibilities thing, but if you ever want to do more than just sending an error message, like log bad request your OnAuthorization method will probably get crowded. You should used the methods given to you for clarity sake if nothing else.

A: Yes I agree. You would need to implement custom filter derived from AuthorizeAttribute.
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
    base.HandleUnauthorizedRequest(actionContext);
    actionContext.Response = new HttpResponseMessage
    {
        StatusCode = HttpStatusCode.Unauthorized,
        Content = new ObjectContent(typeof(ErrorMessage),
        new ErrorMessage()
        {
            StatusCode = (int)HttpStatusCode.Unauthorized,
            Message = Constants.UnauthorisedErrorMessage,
            ErrorCode = Constants.UnauthorisedErrorCode
        }, new JsonMediaTypeFormatter())
    };
}

A: You should override the OnAuthorization method, that use the IsAuthorized and flushs the response, or force a flush at your method. Makes more sense fill the response where the filter manipulates It.


text:
Q: eigenvalues of $p(A)$ This question is related to the following question:
Do $A$ and $p(A)$ have the same eigenvectors?
Suppose again that $p(x) = a_nx^n+...+a_1x+a_0$ is a polynomial, and that $\sigma(A)$ denotes the set of eigenvalues (spectrum) of matrix $A$.  It is easy to show that if $\lambda \in \sigma(A)$, then $p(\lambda)$ is necessarily an eigenvalue of $p(A)$.  But it is not very clear to me if $\{p(\lambda): \lambda \in \sigma(A) \}$ constitutes the entire spectrum of $p(A)$?  Or can $p(A)$ have eigenvalues not belonging to $\{p(\lambda): \lambda \in \sigma(A) \}$?  How do we prove or refute this?
Thanks a lot!

A: Over an algebraically closed field it's the entire spectrum, and you can see that  by considering the Jordan normal form.
In general, it might not be. For example, $A = \begin{pmatrix} 0 & -1 \\ 1 & 0 \end{pmatrix}$ has no real eigenvalues but $A^2$ has eigenvalues.

A: I'm assuming that we're considering matrices over a algebraically closed field (such as $\Bbb C$).
Suppose that $p(A)$ has eigenvalue $\mu$. Then we note that if we set $q(x)=p(x)-\mu$, then
$$
q(x)= a(x-\lambda_1)\cdots (x-\lambda_n)
$$
for some numbers $a$ and $\lambda_k$. The $\lambda_k$ are precisely the values of $x$ for which $p(x)=\mu$.
Now, since $\det(q(A))=0$, we can conclude that $A-\lambda_k I$ is singular for some $k$. For this $k$, $\lambda_k$ is an eigenvalue of $A$.

A: This is true if the characteristic polynomial of $A$ splits into linear factors, i.e., if the spectrum of $A$ contains the all eigenvalues that exist in an algebraic closure of the field (and so in particular if we are working over an algebraically closed field like the complex numbers). To see this it suffices to extend the result you cited to generalised eigenspaces:

For every eigenvalue $\lambda$ of a linear operator$~\phi$ and for any polynomial$~P$, the generalised eigenspace of$~\phi$ for$~\lambda$ is contained in the generalised eigenspace of$~P[\phi]$ for its eigenvalue$~P[\lambda]$.

The proof is simple: that generalised eigenspace of$~\phi$ consists by definition of the vectors in the kernel of $\def\id{\,\mathrm{id}}(\phi-\lambda\id)^k$ for some $k\in\Bbb N$, while the mentioned generalised eigenspace of$~P[\phi]$ consists of the vectors in the kernel of $(P[\phi]-P[\lambda]\id)^k$ for some $k\in\Bbb N$. But since $\lambda$ is clearly a root of $P-P[\lambda]$, the latter polynomial is divisible by $X-\lambda$, say $P-P[\lambda]=(X-\lambda)Q$, and then $(P-P[\lambda])^k=(X-\lambda)^kQ^k$ is a multiple of $(X-\lambda)^k$, and any vector annihilated by $(X-\lambda)^k[\phi]=(\phi-\lambda\id)^k$ is also annihilated by $(P-P[\lambda])^k[\phi]=(P[\phi]-P[\lambda]\id)^k$, which is the desired inclusion.
Now the result of the question follows as before. By hypothesis, the (direct) sum of the generalised eigenspaces for all eigenvalues$~\lambda$ of$~A$ fills the whole space. But each one is contained in the generalised eigenspace for the corresponding eigenvalue$~P[\lambda]$ of$~P[A]$, so the sum of those eigenspaces for all occurring values$~P[\lambda]$ also fills the whole space, and those values constitute the entire spectrum of$~P[A]$.


text:
Q: Laptop fan always says it's running at 8 RPM I have a Lenovo Legion Y520 with these specs:
zjeffer@ArchLinux
-----------------
OS: Arch Linux x86_64
Host: 80WK Lenovo Y520-15IKBN
Kernel: 5.1.7-arch1-1-ARCH
Uptime: 42 mins
Packages: 1659 (pacman)
Shell: zsh 5.7.1
Resolution: 1920x1080, 1920x1080
WM: bspwm
Theme: OSX-Arc-Plus [GTK2/3]
Icons: Papirus-Light [GTK2/3]
Terminal: gnome-terminal
CPU: Intel i7-7700HQ (8) @ 3.800GHz
GPU: NVIDIA GeForce GTX 1050 Mobile
GPU: Intel HD Graphics 630
Memory: 1369MiB / 7866MiB

I'm using thinkfan to try to control my cpu fan. Sadly, I can't see what my true fan speed is, as it always says 8 RPM.
This is my thinkfan.conf, if it matters:
######################################################################
# thinkfan 0.7 example config file
# ================================
#
# ATTENTION: There is only very basic sanity checking on the configuration.
# That means you can set your temperature limits as insane as you like. You
# can do anything stupid, e.g. turn off your fan when your CPU reaches 70°C.
#
# That's why this program is called THINKfan: You gotta think for yourself.
#
######################################################################
#
# IBM/Lenovo Thinkpads (thinkpad_acpi, /proc/acpi/ibm)
# ====================================================
#
# IMPORTANT:
#
# To keep your HD from overheating, you have to specify a correction value for
# the sensor that has the HD's temperature. You need to do this because
# thinkfan uses only the highest temperature it can find in the system, and
# that'll most likely never be your HD, as most HDs are already out of spec
# when they reach 55 °C.
# Correction values are applied from left to right in the same order as the
# temperatures are read from the file.
#
# For example:
# tp_thermal /proc/acpi/ibm/thermal (0, 0, 10)
# will add a fixed value of 10 °C the 3rd value read from that file. Check out
# http://www.thinkwiki.org/wiki/Thermal_Sensors to find out how much you may
# want to add to certain temperatures.

#  Syntax:
#  (LEVEL, LOW, HIGH)
#  LEVEL is the fan level to use (0-7 with thinkpad_acpi)
#  LOW is the temperature at which to step down to the previous level
#  HIGH is the temperature at which to step up to the next level
#  All numbers are integers.
#

# I use this on my T61p:
# tp_fan /proc/acpi/ibm/fan
# tp_thermal /proc/acpi/ibm/thermal (0, 10, 15, 2, 10, 5, 0, 3, 0, 3)

hwmon /sys/devices/platform/coretemp.0/hwmon/hwmon0/temp1_input
hwmon /sys/devices/platform/coretemp.0/hwmon/hwmon0/temp2_input
hwmon /sys/devices/platform/coretemp.0/hwmon/hwmon0/temp3_input
hwmon /sys/devices/platform/coretemp.0/hwmon/hwmon0/temp4_input
hwmon /sys/devices/platform/coretemp.0/hwmon/hwmon0/temp5_input
hwmon /sys/devices/virtual/thermal/thermal_zone1/temp

(0, 0, 51)
(1, 50, 52)
(2, 51, 55)
(3, 54, 58)
(4, 56, 63)
(5, 60, 70)
(6, 66, 79)
(7, 74, 92)
(127, 85, 32767)

Here's the output of dmesg | grep -i thinkpad:
[    0.000000] Command line: BOOT_IMAGE=/vmlinuz-linux root=UUID=661a855a-c479-4291-bcb2-95b148ce2020 rw quiet nowatchdog nvidia-drm.modeset=1 thinkpad_acpi fan_control=1
[    0.155975] Kernel command line: BOOT_IMAGE=/vmlinuz-linux root=UUID=661a855a-c479-4291-bcb2-95b148ce2020 rw quiet nowatchdog nvidia-drm.modeset=1 thinkpad_acpi fan_control=1
[    4.231093] thinkpad_acpi: ThinkPad ACPI Extras v0.26
[    4.231094] thinkpad_acpi: http://ibm-acpi.sf.net/
[    4.231094] thinkpad_acpi: ThinkPad BIOS 4KCN40WW, EC unknown
[    4.231094] thinkpad_acpi: Lenovo Lenovo Y520-15IKBN, model 80WK
[    4.231554] thinkpad_acpi: Standard ACPI backlight interface available, not loading native one
[    4.231620] thinkpad_acpi: Console audio control enabled, mode: monitor (read only)
[    4.232877] thinkpad_acpi: battery 1 registered (start 0, stop 0)
[    4.232879] battery: new extension: ThinkPad Battery Extension
[    4.232896] input: ThinkPad Extra Buttons as /devices/platform/thinkpad_acpi/input/input8

Here it says EC unknown, so I have no idea which EC I have and can't find anything on the internet about my model.
I checked this speed in s-tui, in /proc/acpi/ibm/fan and in sensors: it's always at 8 RPM, which is of course impossible if I can hear it blasting at full speed while playing games.
In windows 10 I found that speedfan doesn't find any fans. I also updated my BIOS version from 4KCN40WW to 4KCN45WW. No changes.

How can I see my true fan speed?

A: Partial answer:
From your dmesg, thinkpad_acpi gets loaded. I had a quick look at the kernel source code, and there don't seem to be any fan related messages it outputs.
However, some comments in the code say:

ThinkPad EC register 0x84 (LSB), 0x85 (MSB):
  Main fan tachometer reading (in RPM)
This register is present on all ThinkPads with a new-style EC, and
  it is known not to be present on the A21m/e, and T22, as there is
  something else in offset 0x84 according to the ACPI DSDT.  Other
  ThinkPads from this same time period (and earlier) probably lack the
  tachometer as well.
Unfortunately a lot of ThinkPads with new-style ECs but whose firmware
  was never fixed by IBM to report the EC firmware version string
  probably support the tachometer (like the early X models), so
  detecting it is quite hard.  We need more data to know for sure.
FIRMWARE BUG: always read 0x84 first, otherwise incorrect readings
  might result.
FIRMWARE BUG: may go stale while the EC is switching to full speed
  mode.
For firmware bugs, refer to:
  http://thinkwiki.org/wiki/Embedded_Controller_Firmware#Firmware_Issues

EC is the embedded controller of your laptop.
So there are three potential issues: On some thinkpads the tachometer isn't available at all, and on some thinkpads something else is in this location, and on some thinkpads the firmware is wrong.
Which means you have to match up your Lenovo Legion Y520 with whatever version nomeclature you are using, and look for firmware bugs.
In doubt I'd contact the maintainers of this module either via the kernel bugtracker and see if they have any ideas about your particular model.

A: I contacted Lenovo support and they said the current (and latest) version of my laptop's BIOS doesn't support fan control.


text:
Q: Set dynamic width and height of item in recyclerview I am working on a android project in which I am using Recyclerview withgridlayoutmanger and Items are Images. I want to display four items in single row so I have set spancount to 4 and a gap of 2dp is set between each item with Itemdecoration.
ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(getContext(),R.dimen.offset);
fRecyclerView.addItemDecoration(itemDecoration);

GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(),4);

Each Item height and width are currently 90dp.
Item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="90dp"
android:layout_height="90dp"
android:id="@+id/imagevideo_layout"
>
<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/image_video_pic"
    android:scaleType="centerCrop"
    android:adjustViewBounds="true"
    />
 </RelativeLayout>

Problem is as I am fixing the height and width of item, in some devices due to the screen size differences there is more gap between each item.And in some devices items are overlapping because of small screen sizes.I need only 2dp and only 4 items in single row for all the screen sizes. Is there any way to do this? Is it possible to dynamically set the relativelayouts height and width depending on the screen size? I have searched in SO, questions are on setting the spancount dynamically by fixing the height and width of each item, but I need reverse of it.


text: Q: Authorising external Domains to embed my content I am looking for code to insert into a php file i.e. webfile.php (the content of this file is just basic html content), that will authorise/give selected domains the ability to embed this file. I was considering the external domains call the page via <?php echo file_get_contents('webaddress/webfile.php'); ?>


text:
Q: Using PHP to Match a Javascript Timestamp Alright when I do the code:
<script type = "text/javascript" >
document.write((new Date).getTime());
</script>

You get the Unix timestamp in miliseconds. I need something that will match this in PHP. I need a variable to be set to that, NOT necessarily printed. The variable needs to be a string OR number without any formatting (decimals, commas, etc).
The numbers don't have to match exactly, but have to be close. I tried doing time()*1000 but it turns it into scientific notation and I couldn't format it out without messing up the string.
Thanks so much for any help

A: What you are looking for is millisecond time in PHP. To accomplish this you need to use a combination of the microtime function and some multiplication.
microtime when passed true as its first parameter will return the current time as the number of seconds since the Unix epoch to the nearest microsecond.
To convert the value into an integer value of the number of milliseconds since the Unix epoch you must multiply this value by 1000 and cast to an integer.
So:
$milliseconds = (int)(microtime(true) * 1000);

A: If you don't need (millisecond) presision, then just divide & Math.floor the javascript's function. So:
time();

and
Math.floor((new Date).getTime()/1000)

should return the same value at the same time.

A: The javascript
getTime() ;

method returns the number of milliseconds since midnight of January 1, 1970 and the specified date.
A php equivalent is
time() * 1000; // not microtime() as I wrongly said earlier.

However they wont match as php does not support millisecond precision it seems.


text:
Q: Why does absolute path depend on where we call the script? I have the following structure in my computer:
.
├── README.md
├── Rakefile
├── lib
│   ├── box_office.rb
│   └── movies.csv
└── spec
    └── box_office_spec.rb

When I run box.office.rb, I want to load the movies.csv file. If I hard-code the path, it works:
current_directory = Dir.pwd
file_path = "#{current_directory}/lib/movies.csv"
puts file_path

How can I do this without hard-coding the path (this lib/ directory)? I need the current directory of the file, where I do ruby: XXXX.rb.
I've tried:
current_directory = File.expand_path(File.dirname(__dir__))
puts current_directory

current_directory = Dir.pwd

path = Pathname.new(__FILE__)
p path.realpath


text:
Q: Calculate resistance for high amperage LEDs for control with Arduino I'm trying to control my LED strip with my Arduino, so I decided to buy a FET. Now I want to learn why and what kind of resistance should be put between the gate and the Arduino.
I have a long (1560 cm) LED strip connected (in parallel). The strip consumes 1.2A per meter, so it needs 18.7A.
I bought a N-Channel Mosfet (IRF540N, which can handle up to 30A), but the problem is that I'm new on resistances.
I know the formula of Ohm's Law, but my problem is that I don't understand it well.
What resistance should I put?

A: You must connect the negative side of the LED strip to the Drain (D), the ground (the negative side of the power supply) to the Source (S) (without any resistor)
and the Arduino output to the Gate (G). Apply at least 4V to the Gate but no more than 18V. So your 5V from Arduino is fine. On the gate you need two resistors: Between the Arduino output and the Gate, put a resistor of 140 Ohms (or between 100 and 1K if you don't have 140 Ohms exactly). Between the Gate and the ground, put a resistor between 200K and 800K (any value in between is ok). HTH.

A:

simulate this circuit – Schematic created using CircuitLab
Use low value for R4 like 100 Ohmes. R1 is used as pull down resistor typically use around 100k for consistency of transistor when unknown states of arduino and preventing switching the transistor.Using higher value help reduce the unwanted current draw through R1. FETs are based on voltage not on current. They just draw number of \$\mu A\$ while continuously active. Actually it will run without problem even if there is no R4. But it may help for safety in case of higher current is drawn.But higher R4 reduce the sensitivity of gate. See the data sheet whether voltage between Gate and Source is enough to flow current through Drain and Source.See charastric of MOSFETs.


text:
Q: Align div to bottom without removing it from the flow I need to align a div to the bottom of the parent div. You might just tell me to use position: absolute; and bottom: 0px;, but I cannot remove the div from the flow.
My HTML markup looks like this:

        Lorem ipsum dolor sit amet

The parent div has a dynamic height. Sometimes, it is just as high as necessary to show all of its content (height: auto;), but sometimes, it has a fixed height, which is smaller than the child's height. In that case, I want the child to reach outside the parent at the top edge. The child always has height: auto; to fit its content, which I also don't know at design-time.

What I have tried is using position: absolute; and bottom: 0px; on the child div, but this removes the child from the flow; thus, the parent div will fail to show its content while it has height: auto; active. I also tried using display: table-cell; and vertical-align: bottom; on the parent, but this seems to make it impossible to give it a height smaller than the content.
If nothing helps, I can still try a JS solution, but I'm sure this has to possible using plain CSS somehow, even if I need to modify my HTML and insert a wrapper div or something.

A: How's this?
.parent {
    margin-top:-16px;
    background-color: gold;
    height: 88px;
    position:relative;
    -webkit-transform:translateY(-100%);
    transform:translateY(-100%);
    transition:1s all;
    z-index:-1;
}
.down {
    -webkit-transform:translateY(0);
    transform:translateY(0);
}

$(".header").click(function () {
    $(".parent").toggleClass('down');
});

Demo
You could hide the overflow above the header by using a container as well Demo
As Linek mention, browsers that don't support transforms would just show the content. In order to reach them without using a set height or taking them out of the flow, you have to over estimate the height of the element and use a negative margin-top. This demo should fix the problem in IE8


text:
Q: Azure components for photo / video content management I am evaluating Windows Azure for my photo / video management software which will have functionality of
1) uploading the photos / videos, Tagging, album creation etc
2) Live streaming of content from server
3) Download of content from server.
CDN and AppFabric Cache will definitely be helpful here. Can anyone please let me know if there are some built in components / off the shelf components / specific design patterns of Azure which can facilitate the fast development e.g. if there is something else which can help in fast streaming of content, it will definitely be helpful.
Thanks.

A: As you've noted, the CDN and caching will definitelly help you. However I would mostly look at the CDN. I would use caching for relatively small chunks of data (such as any data-base driven lists of details, i.e. list of cities, or countries), or a slowly-changing data. I would not put large media content in AppFabric Cache.
As for leveraging blobs/CDN for streaming, you may want to check this example.
UPDATE
Well, will you have some photo/video manipulation on server side? Or what people (users or admins) upload, that is served to the users?
If not, than there is nothing additional.
If you, however will have some image,video processing on the server side I suggest that you split your app into a WebRole (for users upload/download/stream) and a Worker Role (for processing). You can check out this lab to get understanding of how to decouple web from worker role and how to submit work items to the worker.
The reason to have separate worker role for processing is to be able to independenatly scale either web or worker on demand.


text:
Q: Displaying smile emoticon inside text view How can I display smile emoticon inside TextView? Are there any special Android libraries for this purpose or I must embed this emoticon by Unicode characters in format \uXXXX?

A: In my unicode I replaced 'U+' by '0x'
Example: replace 'U+1F60A' by '0x1F60A'
This way I got an 'int' like
int unicode = 0x1F60A;

Which can be used with
public String getEmojiByUnicode(int unicode){ return new String(Character.toChars(unicode)); }

So Textview displays  without Drawable
Try it with http://apps.timwhitlock.info/emoji/tables/unicode


text:
Q: Popup box if a negative number based from formula I am trying to figure out a script that will popup a box if a number in column F goes negative. I think I may be running into an issue due to the negative number generating from a formula as opposed to someone manually typing it in. Here is the script I have been working with:
function onEdit(event){
  var sheet = event.source.getActiveSheet().getName()
  var editedCell = event.range.getSheet().getActiveCell();
  if(sheet=="Numbers"){
     if(editedCell.getColumn() == 6 && event.value==-0.1){
        Browser.msgBox('It looks like there is a negative number in Column F.');
  }}}

I think it may have something to do with the 'editedcell' function but I am not 100%. Does anyone know of a better script that will popup a box even if a formula is generating a negative number (the value in column F will be a formula that may generate a negative)?
At this point, nothing happens with this code unless I manually type "-1" or some other negative in Column F.

A: Answer:
The event object returns the range of the cells you edited, not the ones edited by a script or formulae. As well as this, there are a few things you can do to fix or optimise your code.
Code Fixes:
Firstly, you can change your conditional to optimise the script and only make calls when you need them - this I have done with a slightly different conditional order.
As well as this, rather than event.range.getSheet().getActiveCell() you need to specify the values of column F explicitly, and use the getDisplayValues() function as this will also pick up the values if the cell contains a formula:
function onEdit(event) {
  var sheet = event.source.getActiveSheet();
  if (sheet.getName() != "Numbers") {
    return;
  }

  var values = sheet.getRange('F:F').getDisplayValues()

  for (var i = 0; i < values.length; i++) {
    if (values[i] < 0) {
      Browser.msgBox('It looks like there is a negative number in Column F.');
      return;
    }
  }
}

References:

*

*Google Apps Script - Event Objects

*Google Apps Script - Best Practices


text:
Q: How to create kotlin login with sqlite? how can I create a login in koltin using sqlite.
User register
 bt_204.setOnClickListener {
            val admin = AdminSQliteOpenHelper(this, "administracion",null,1)
            val bd = admin.writableDatabase
            val registro = ContentValues()
            registro.put("nombre_usuario", et_nombre_201.text.toString())
            registro.put("clave1", et_pasword_204.text.toString())
            registro.put("clave2",et_paword_203.text.toString() )
            bd.insert("usuario", null , registro)
            bd.close()
            et_nombre_201.setText("")
            et_paword_203.setText("")
            et_pasword_204.setText("")
            Toast.makeText(this,"Usuarios registrado correctamente", Toast.LENGTH_SHORT).show()
            val intent = Intent (this,MainActivity::class.java)
            startActivity(intent)
        }

main activity
try this but the app is destroyed(I am a beginner)
   bt_ingresar_04.setOnClickListener {
            val admin = AdminSQliteOpenHelper(this, "administracion", null, 1)
            val bd = admin.writableDatabase
            val fila = bd.rawQuery(
                "select nombre_usuario,clave1 from usuario where nombre_usuario=${et_02.text} &&    ${etp_03.text}"
                null
            )
            if (fila.moveToFirst()) {
                val intent = Intent(this, MainActivity_03::class.java)
                startActivity(intent)
            } else {
                Toast.makeText(this, "Usuario no registrado", Toast.LENGTH_SHORT).show()
            }

        }

A: && is the logical operator for Java but not for sql. You must use AND.
Also in the where clause of the query you must specify all the needed column names, but you don't. You specify only the column nombre_usuario.
Also the parameters et_02.text and etp_03.text should be properly quoted, so the final result is something like:
where column1 = 'value1' and column2 = 'value2'

But the proper way of doing this is by using ? placholders and pass the parameters in the 2nd argument of rawQuery() as an array of strings.
So change to this:
val fila = bd.rawQuery(
    "select nombre_usuario, clave1 from usuario where nombre_usuario = ? and column_password = ?",
    arrayOf(et_02.text, etp_03.text)
)

Replace column_password with the name of the column where you store the password.
Also, in bt_204.setOnClickListener, in this line:
registro.put("clave2",et_paword_203.text.toString() )

maybe there is a typo for et_paword_203.


text:
Q: Common mode feedback for current mirrors I was reading the chapter about Op - Amp design in Microelectronic Circuits by Sedra Smith, and I have some questions about the so called "common mode feedback" (CMFB) which is used to control some current mirrors.
Let's consider this scheme:

The book says:

Relying solely on matching will not be sufficient to ensure that the
  currents supplied by Q9 and Q10 are exactly equal to the currents supplied by Q7 and Q8. Any
  small mismatch \$\Delta\$I between the two sets of currents will be multiplied by the large output
  resistance between each of the collector nodes and ground, and thus there will be large changes
  in the voltages vO1 and vO2. These changes in turn can cause one set of the current sources
  (i.e., Q7
  −Q8 or Q9
  −Q10) to saturate. We therefore need a circuit that detects the change in the
  dc or common-mode component VCM of vO1 and vO2,
  VCM
  = 1
  2
  (vO1
  +vO2)
  and adjusts the bias voltage on the bases of Q7 and Q8, VB, to restore current equality. This
  negative-feedback loop should be insensitive to the differential signal components of vO1 and
  vO2; otherwise it would reduce the differential gain. Thus the feedback loop should provide
  common-mode feedback (CMF).

I have the following questions:
1) How is it possible that for instance current of Q9 is different from that of Q7? Their channels are in series (since the load is supposed to be of infinite impedance) and so, by kirchoff current law, all the current through Q9 should go on Q7, I think...
2) Does the book refer to DC or signal currents?
3) Why do we decide that the CMFB has to read the common mode voltage? Suppose there is a mismatch between current of Q9 and current of Q7: there would be a spurious value inside vO1. Which is the link between this spurious voltage, and the common mode voltage between the outputs in 1 and 2?

A: 1) The currents of Q7/Q8 and Q9/Q10 are set by the bias voltages. It is very difficult to get this bias voltage exactly right without a feedback network, so the theoretical collector currents would differ. This discrepancy in current results in wild shifts in output voltage as a result of the Early effect (i.e. R_out in the small-signal model of each BJT).
2) The DC bias itself is susceptible.
3) This portion of the question isn't that clear. We want to regulate the common-mode voltage because it is part of the desired specification of a differential amplifier: as the outputs swing up and down with a differential input, they swing around a well-regulated constant common-mode voltage. If we regulated Q7 and Q8 using only the voltage at vO1, we wouldn't get a fully differential amplifier; instead we would get something along the lines of a differential-to-single-ended amplifier.

A:
How is it possible that for instance current of Q9 is different from that of Q7? Their channels are in series (since the load is supposed to be of infinite impedance) and so, by kirchoff current law, all the current through Q9 should go on Q7, I think...

Assume that you have identical transistors including pnp and npn. Suppose you set the bias \$V_B\$ such that \$V_{BE_{pnp}} \ne V_{BE_{npn}}\$. Assuming the system starts with both the transistors in active region, the two transistors are going to have different currents. Let's say npn has smaller \$V_{BE}\$, thus at node \$v_{O1}\$ less current is being sunk to ground then what is being sourced from supply. The potential at this node will rise as a result. And in steady state or DC the pnp will go into saturation. In DC, the current through the pnp is same as npn but you will loose all the gain as pnp is saturated. This needs to be avoided via CMFB.

Does the book refer to DC or signal currents?

As explained, DC Currents.

This portion of the question isn't that clear. We want to regulate the common-mode voltage because it is part of the desired specification of a differential amplifier: as the outputs swing up and down with a differential input, they swing around a well-regulated constant common-mode voltage. If we regulated Q7 and Q8 using only the voltage at vO1, we wouldn't get a fully differential amplifier; instead we would get something along the lines of a differential-to-single-ended amplifier.

CMFB will regulate the DC level of both \$v_{O1}\$ and \$v_{O2}\$. In fact, common mode is always defined for a pair of signals. Thus CMFB would regulate \$v_{CM} = \frac{v_{O1}+v_{O2}}{2}\$.


text:
Q: Unable to load PHP file into a inner HTML Div created dynamically with javascript I am able to load a .php file into a div simply by using <?php include("file.php") ?>
The file can have php, javascript, html and plain text in it and it still works great.
I am NOT able to load the file into a Div I created dynamically with javascript if the file has script tags in it.
NOTE: I am updating the code as I make progress
index.php
The first Div works great and loads the test.php file with no issues.

        This is the phpDiv

        <?php include("test.php"); ?>

The Second Div created dynamically will not load the file if it has script tags in it

test.php  <-the file i'm trying to load
<?php echo "php works
"; ?>

 html works

and extra spaces and plain text work fine as well

A: I would say it doesn't work because you use single quotes into your single quotes statement setting your innerHTML.
<?php echo "php works
"; ?>

 html works

Edit:
You can try to strip newlines automatically like so:
// Create a stream
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n"
  )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('test.php', false, $context);
$file = str_replace( "\r\n", "", $file );

put $file into your innerHTML

A: Try to see this code . I was successful with it . Create your index.php code and put the Jquery file in that directory.Download it from here http://jquery.com/download/.

<meta charset="utf-8">
<title>load demo</title>

Successful Response (should be blank):

Error Response:


text:
Q: How do I change the line spacing in WinEdts editor (options interface...)? I managed to change the font size in Options Interface. Now, a want to enlarge the line spacing. How I do this?

A: Options menu > Preferences > Font tab, change the value for Extra Line Spacing (0 by default):


text:
Q: insert statement one column from another table rest of the columns is values would like to know how to write SQL query, when you want to use the insert statment and fill it with 2 values and then a value from a external table?
Something like this.
INSERT INTO [PPLAT_KPI].[dbo].[KPI_Values]
       (TS,
       Value,
       ID)
 VALUES
       ('2010-02-04'
       ,'200',
           SELECT KPI_Parameter.ID
         FROM [PPLAT_KPI].[dbo].[KPI_Parameter]
            where KPI_Parameter.Site = 'XXX' and KPI_Parameter.Plant = 'vv';)

A: Please try:
INSERT INTO [PPLAT_KPI].[dbo].[KPI_Values]
       (TS,
       Value,
       ID)
SELECT
      '2010-02-04',
      '200',
      KPI_Parameter.ID
FROM [PPLAT_KPI].[dbo].[KPI_Parameter]
where KPI_Parameter.Site = 'XXX' and KPI_Parameter.Plant = 'vv';

A: Use INSERT INTO...SELECT like this: http://www.w3schools.com/sql/sql_insert_into_select.asp


text:
Q: static variables local to a function In Linux, "static" variables are present in the BSS segment (in a code that is not running) and "local" variables are present in the "stack".
This means that static variables local to a function are present in the BSS area. How is the book-keeping done to ensure that the scope is within the function itself?

A: Where a variable is stored has nothing to do with scope. It's usually the compiler itself that restricts scope (access to the variable). When you have a statement like:
static int xyzzy;

within a function, xyzzy will not be allowed to be accessed by code outside that function, regardless of the fact that it has static storage duration.
Any attempt to do so will be a compile-time error, not a run-time check.
In fact, you can affect the local static variable but with something like a buffer overflow (running into the storage area where it exists), not via its name (which the compiler will disallow).


text:
Q: Binding value to ComboBox WPF So, I need to make a WPF app that'll take values from the list and store them to DataGrid. I have 3 fields I want to show in the grid: Username, FullName and Role. Now, the Role can have 2 values: shopper and supplier. How do I make that part of the DataGridTemplate? In addition, how do I select the right one on load for every user? The empty line is where the missing code should be. Here's the code I'm working on:
<Grid>
    <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding UserList}" Name="dgUsers" HorizontalAlignment="Left" Height="450" Width="400">
        <DataGrid.Columns>
            <DataGridTemplateColumn Header="Username" Width="100" IsReadOnly="True">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Username}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn Header="Full Name" Width="200" IsReadOnly="True">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding FullName}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn Header="Role" Width="100">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>

                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

EDIT:
As a DataTemplate I did this:
<DataGridTemplateColumn.CellTemplate>
     <DataTemplate>
            <ComboBox ItemsSource="{Binding valueList}" SelectedIndex="{Binding Role}"/>
     </DataTemplate>
</DataGridTemplateColumn.CellTemplate>

As a Role, inside of the constructor, I did this:
public class UserToChange
{
    public string Username { get; set; }
    public string FullName { get; set; }
    public int Role { get; set; }
    public List<string> valueList { get; set; }

    public UserToChange()
    {

    }

    public UserToChange(UserVM row)
    {
        Username = row.UserName;
        FullName = row.FirstName + " " + row.LastName;
        Role = row.RoleId == 102 ? 0 : 1;
        valueList = new List<string>
        {
            "Supplier",
            "Shopper"
        };
    }
}

And it worked. Now I need to program the logic to update Database, but I can handle that. Thanks everyone!

A: You can bind the Collection in two ways.
1) Create a ComboBox inside DataTemplate
         <DataGridTemplateColumn Header="Role" Width="100">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <ComboBox ItemsSource="{Binding dataList}"  Width="100" DisplayMemberPath="{Binding DisplayProperty}" SelectedValuePath="{Binding PropertyId}" SelectedIndex="0" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

For ComboBox, Use SelectedIndex to set a default Item on Load.
2) Instead of DataGridTemplateColumn  use DataGridComboBoxColumn
<DataGridComboBoxColumn ItemsSource="{Binding dataList}" Width="100" Header="Role2" DisplayMemberPath="{Binding DisplayProperty}" SelectedValuePath="{Binding PropertyId}" SelectedItemBinding="{Binding DefaultValuePro, Mode=TwoWay}" />

For DataGridComboBoxColumn use SelectedItemBinding bind it with property to set a default value.

A: *

*First Fill the ListofRole collection with your respective values.

*Bind it with the combo-box inside DataGridTemplateColumn.

*Bind the SelectedValue property of combo-box, and there comes to magic, bind SelectedValue to that variable which contains a Role value in a dataList.
Note: ListofRole collection should not be an of custom type, then we need to add some more parameters in combo box, it should be a normal string type.
         <DataGridTemplateColumn Header="Role" Width="0.45*">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ComboBox ItemsSource="{Binding ListOfRole}"
                                  SelectedValue="{Binding Role,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>


text:
Q: Send Tone from arduino through mono aux cord to speakers via 3.5mm jack Hello I am using Arduino C to program my microcontroller to output frequencies via tone(); to a piezo buzzer. Currently the frequency(s) is/are chosen with a potentiometer. I would like to ditch the piezo buzzer and instead output the frequency to a 3.5mm headphone jack, where either headphones can be plugged in or a mono auxiliary cord, with a pair of desktop speakers on the other end. What is the best and most efficient way to do this as far as coding/translating the frequency to be output over the 3.5mm jack?
update :
so for my 3.5mm audio jack, i have the 10k ohm resistor inline with the ground connection and then one pin running to positive lead and the other pin running to digital pin 4 on my arduino. I have tried testing multiple frequencies on a pair of desktop speakers with a subwoofer, and comparing them to an actual tone generator app i have on my phone. my prototype seems to emit more of a noisy/fuzzy sound compared to the tone generator app which seems to be a lot more crisp/clean. Also frequencies under 100 Hz arent playing what they should sound like, however the app outputs frequencies under 100 Hz just fine. My three questions are:
1. How can I get to output to be as close as possible to the actual frequency?
2. How can i get the output to be crisp and clean, not noisy and fuzzy?
3. Is there something i'm missing/any ideas how to make the frequencies go below 100 Hz?
i know theres 5 pins on the 3.5mm audio jack but im only using 3, could this be an issue?
please feel free to ask any questions, i can also upload pictures as needed.

A: It's exactly the same thing- just send the square wave through the audio jack. Assuming your speakers have their own amplifier (which most desktop speakers do), you should just put a 10k resistor on the output line. Just hook up the pin and ground to the jack and you should be fine.


text:
Q: I'm bugged in a map and I'm going to lose my best soldier, what can I do to get him out? I just equiped my best soldier (A just now max ranked Sniper) with the skeleton Suite. When I was going to bring him in position with the hook he just got placed out of the map and cannot move anywhere. I thought "Hm, that's ok then I have to finish the mission with out his force" After 2 deaths in my team I got pissed and checked for a savegame because with the snipers firepower things would have gone different. But the last save game Is 6 hours ago.
Well I had just like 1 turn to finish the objective. I did so and the next objective was like "X turns until airstrike! any one who is not in the pick up area until then will be left behind and will die!"
And my sniper is still unable to move anywhere and I would bet just because her is light years away from the air strike wont stop the game mechanic from killing him.
What can I do? I don't want to lose the guy I put my best equip and all exp in to such kind of a bug.
Is there a way I can recover him from dying after the mission?
Or to move him in some other way into the area?
Since the game has cheated me in this situation cheating would be a option for me as well!

A: I have figured out that there is a developer console for the game. I was going to name a Sniper Ken Levine, which would activate a so-called superhero sniper, but I later read that this deactivates the Steam achievements, so I didn't try it and thus I can't confirm.
By activating the developer console, it became possible to press \ to enter various codes, one of which was TeleportAllToCursor. (There is a case-sensitive autocomplete feature built in.)
This command made the whole squad teleport to the cursor and I was able to save the sniper.


text:
Q: For what reasons would a site be excluded from a full crawl? This is what I've checked so far:

*

*The default page of the site is published

*In site admin it is set to 'allow this site to appear in search results'

*In site admin of the root site, it will search all web parts

*Everything builds and can be browsed as expected (no bugs/404's etc.)

Still no luck. Is there something else I'm missing? Or any similar scenarios you've came across?

A: What about your search crawl rules?
Does the full crawl log say that it's excluded or does the log say that it indexed it but it doesn't show up in search results?

A: If you have a lot of users in the site (usually over ~1800), your site will no longer be crawled. This count includes unique users in sharepoint groups or site permissions. Users in active directory security groups don't count towards the limit (the security group counts as 1).
If this were the case, you would likely be receiving a message like The parameter is incorrect in your crawl log.
A very good explanation of the issue here: SharePoint Indexing Limited by 64 kB ACL Limit

A: The most ubiquitous reason that Sharepoint Search/Crawling fails completely is the legendary Loopback Security Check

A: A few reasons that I'm thinking of

*

*the targeted site is not part of any content source

*the crawler account that is used has no access to the target site

*A specific robots.txt is available at the root of the web application preventing a proper crawl / indexing

*A too generic crawl rule is defined or wrongly positioned (cascading effect)

*an unconfigured binding / AAM is used to access the site.

The easiest way to understand what's going wrong, if the suggestions above do not help is to install Fiddler on the Crawl server and set the Search Service Application proxy to the one used by Fiddler. That way whenever you start a full / incremental crawl, you'll have a clear view of what's preventing / blocking the crawl.
Hope it helped !


text:
Q: My table in lua only print nil when I use "for" to fill it I would like to contruct a configuration file with the code :
  But, my code is  wrong, why ? the final line only print nil, nil, nil...
-- Define ten network interfaces
interfaces = {} -- Define an empty table
for n = 1, 10 do
interfaces[n] = {
device = "eth"..n,
address = "192.168.1."..n
}
end
for k, v in pairs(interfaces) do print(device,address) end

A: In the code below, the names device and address are resolved as global variables that are undefined. Hence the nils in the output.
for k, v in pairs(interfaces) do print(device,address) end

Try this instead:
for k, v in pairs(interfaces) do print(v.device,v.address) end

Since the order of pairs traversed by pairs is not defined, use ipairs if you need the list to be output in order.


text:
Q: Series representation of $({\bf I-A})^{-1}$? I have a problem of the form
$$\mathbf{x} = \mathbf{A}\mathbf{x} + \mathbf{b}$$
where $\mathbf{x}$ and $\mathbf{b}$ are vectors and $\mathbf{A}$ is an invertible matrix. I can solve this problem for $\mathbf{x}$
$$\mathbf{x} = (\mathbf{I}-\mathbf{A})^{-1}\mathbf{b}.$$
I'd like to try to interpret this solution by deriving a series representation for the entries of $(\mathbf{I}-\mathbf{A})^{-1}$. I think that this should be somewhat similar to solving a linear non-homogeneous ODE (e.g. page 19 here).
Some context if it is useful: The first equation comes from the market clearing conditions in an input-output model of an economy. The entries in $\mathbf{x}$ are the revenues of each firm in the economy while $\mathbf{b}$ is the vector of consumer demands (in "dollar" terms). The $\mathbf{A}$ matrix contains the elasticity/share parameters for the inputs of the firms. Finally, $(\mathbf{I}-\mathbf{A})^{-1}$ is known as the Leontief Inverse. There is a textbook explanation of this matrix that has to do with the amount of good i needed to produce an additional unit of good j (loosely put). My idea is to use the series representation to show this explicitly.


text:
Q: run two different python programs and sync they variables I need to run two different python programs in two different places (two droplets in Digital Ocean for example), I need to share some variables between them, and I don't really know the best way to accomplish that.
Any idea or advice will be appreciated. Thanks.

A: If the rate at which you update and use them permits and if there's no overlap, I'd store each variable in an high availability database and read them from there.


text:
Q: ElasticSearch 5.6 is there a way to modify ES search response? Let's say I have a search response like
        "hits": [
        {
            "_index": "customer",
            "_type": "doc",
            "_id": "5",
            "_score": 1,
            "_source": {
                "name": "TEST1",
                "surname": "Soanems1"
            }
        },

I want to be able to modify the data before the user gets the response. Let's say the "name" field has a value of "TEST1" and I want the data at rest to stay "TEST1" but I want the user to see a different value, for example, "TEST12345". Is there a way to do it?
Is there a way to create a custom plugin that does this transformation for me? (there are some not trivial transformations that I want to do to the response)


text:
Q: Embeding Movilizer Client In My Application I have created a Mobile application in Movilizer. I have three to four movelets in it. Now I want to embed the Movilizer client in my program and deploy it in Google play store so that anyone downloading from there would get the client along with it and can run my application without having to download the client separately.
What is the procedure for the same?

A: As per my understanding, Movilizer is a standalone app which contains many movelets.
If you wanna to create a separate container for your company, you can create the same by using Google cloud developer console platform.
For that you should create a signedAPK and should register in Google developer console.
Note: Initial payment = 25$


text:
Q: How does x+y = x for non-zero value of y in floating-point arithmetic? So, as the question asks, is we have only normalised floating-point values and normalised results, could you please explain how x + y = x?
I know it all relates to precision, but how can I explain that?

A: Suppose you have a floating-point system which keeps track of, say, two decimal digits. If $x=1.0 \times 10^0$ and $y=3.4 \times 10^{-10}$, then the exact value of $x+y$ is $1.00000000034$, which would be represented in your system by the closest floating-point number, which is... Well, what is it?


text: Q: Overleaf lost connection every several minutes I have two windows computers, both using the Microsoft Edge browser. When I'm typing on the Overleaf website, the connection gets lost every 2-5 minutes. What's worse, some unsynced sentences are gone when the connection resumes. I'm not sure whether this is a network problem since all other websites look good, including Twitter and Gmail. I wondered if this is about the framework of what Overleaf cloud service used. Could anyone give some tips about the issue here?


text:
Q: Passing control between two views in iphone
Possible Duplicate:
Passing model objects from one view controller to another in a navigation stack

I am trying to pass the control between two views in iphone. I have tried this and it works fine when you pass from the first view controller to the second but when i click the second, it blanks out. Why is that so? Any help is appreciated.. Thanks...
Viewcontroller.h
#import <UIKit/UIKit.h>
#import "ViewController2nd.h"

@interface ViewController : UIViewController <SecondViewControllerDelegate>
{
    IBOutlet UILabel *lbl;

}
-(IBAction)passdata:(id)sender;

@end

Viewcontroller.m
#import "ViewController.h"
#import "ViewController2nd.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void) changeLabel:(NSString*)str{
    lbl.text = @"Hello";
}

-(IBAction)passdata:(id)sender{
    ViewController2nd *second = [[ViewController2nd alloc] initWithNibName:nil bundle:nil];
    [self presentViewController:second animated:YES completion:^{ }];
}

@end

ViewController2nd.h
#import <UIKit/UIKit.h>

@protocol SecondViewControllerDelegate <NSObject>
@optional
-(void) changeLabel:(NSString*)str;
@end

@interface ViewController2nd : UIViewController{

    IBOutlet UIButton *bttn;

}

-(IBAction)bttnclicked;
-(IBAction)back:(id)sender;
@end

ViewController2nd.m
#import "ViewController2nd.h"
#import "ViewController.h"

@interface ViewController2nd ()

@end

@implementation ViewController2nd

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)bttnclicked{

}

-(IBAction)back:(id)sender{
    ViewController *first = [[ViewController alloc] initWithNibName:nil bundle:nil];
    [self presentmodalViewController:first animated:YES completion:^{ }];
}

@end

Am i missing something?

A: If your requirement is to go to the first view change the back: method like:
-(IBAction)back:(id)sender
 {
     [self dismissViewControllerAnimated:YES completion:NULL];
 }

Don't display the parentView as the childView of the chilkdViewController. It also makes memory issues and logical issues.
So if you want to go from the childView to parentView, dismiss the childView and never create the parent object and present it there.


text:
Q: Doubt regarding definition of converging sequence. I am currently studying about converging sequence in my Real Analysis class.
The definition of a converging sequence is

A sequence of real numbers converges to a real number a if, for
  every positive number $\epsilon$, there exists an $N \in \mathbb N$ such that for all $n ≥ N$, $|a_n - a| < \varepsilon$.

However instead of using $\varepsilon$ why can't we just define it as follows.

A sequence of real numbers converges to a real number if, $\forall\ n\ \in \mathbb N$ and $n > 2$, $|a_n-a_{n-1}| < |a_{n-1}-a_{n-2}|$.

Any help would be appreciated.

A: I think the other folks who've commented and answered have done a good job explaining why you can't use the explicit definition you've given, but I also think your basic intuition is in the right place. The definition you've given is the standard one, but there is also the idea of a Cauchy sequence in real analysis, which is what I think you are trying to aim at.
Specifically, if you check out Rudin's Principles of Mathematical Analysis (3rd Ed.), he proves that every sequence in $R^k$ converges if and only if it is Cauchy. See theorem 3.11 in that work.

A: No, we can't. For instance, if $a_n=\sum_{k=1}^n\frac1k$, then the condition that you stated holds, but $(a_n)_{n\in\mathbb N}$ diverges.
On the other hand, the sequence $0,1,0,0,0,0,\ldots$ converges, but your condition doesn't holds for it.

A: An equivalent def'n of $A=\lim_{n\to \infty}a_n$ is that whenever $r>0 ,$ the set $\{n\in \Bbb N: a_n\not \in (A-r,A+r)\}$ is finite. Verbally we can say this as:  Each  neighborhood of $A$ (no matter how small) contains $a_n$ for all but finitely many $n\in \Bbb N$.
This does not require $a_n$ to progress in any "orderly fashion" towards $A$ as $n$ increases. For example if $a_n=2^{-n}$ when $n$ is odd and $a_n=10^{-n}$ when $n$ is even then $a_n\to 0.$


text:
Q: Inequality with differences in sequence
Let $n$ be a positive integer, and $a_1,\ldots,a_n, b_1,\ldots,b_n$ be nonnegative real numbers such that $0 \le a_1+\dots+a_n\le 1$ and $0 \le b_1+\dots+b_n\le 1$. Let $c_i = a_i-b_i$ for each $i$. Prove or disprove that
$$4n\cdot\max(|c_1|,\dots,|c_n|) + 2n \ge 2 + (n+1)(|c_1|+\dots+|c_n|+|c_1+\dots+c_n|).$$

The inequality can be equality when $a_i = 1/n$ and $b_i = 0$ for all $i$ -- the left-hand side is $4+2n$ and the right-hand side is $2 + (n+1)\cdot 2 = 2n+4$. In order to prove the inequality, an attempt is to use $$|c_1+\dots+c_n| \le |c_1|+\dots+|c_n| \le n\cdot\max(|c_1|,\dots,|c_n|)$$
to write everything in terms of $|c_1|+\dots+|c_n|$.
This reduces the inequality to $|c_1|+\dots+|c_n| \le 1$, but it is not always true.


text:
Q: How to Open Drop down (combo items) of Combo Box on KeyDown Event? Scenario :
I am working on project where my client needs to open the drop down(combo items) of combo box on f1 key down, but i am achieving it my try multiple codes.
how can i open combo box items on any key event.
Here is my code
private void dgvItemLists_KeyDown(object sender, KeyEventArgs e)
        {

            try
            {
                if (e.KeyCode == Keys.Subtract)
                {
                    txtDiscount.Focus();
                }

                if (e.KeyCode == Keys.Add)
                {
                    mtxtQty.Focus();
                }

                if (e.KeyCode == Keys.F1)
                {
                   cmbAreaName.Focus();
                //  cmbAreaName.AllowDrop = true;
               //   cmbAreaName.Show();
                  cmbAreaName_Click(this, new System.EventArgs());
                  //cmbAreaName_DrawItem(this, new DrawItemEventArgs);

                 // cmbAreaName.SelectedIndexChanged=;
                }

}

required result image is given.

any suggestions or recommendations of code will be highly appreciated.

A: Try
if (e.KeyCode == Keys.F1)
{
    cmbAreaName.DroppedDown = true;
}

Maybe you should put this in a method so you can raise it on events you need.

A: Currently, you're just executing the code inside the Click event when you call cmbAreaName_Click.
If you want to show the dropdown, set the DroppedDown property to true:
cmbAreaName.DroppedDown = true;


text:
Q: How to display an external image or graph in my existing Angular 6 application? I am trying to build an application which displays an external graph hosted in a different server. I am providing the url in the script and trying to display it in my component. But nothing is getting displayed. Instead I am getting an error like this :-
app.component.ts:28 Cross-Origin Read Blocking (CORB) blocked cross-origin response .... with MIME type text/html.
I came across some other posts where ComponentFactoryResolver has been used to dynamically load a component but could not really implement that solution.
A working code snippet would be appreciated. Thanks.

A: In my opinion you can't display any image in your angular app.
Because back end server must be enabled cors.
But problem is that we can't enable cors in front end.
So this is impossible I think.

A: CORS (cross origin requests) on your server side must be enabled in order to be allowed doing this.


text:
Q: How to change Extensions' location for VS Code My default download location for the VS code extensions is the C disk but I want to save the extension downloads on the D disk and use it from there. How can I do that?
I tried to change its path through VS Code setting but I couldn't figure out that.

A: As mentioned in the VS Code docs, extensions are installed in a per user extensions folder. For Windows, it is %USERPROFILE%\.vscode\extensions.
You can change the location by launching VS Code with the --extensions-dir <dir> command-line option. Some other ways are discussed here.


text:
Q: how to show a tooltip on a disabled control? I'm displaying a list of buttons, some of which might be disabled. I need to show a tooltip on the disabled buttons with an explanation of why it's disabled, but it seems I can't disable the button without disabling the tooltip. Is there a simple way around this?

A: Wrap the Button in a Group, and apply the toolTip to the group instead.
<s:Group toolTip="My toolTip">
    <s:Button enabled="false"/>
</s:Group>

It's a bit ugly, but it works.

A: One way to do this is to override the enabled getter and setter to do what you want. So in my case, I still wanted most mouse events to fire, just not the click event.
<?xml version="1.0" encoding="utf-8"?>
<s:Button buttonMode="true" click="handleClick(event)" xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:mx="library://ns.adobe.com/flex/mx" xmlns:s="library://ns.adobe.com/flex/spark">
    <fx:Script>
        <![CDATA[
            public var data:Object;
            private var _enabled:Boolean = true;

            public override function get enabled():Boolean
            {
                return _enabled;
            }

            public override function set enabled(value:Boolean):void
            {
                _enabled = value;
                invalidateDisplayList();
                dispatchEvent(new Event("enabledChanged"));
                invalidateSkinState();
            }

            protected function handleClick(event:MouseEvent):void
            {
                if (!_enabled)
                {
                    event.stopPropagation();
                }
            }
        ]]>
    </fx:Script>
</s:Button>

Since mouse events now fire, the tooltips work again.

A: <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Script>
        <![CDATA[
        import mx.managers.ToolTipManager;
        import mx.controls.ToolTip;
        private var tooltip:ToolTip;
        private var p:Point;

        private function whyDisable():void
        {

            //calculate the button position , so that roll over shows the tooltip
            p=new Point();
            p=localToGlobal(new Point(btn.x,btn.y));
            if(btn.enabled==false)
                tooltip = ToolTipManager.createToolTip('Button is disabled',p.x+(btn.width/2),p.y-20,'errorTipAbove') as ToolTip;
            else
                tooltip=ToolTipManager.createToolTip('Button is enabled',p.x+(btn.width/2),p.y-20,'errorTipAbove') as ToolTip;
        }
        ]]>
    </mx:Script>
    <mx:VBox height="100%" width="100%" horizontalAlign="center" verticalAlign="middle">
        <mx:Button id="btn" label="Show Tooltip" buttonDown="trace('ankur')" autoRepeat="true" enabled="true" rollOver="whyDisable();" rollOut="{ToolTipManager.destroyToolTip(tooltip);}"/>
    </mx:VBox>
</mx:Application>

Hi, this application works on the disabled button,I used ToolTipManager to do this,
i hope this works for you
have a gr8 time
Ankur Sharma

A: The best choice for me was to put a void label around and in front of the element. Then, if necessary, I set the element to disable and the tooltip works in the label. If not, I put sent the label to back. It works pretty well.
if (new MainListsAdmin(this.mainApp).temInvestimentoComAqueleTipo(t)) {
            deletarGroupInto.setTooltip(new Tooltip("Há investimentos vinculados a Tipo de Investimento.\nDeleção bloqueada."));
            this.deletarButton.setDisable(true);
}else{
        deletarGroupInto.toBack();
}

A: You will need to use the ToolTipManager class to create and destroy the tool tips manually.
This article should give you all the info you need to accomplish this:
http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf60d65-7ff6.html


text:
Q: Unable to remove space between header and slider section in wordpress website I am creating a wordpress website (colorsplash.info/vinovekitchenware/). Currently I am stuck with the following problem: i want to remove the white space between the header and the slider. After spending 2 to 3 hours, i am still unable to remove the space between these two section of div.
Here is the div section:
header id="header" class="col-full parent">  // it contains header section
section id="main" class="col-left">  // it contains slider section
Please help me!!

A: It is difficult to say what can be your problem here ans there are tons of reasons why this can be happening. I can suggest you to copy your html and css and create a codepen or a js fiddle and update your answer with the link to your code. This way anyone can take a look the problem you have and help you.

A: I usually won't do 'live-review' but in this case I couldn't resist to take a quick look at the problem 'on location'. And there are actually a couple of reasons for the white space – at least I found these two so far:

*

*Your header has a margin-bottom of 0.631em in line 585 of your stylesheet. Remove that or set it to 0 and some white space will disappear.

*The article post-33 has an empty header with an empty headline h1 inside, which sits right above the slider. Remove that header and you'll win another 15px or so (not tested, but should work: .post-33 header { display:none; } )
The above two measures should reduce the gap to approximately 5px. There should be at least a third reason for the remaining 5px which you'll probably find once you take a deeper look at what's going on (I recommend firebug or the like).
Update: the remaining 5px are actually part of the images presented in the slider! Crop the images properly, and the remaining 5px will probably be gone.
Here's a quick screenshot of the gap after I 'fixed' the two issues in firebug:


text:
Q: Quickblox: ClassDefNotFoundError : Smack.smackAndroid in video chat I have used this link to preform videoChat.However, it gives me  java.lang.NoClassDefFoundError which cannot locate : com.quickblox.module.chat.smack.SmackAndroid class .I tried changing the preferences of libraries but din't helped.
Here is the log:
03-22 18:14:21.476: I/dalvikvm(9908): Could not find method com.quickblox.module.chat.smack.SmackAndroid.init, referenced from method com.quickblox.videochatsample.ui.App.onCreate
03-22 18:14:21.476: W/dalvikvm(9908): VFY: unable to resolve static method 50: Lcom/quickblox/module/chat/smack/SmackAndroid;.init (Landroid/content/Context;)Lcom/quickblox/module/chat/smack/SmackAndroid;
03-22 18:14:21.476: D/dalvikvm(9908): VFY: replacing opcode 0x71 at 0x0003
03-22 18:14:21.481: D/AndroidRuntime(9908): Shutting down VM
03-22 18:14:21.481: W/dalvikvm(9908): threadid=1: thread exiting with uncaught exception (group=0x41927700)
03-22 18:14:21.486: E/AndroidRuntime(9908): FATAL EXCEPTION: main
03-22 18:14:21.486: E/AndroidRuntime(9908): java.lang.NoClassDefFoundError: com.quickblox.module.chat.smack.SmackAndroid
03-22 18:14:21.486: E/AndroidRuntime(9908):     at com.quickblox.videochatsample.ui.App.onCreate(App.java:13)
03-22 18:14:21.486: E/AndroidRuntime(9908):     at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1024)
03-22 18:14:21.486: E/AndroidRuntime(9908):     at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4684)
03-22 18:14:21.486: E/AndroidRuntime(9908):     at android.app.ActivityThread.access$1400(ActivityThread.java:159)
03-22 18:14:21.486: E/AndroidRuntime(9908):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1376)
03-22 18:14:21.486: E/AndroidRuntime(9908):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-22 18:14:21.486: E/AndroidRuntime(9908):     at android.os.Looper.loop(Looper.java:137)
03-22 18:14:21.486: E/AndroidRuntime(9908):     at android.app.ActivityThread.main(ActivityThread.java:5419)
03-22 18:14:21.486: E/AndroidRuntime(9908):     at java.lang.reflect.Method.invokeNative(Native Method)
03-22 18:14:21.486: E/AndroidRuntime(9908):     at java.lang.reflect.Method.invoke(Method.java:525)
03-22 18:14:21.486: E/AndroidRuntime(9908):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
03-22 18:14:21.486: E/AndroidRuntime(9908):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
03-22 18:14:21.486: E/AndroidRuntime(9908):     at dalvik.system.NativeStart.main(Native Method)

A: go to build path and click on add external jar and add quickbox-android-1.2.2.jar
and go to Order and Export tab and check jarfile checkbox.and clean and rebuild project thats it...